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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#![warn(missing_docs)]

//! Axle is inspired by Processing

extern crate sdl2;
#[macro_use]
#[cfg(feature = "toml_cfg")]
extern crate serde_derive;
#[cfg(feature = "toml_cfg")]
extern crate toml;

mod prelude;
pub use prelude::*;

#[derive(Debug)]
/// Enum of the various drawable types
enum Drawable {
    /// Start, End, Color
    Line(Point, Point, Color),
    /// Top Left, Width, Height, Color
    Rect(Point, u32, u32, Color),
    /// P1, P2, P3, P4, Color
    Quad(Point, Point, Point, Point, Color),
    /// Top Left, Bottom Right, Corner Radius, Color
    RoundedRect(Point, Point, i16, Color),
    /// Centre, radius-x, radius-y, start(rad), end(rad), point_count, Color
    Arc(Point, i16, i16, f64, f64, i16, Color),
    /// Centre, radius-x, radius-y, point_count, color
    Ellipse(Point, i16, i16, i16, Color),
    Pixel(Point, Color),
}

impl Drawable {
    fn draw(&self, canvas: &mut sdl2::render::Canvas<sdl2::video::Window>) {
        match *self {
            Drawable::Line(point1, point2, c) => {
                canvas.set_draw_color(c);
                canvas
                    .draw_line(point1, point2)
                    .expect("Failed to draw line");
            }
            Drawable::Rect(top_left, width, height, c) => {
                canvas.set_draw_color(c);
                canvas
                    .draw_rect(Rect::new(top_left.x(), top_left.y(), width, height))
                    .expect("Failed to draw Rect");
            }
            Drawable::Quad(point1, point2, point3, point4, c) => {
                canvas.set_draw_color(c);
                canvas
                    .draw_line(point1, point2)
                    .expect("Failed to draw Quad");
                canvas
                    .draw_line(point2, point3)
                    .expect("Failed to draw Quad");
                canvas
                    .draw_line(point3, point4)
                    .expect("Failed to draw Quad");
                canvas
                    .draw_line(point4, point1)
                    .expect("Failed to draw Quad");
            }
            Drawable::RoundedRect(p1, p2, r, c) => unimplemented!(),
            Drawable::Ellipse(center, radius_x, radius_y, point_count, c) => {
                canvas.set_draw_color(c);
                Drawable::draw_arc(
                    canvas,
                    center,
                    radius_x,
                    radius_y,
                    0.0,
                    PI * 2.0,
                    point_count,
                )
            }
            Drawable::Arc(center, radius_x, radius_y, start, end, point_count, c) => {
                canvas.set_draw_color(c);
                Drawable::draw_arc(canvas, center, radius_x, radius_y, start, end, point_count)
            }
            Drawable::Pixel(point, c) => {
                canvas.set_draw_color(c);
                canvas.draw_point(point).expect("Failed to draw Pixel");
            }
        };
    }

    fn draw_arc(
        canvas: &mut sdl2::render::Canvas<sdl2::video::Window>,
        center: Point,
        radius_x: i16,
        radius_y: i16,
        start: f64,
        end: f64,
        point_count: i16,
    ) {
        let step = (start - end) / f64::from(point_count);
        let (mut prev_x, mut prev_y) = (
            -(start.sin() * (radius_x as f64)),
            -(start.cos() * (radius_y as f64)),
        );
        for i in 1..(point_count + 1) {
            let (new_x, new_y) = (
                -(start + f64::from(i) * step).sin() * f64::from(radius_x),
                -(start + f64::from(i) * step).cos() * f64::from(radius_y),
            );
            canvas
                .draw_line(
                    Point::new(center.x() + prev_x as i32, center.y() + prev_y as i32),
                    Point::new(center.x() + new_x as i32, center.y() + new_y as i32),
                )
                .expect("Failed to draw arc");
            prev_x = new_x;
            prev_y = new_y;
        }
    }
}

use std::collections::HashMap;

pub type ItemID = u64;

/// The main type for the crate
pub struct Axle {
    /// The canvas that everything is drawn onto
    canvas: sdl2::render::Canvas<sdl2::video::Window>,
    /// Event pump for receiving user input
    event_pump: sdl2::EventPump,
    /// All the items that are drawable
    items: HashMap<u64, Drawable>,
    /// Background color
    background: Color,
    /// Whether the pen is down or not
    pen_down: bool,
    /// Counter for the current item id
    item_id: ItemID,
}

impl Default for Axle {
    fn default() -> Self {
        Self::new(&Config::default())
    }
}

use std::thread;
use std::time::Duration;

impl Axle {
    pub fn new(cfg: &Config) -> Axle {
        let ctx = sdl2::init().expect("Error initialising SDL2");
        let video_subsystem = ctx.video().expect("Error initialising video subsystem");

        let window = video_subsystem
            .window(&cfg.title, cfg.width, cfg.height)
            .position_centered()
            .build()
            .expect("Error building window");

        let mut canvas = window.into_canvas().build().expect("Error building canvas");
        canvas.set_draw_color(Color::RGB(0, 0, 0));
        let event_pump = ctx.event_pump().expect("Error getting event pump");
        Axle {
            canvas,
            event_pump,
            items: HashMap::new(),
            pen_down: true,
            background: Color::RGB(0, 0, 0),
            item_id: 0,
        }
    }

    pub fn set_draw_color(&mut self, color: Color) {
        self.canvas.set_draw_color(color)
    }

    pub fn background(&mut self, color: Color) {
        self.background = color;
    }

