rust-pilot/src/game/map.rs

67 lines
2.1 KiB
Rust

use piston_window::*;
use piston_window::math::*;
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 0.05];
const GRID_SIZE: Scalar = 100.0;
pub struct Map {
pub width: Scalar,
pub height: Scalar
}
impl Map {
pub fn new(width: Scalar, height: Scalar) -> Self {
Map { width, height }
}
pub fn center(&self) -> Vec2d {
[self.width / 2.0, self.height / 2.0]
}
pub fn clamp(&self, other: Vec2d) -> Vec2d {
let x = other[0].max(0.0).min(self.width);
let y = other[1].max(0.0).min(self.height);
[x, y]
}
pub fn draw_grid<G>(&self,
cam_pos: Vec2d,
cam_size: Vec2d,
draw_state: &DrawState,
transform: Matrix2d,
g: &mut G)
where G: Graphics
{
/* Camera coordinates will be centered in the screen, so find the
upper left and lower right coordinates */
let min = sub(cam_pos, mul_scalar(cam_size, 0.5));
let max = add(cam_pos, mul_scalar(cam_size, 0.5));
/* Determine the number of grid lines to draw in each direction */
let xcount = (cam_size[0] / GRID_SIZE).ceil() as u32 + 1;
let ycount = (cam_size[1] / GRID_SIZE).ceil() as u32 + 1;
/* Clamp the line coordinates to multiples of the grid size */
let first_x = (min[0] / GRID_SIZE).trunc() * GRID_SIZE;
let first_y = (min[1] / GRID_SIZE).trunc() * GRID_SIZE;
/* Draw vertical grid lines */
for x in 0..xcount {
let line_x = first_x + (GRID_SIZE * Scalar::from(x));
let p1 = [line_x, min[1]];
let p2 = [line_x, max[1]];
Line::new(GREEN, 1.0)
.draw([p1[0], p1[1], p2[0], p2[1]], draw_state, transform, g);
}
/* Draw horizontal grid lines */
for y in 0..ycount {
let line_y = first_y + (GRID_SIZE * Scalar::from(y));
let p1 = [min[0], line_y];
let p2 = [max[0], line_y];
Line::new(GREEN, 1.0)
.draw([p1[0], p1[1], p2[0], p2[1]], draw_state, transform, g);
}
}
}