aboutsummaryrefslogtreecommitdiff
path: root/src/grid.rs
blob: ec27fa7ba4fa7339024740587d10f874382f8b18 (plain) (blame)
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
use crate::math::{self, Vec2};
use crate::transform::Transform;
use raylib::drawing::RaylibDraw;
use raylib::ffi::Color;

/// The internal grid length which will be used to snap things to it.
pub const SNAP_SIZE: f64 = 0.5;

pub const LINE_COLOUR: Color = Color {
    r: 255,
    g: 255,
    b: 255,
    a: 75,
};

/// Snap a vector to the grid with the factor being the sub-grid accuracy. For instance, 0.5 will
/// snap to half a grid cell, while 2.0 would snap to every second grid cell
pub fn snap_to_grid(mut vec: Vec2<f64>, snap_fraction: f64) -> Vec2<f64> {
    vec.x = math::round(vec.x, snap_fraction);
    vec.y = math::round(vec.y, snap_fraction);

    vec
}

/// Draw an infinite grid that can be moved around on the screen and zoomed in and out of.
pub fn draw_grid<D>(rld: &mut D, screen_width: i32, screen_height: i32, transform: &Transform)
where
    D: RaylibDraw,
{
    /* Calculate the first whole meter that can be seen on the grid. This is the first meter that
     * will be seen on screen.
     */
    let mut first_cell = *transform.translation_px() / -transform.pixels_per_m();
    first_cell.x = first_cell.x.floor();
    first_cell.y = first_cell.y.floor();

    let mut cell = first_cell;
    let mut draw_y = transform.point_m_to_px(&cell).y;
    loop {
        draw_y = math::round(draw_y, 1.);
        rld.draw_line(0, draw_y as i32, screen_width, draw_y as i32, LINE_COLOUR);
        cell.y += 1.;
        draw_y = transform.point_m_to_px(&cell).y;

        if draw_y as i32 > screen_height {
            break;
        }
    }

    let mut draw_x = transform.point_m_to_px(&cell).x;
    loop {
        draw_x = math::round(draw_x, 1.);
        rld.draw_line(draw_x as i32, 0, draw_x as i32, screen_height, LINE_COLOUR);
        cell.x += 1.;
        draw_x = transform.point_m_to_px(&cell).x;

        if draw_x as i32 > screen_width {
            break;
        }
    }
}