Skip to content

Instantly share code, notes, and snippets.

@techgeek1
Created September 12, 2018 00:32
Show Gist options
  • Save techgeek1/a97c3dd173a8e5d5f2c9d47f474129dc to your computer and use it in GitHub Desktop.
Save techgeek1/a97c3dd173a8e5d5f2c9d47f474129dc to your computer and use it in GitHub Desktop.
Attempt at one API for ECS system/component declaration
use std::any::TypeId;
macro_rules! depends_on {
($($type:ty),*) => {
fn dependencies(&self) -> &'static [TypeId] {
$(<$type as System>::__assert_is_system();)*
&[$(TypeId::of::<$type>()),*]
}
}
}
macro_rules! reads {
($($type:ty),*) => {
fn reads(&self) -> &'static [TypeId] {
$(<$type as Component>::__assert_is_component();)*
&[$(TypeId::of::<$type>()),*]
}
}
}
macro_rules! writes {
($($type:ty),*) => {
fn writes(&self) -> &'static [TypeId] {
$(<$type as Component>::__assert_is_component();)*
&[$(TypeId::of::<$type>()),*]
}
}
}
trait System {
fn dependencies(&self) -> &'static [TypeId];
fn reads(&self) -> &'static [TypeId];
fn writes(&self) -> &'static [TypeId];
fn __assert_is_system() {}
}
trait Component {
fn __assert_is_component() {}
}
struct CompA;
struct CompB;
struct CompC;
struct CompD;
impl Component for CompA { }
impl Component for CompB { }
impl Component for CompC { }
impl Component for CompD { }
struct SysA;
struct SysB;
struct SysC;
struct SysD;// Invalid
impl System for SysA {
depends_on!();
reads!();
writes!(CompD);
}
impl System for SysB {
depends_on!(SysA);
reads!(CompA);
writes!();
}
impl System for SysC {
depends_on!(SysB, SysC);
reads!(CompB);
writes!(CompC);
}
impl System for SysD {
depends_on!(SysA);
reads!(CompC, CompD);
writes!();
}
fn main() {
let a = SysA {};
let b = SysB {};
let c = SysC {};
let d = SysD {};
print_sys("SysA", &a);
print_sys("SysB", &b);
print_sys("SysC", &c);
print_sys("SysD", &d);
}
fn print_sys<T>(name: &str, sys: &T)
where T: System + Sized
{
println!(
"{} -\n deps {:?}\n reads {:?}\n writes {:?}",
name,
sys.dependencies(),
sys.reads(),
sys.writes()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment