Skip to content

Instantly share code, notes, and snippets.

@SOF3
Last active February 5, 2022 14:11
Show Gist options
  • Save SOF3/aacfc96e98ef6a77095097e1d4fbc710 to your computer and use it in GitHub Desktop.
Save SOF3/aacfc96e98ef6a77095097e1d4fbc710 to your computer and use it in GitHub Desktop.
fn main() {
let mut world = dynec::World::default();
world.schedule(run);
let farm = world.create::<Node>(
None,
dynec::component_initials![
@CROPS => Capacity(100),
@CROPS => Volume(50),
],
);
let factory = world.create::<Node>(
None,
dynec::component_initials![
@CROPS => Capacity(100),
@FOOD => Capacity(100),
@FOOD => Volume(100),
],
);
let market = world.create::<Node>(
None,
dynec::component_initials![
@FOOD => Capacity(200),
],
);
// TODO add edges
assert_eq!(
world.get_multi::<Node, Capacity, _, _>(CROPS, farm, |x| *x),
Some(Capacity(100))
);
}
#[derive(dynec::Archetype)]
enum Node {}
/// Identifies an item type.
struct ItemType(usize);
const CROPS: ItemType = ItemType(0);
const FOOD: ItemType = ItemType(1);
impl From<usize> for ItemType {
fn from(id: usize) -> Self {
ItemType(id)
}
}
impl From<ItemType> for usize {
fn from(id: ItemType) -> Self {
id.0
}
}
/// A component storing the position of an object.
#[derive(Debug, Clone, Copy, PartialEq, dynec::Component)]
#[component(of = Node, required)]
struct Position([f32; 3]);
/// A component storing the item capacity of a node.
#[derive(Debug, Clone, Copy, PartialEq, dynec::Component)]
#[component(of = Node, multi = ItemType, required)]
struct Capacity(u32);
/// A component storing the item volume in a node.
#[derive(Debug, Clone, Copy, PartialEq, Default, dynec::Component)]
#[component(of = Node, multi = ItemType, default)]
struct Volume(u32);
#[derive(dynec::Archetype)]
enum Edge {}
#[derive(dynec::Component)]
#[component(of = Edge, required)]
struct Endpoints(dynec::Entity<Node>, dynec::Entity<Node>);
#[derive(Debug, Clone, Copy, PartialEq, dynec::Component)]
#[component(of = Edge, multi = ItemType, required)]
struct Flow(u32);
#[derive(Debug, Clone, Copy, PartialEq, dynec::Component)]
#[component(of = Edge, required)]
struct Power(u32);
#[dynec::system(
read(Edge; Flow, Power, Endpoints),
read(Node: Capacity),
write(Node: Volume),
)]
fn run(ctx: _) {
for edge in dynec::join!(context, Edge; Flow, Power, Endpoints) {
let &Endpoints(src, dest) = edge.get::<Endpoints>();
let power = edge.get::<Power>();
for (item, flow) in edge.get_multi::<Flow>() {
let mut delta = flow.0 * power.0;
delta = cmp::min(delta, ctx.get_multi::<Node, Volume>(item, src));
delta = cmp::min(delta, ctx.get_multi::<Node, Capacity>(item, dest) - ctx.get_multi::<Node, Volume>(item, dest));
*ctx.get_multi_mut::<Node, Volume>(item, src) -= delta;
*ctx.get_multi_mut::<Node, Volume>(item, dest) += delta;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment