Created
September 18, 2018 17:11
-
-
Save techgeek1/0bbaba0977600679fd1ff8154746fb85 to your computer and use it in GitHub Desktop.
Testing ideas for iterating the intersection of entities with a specified subset of components in a system
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rand; // 0.5.5 | |
use std::default::Default; | |
use rand; | |
macro_rules! declare_components { | |
($($name:ident),*) => { | |
$( | |
struct $name { | |
pub value: i32 | |
} | |
impl $name { | |
fn new() -> Self { | |
$name { | |
value: rand::random::<i32>() | |
} | |
} | |
} | |
impl Default for $name { | |
fn default() -> $name { | |
$name::new() | |
} | |
} | |
)* | |
} | |
} | |
declare_components!(CompA, CompB, CompC, CompD); | |
type DataItem = (CompA, CompB, CompC, CompD); | |
type Data<'a> = (&'a [CompA], &'a [CompB], &'a [CompC], &'a [CompD]); | |
struct DataIter<'a> { | |
data: &'a Data<'a>, | |
index: usize | |
} | |
impl<'a> DataIter<'a> { | |
fn new(data: &Data<'a>) -> Self { | |
DataIter { | |
data: data, | |
index: 0 | |
} | |
} | |
} | |
impl<'a> Iterator for DataIter<'a> { | |
type Item = DataItem; | |
fn next(&mut self) -> Option<Self::Item> { | |
if index > self.data.0.len() { | |
return None; | |
} | |
let item = ( | |
self.data.0[index], | |
self.data.1[index], | |
self.data.2[index], | |
self.data.3[index] | |
); | |
index += 1; | |
item | |
} | |
} | |
fn main() { | |
let num_components = 512; | |
let a = create_vec<CompA>(num_components); | |
let b = create_vec<CompB>(num_components); | |
let c = create_vec<CompC>(num_components); | |
let d = create_vec<CompD>(num_components); | |
let data = (&a, &b, &c, &d); | |
let iter = DataIter::new(data); | |
for (a, b, c, d) in iter { | |
println!("Results ({:?}, {:?}, {:?}, {:?})", a, b, c, d); | |
} | |
} | |
fn create_vec<T>(capacity: usize) -> Vec<T> { | |
let vec = Vec::with_capacity::<T>(capacity); | |
for i in 0..capacity { | |
vec.push(Default::default::<T>()); | |
} | |
vec | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment