Added class matrix

This commit is contained in:
Thomas Forgione 2018-10-03 15:50:37 +02:00
parent eaefcd3272
commit 4da27c5777
No known key found for this signature in database
GPG Key ID: 203DAEA747F48F41
2 changed files with 65 additions and 0 deletions

62
src/engine/math/mod.rs Normal file
View File

@ -0,0 +1,62 @@
use std::ops::{
Index,
IndexMut
};
/// A generic matrix type, useful for levels.
pub struct Matrix<T> {
/// The number of rows of the matrix.
rows: usize,
/// The number of cols of the matrix.
cols: usize,
/// The contained data in the matrix.
data: Vec<T>,
}
impl<T> Matrix<T> where T: Clone {
/// Creates a matrix from an element and duplicates it.
pub fn from_size(rows: usize, cols: usize, element: T) -> Matrix<T> {
Matrix {
rows: rows,
cols: cols,
data: vec![element; rows * cols],
}
}
}
impl<T> Matrix<T> {
/// Converts an a pair corresponding to the row and columns into an integer.
pub fn to_usize(&self, (row, col): (usize, usize)) -> usize {
self.cols * col + row
}
/// Returns the number of rows.
pub fn rows(&self) -> usize {
self.rows
}
/// Returns the number of columns.
pub fn cols(&self) -> usize {
self.cols
}
}
impl<T> Index<(usize, usize)> for Matrix<T> {
type Output = T;
fn index(&self, index: (usize, usize)) -> &T {
let index = self.to_usize(index);
&self.data[index]
}
}
impl<T> IndexMut<(usize, usize)> for Matrix<T> {
fn index_mut(&mut self, index: (usize, usize)) -> &mut T {
let index = self.to_usize(index);
&mut self.data[index]
}
}

View File

@ -10,3 +10,6 @@ pub mod controls;
/// This module helps us dealing with textures.
pub mod texture;
/// This module contains the math tools that will be used.
pub mod math;