    pub fn line(&mut self, point1: Point, point2: Point) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Line(point1, point2, self.canvas.draw_color()),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn rect(&mut self, top_left: Point, width: u32, height: u32) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Rect(top_left, width, height, self.canvas.draw_color()),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn quad(
        &mut self,
        point1: Point,
        point2: Point,
        point3: Point,
        point4: Point,
    ) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Quad(point1, point2, point3, point4, self.canvas.draw_color()),
            );
            return Some(self.item_id);
        }
        None
    }

    // pub fn rounded_rect(&mut self, x: i16, y: i16, w: i16, h: i16, r: i16) -> Option<ItemID> {
    //     if self.pen_down {
    //         self.item_id += 1;
    //         self.items.insert(
    //             self.item_id,
    //             Drawable::RoundedRect(x, y, w, h, r, self.canvas.draw_color()),
    //         );
    //         return Some(self.item_id);
    //     }
    //     None
    // }

    pub fn ellipse(&mut self, center: Point, radius_x: i16, radius_y: i16) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Ellipse(center, radius_x, radius_y, 36, self.canvas.draw_color()),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn circle(&mut self, center: Point, radius: i16) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Ellipse(center, radius, radius, 36, self.canvas.draw_color()),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn regular_ngon(&mut self, center: Point, radius: i16, point_count: i16) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Ellipse(
                    center,
                    radius,
                    radius,
                    point_count,
                    self.canvas.draw_color(),
                ),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn ellipsoidal_ngon(
        &mut self,
        center: Point,
        radius_x: i16,
        radius_y: i16,
        point_count: i16,
    ) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Ellipse(
                    center,
                    radius_x,
                    radius_y,
                    point_count,
                    self.canvas.draw_color(),
                ),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn circle_arc(
        &mut self,
        center: Point,
        radius: i16,
        start: f64,
        end: f64,
    ) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Arc(
                    center,
                    radius,
                    radius,
                    start,
                    end,
                    36,
                    self.canvas.draw_color(),
                ),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn ellipse_arc(
        &mut self,
        center: Point,
        radius_x: i16,
        radius_y: i16,
        start: f64,
        end: f64,
    ) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Arc(
                    center,
                    radius_x,
                    radius_y,
                    start,
                    end,
                    36,
                    self.canvas.draw_color(),
                ),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn n_point_ellipse_arc(
        &mut self,
        center: Point,
        radius_x: i16,
        radius_y: i16,
        start: f64,
        end: f64,
        point_count: i16,
    ) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Arc(
                    center,
                    radius_x,
                    radius_y,
                    start,
                    end,
                    point_count,
                    self.canvas.draw_color(),
                ),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn set_pixel(&mut self, point: Point) -> Option<ItemID> {
        if self.pen_down {
            self.item_id += 1;
            self.items.insert(
                self.item_id,
                Drawable::Pixel(point, self.canvas.draw_color()),
            );
            return Some(self.item_id);
        }
        None
    }

    pub fn mouse_pos(&self) -> (i32, i32) {
        let mouse_state = sdl2::mouse::MouseState::new(&self.event_pump);
        (mouse_state.x(), mouse_state.y())
    }

    pub fn mouse_pressed(&self, button: MouseButton) -> bool {
        let mouse_state = sdl2::mouse::MouseState::new(&self.event_pump);
        mouse_state.is_mouse_button_pressed(button)
    }

    pub fn keyboard_pressed(&self, key: Key) -> bool {
        let keyboard_state = sdl2::keyboard::KeyboardState::new(&self.event_pump);
        keyboard_state.is_scancode_pressed(key)
    }

    pub fn draw(&mut self) {
        let c = self.canvas.draw_color();
        self.canvas.set_draw_color(self.background);
        self.canvas.clear();
        self.canvas.set_draw_color(c);
        for item in self.items.values() {
            item.draw(&mut self.canvas)
        }
        self.canvas.present();
    }

    pub fn sleep(&self, time: f64) {
        thread::sleep(Duration::from_millis((time * 1_000.0) as u64))
    }

    pub fn sleep_ms(&self, time: u64) {
        thread::sleep(Duration::from_millis(time))
    }

    pub fn fps(&self, fps: f64) -> f64 {
        1.0 / fps
    }

    pub fn events(&mut self) -> Vec<Event> {
        self.event_pump.poll_iter().collect()
    }

    pub fn wait_event(&mut self) -> Event {
        self.event_pump.wait_event()
    }

    pub fn clear(&mut self) {
        self.items.clear()
    }

    pub fn remove(&mut self, item_id: ItemID) {
        self.items.remove(&item_id);
    }

    pub fn pen_down(&mut self) {
        self.pen_down = true;
    }

    pub fn pen_up(&mut self) {
        self.pen_down = false;
    }

    pub fn size(&self) -> (u32, u32) {
        self.canvas
            .output_size()
            .expect("Error getting output size")
    }
}

#[cfg_attr(feature = "toml_cfg", derive(Serialize, Deserialize))]
/// Config files
pub struct Config {
    /// Wdith of the window
    pub width: u32,
    /// Height of the window
    pub height: u32,
    /// Title of the window
    pub title: String,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            width: 640,
            height: 480,
            title: String::from("Axle"),
        }
    }
}

#[cfg(feature = "toml_cfg")]
use std::fs::File;
#[cfg(feature = "toml_cfg")]
use std::io::{Read, Write};

impl Config {
    #[cfg(feature = "toml_cfg")]
    pub fn from_toml(path: &str) -> Config {
        let mut file = File::open(path).expect("Error opening file");
        let mut buf = String::new();
        file.read_to_string(&mut buf)
            .expect("Error reading to string");
        toml::from_str(&buf).expect("Error deserialising toml")
    }

    #[cfg(feature = "toml_cfg")]
    pub fn export_toml(&self, path: &str) {
        let s = toml::to_string(self).expect("Error serialing to toml");
        let mut file = File::create(path).expect("Error creating file");
        file.write_all(s.as_bytes()).expect("Error writing to file");
    }
}