Skip to content

Instantly share code, notes, and snippets.

@PsichiX
Created February 24, 2024 00:06
Show Gist options
  • Save PsichiX/39551a57dcebd5cbba10c60097894876 to your computer and use it in GitHub Desktop.
Save PsichiX/39551a57dcebd5cbba10c60097894876 to your computer and use it in GitHub Desktop.
Intuicio with hecs example
use hecs::World;
use intuicio_core::prelude::*;
use intuicio_data::{
lifetime::Lifetime,
managed::{ManagedRef, ManagedRefMut},
};
use intuicio_derive::*;
#[derive(IntuicioStruct, Default)]
struct Health {
value: usize,
}
#[derive(IntuicioStruct, Default)]
struct Damage {
value: usize,
}
// imagine this system function comes from script, not native side.
#[intuicio_function(module_name = "test", transformer = "ManagedValueTransformer")]
fn deal_damage(health: &mut Health, damage: &Damage) {
health.value = health.value.saturating_sub(damage.value);
}
#[test]
fn test_ecs() {
let mut context = Context::new(1024, 1024, 1024);
let mut registry = Registry::default().with_basic_types();
registry.add_struct(NativeStructBuilder::new_uninitialized::<ManagedRefMut<Health>>().build());
registry.add_struct(NativeStructBuilder::new_uninitialized::<ManagedRef<Damage>>().build());
// imagine this system function gets installed from script, not native side.
let deal_damage = registry.add_function(deal_damage::define_function(&registry));
let mut world = World::new();
let entity = world.spawn((Health { value: 100 }, Damage { value: 42 }));
world.spawn((Health { value: 100 },));
world.spawn((Damage { value: 42 },));
assert_eq!(world.get::<&Health>(entity).unwrap().value, 100);
for (_, (health, damage)) in world.query::<(&mut Health, &Damage)>().iter() {
let health_lifetime = Lifetime::default();
let damage_lifetime = Lifetime::default();
deal_damage.call::<(), _>(
&mut context,
&registry,
(
ManagedRefMut::new(health, health_lifetime.borrow_mut().unwrap()),
ManagedRef::new(damage, damage_lifetime.borrow().unwrap()),
),
false,
);
}
assert_eq!(world.get::<&Health>(entity).unwrap().value, 58);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment