WIP: Wall intersection
[kaka/rust-sdl-test.git] / src / core / level / mod.rs
index 3945776..2a90739 100644 (file)
@@ -1,4 +1,4 @@
-use common::{Point, Dimension};
+use common::{Point, Dimension, Intersection};
 use core::render::Renderer;
 use sprites::SpriteManager;
 use std::rc::Rc;
@@ -96,6 +96,26 @@ impl Level {
            }
        }
     }
+
+    pub fn intersect_walls(&self, p1: Point<f64>, p2: Point<f64>) -> IntersectResult {
+       let c = point!(p2.x as isize / self.wall_grid.cell_size.width as isize, p2.y as isize / self.wall_grid.cell_size.height as isize);
+       if let Some(walls) = self.wall_grid.at(c) {
+           for w in walls {
+               if let Intersection::Point(p) = Intersection::lines(p1, p2, w.p1, w.p2) {
+                   let wall = Wall {
+                       edge: Rc::clone(&w),
+                   };
+                   return IntersectResult::Intersection(wall, p)
+               }
+           }
+       }
+       IntersectResult::None
+    }
+}
+
+pub enum IntersectResult {
+    Intersection(Wall, Point<f64>),
+    None
 }
 
 ////////// GRID ////////////////////////////////////////////////////////////////
@@ -107,6 +127,19 @@ pub struct Grid<T> {
     pub cells: Vec<Vec<T>>,
 }
 
+impl<T> Grid<T> {
+    pub fn at<C>(&self, c: C) -> Option<&T>
+    where C: Into<(isize, isize)>
+    {
+       let c = c.into();
+       if c.0 >= 0 && c.0 < self.size.width as isize && c.1 >= 0 && c.1 < self.size.height as isize {
+           Some(&self.cells[c.0 as usize][c.1 as usize])
+       } else {
+           None
+       }
+    }
+}
+
 ////////// WALL REGION /////////////////////////////////////////////////////////
 
 #[derive(Debug)]
@@ -116,7 +149,7 @@ pub struct WallRegion {
 
 impl WallRegion {
     pub fn new(points: Vec<Point<f64>>) -> Rc<Self> {
-       let mut edges = vec!();
+       let mut edges = Vec::with_capacity(points.len());
 
        for i in 0..points.len() {
            let edge = Rc::new(WallEdge {
@@ -151,3 +184,10 @@ struct WallEdge {
     pub p1: Point<f64>,
     pub p2: Point<f64>,
 }
+
+////////// WALL ////////////////////////////////////////////////////////////////
+
+pub struct Wall {
+//    region: Rc<WallRegion>,
+    edge: Rc<WallEdge>,
+}