Fix DeferredSystem unsafety

This commit is contained in:
JMS55 2023-12-07 12:04:06 -08:00
parent 92c97b44e4
commit 3232fb392a
3 changed files with 9 additions and 30 deletions

View file

@ -6,7 +6,7 @@ use bevy::ecs::{
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct DeferredSystem { pub struct DeferredSystem {
id: SystemId, id: SystemId,
world: *mut World, run_queue: *mut Vec<SystemId>,
} }
impl DeferredSystem { impl DeferredSystem {
@ -15,33 +15,18 @@ impl DeferredSystem {
S: IntoSystem<(), (), ()> + 'static, S: IntoSystem<(), (), ()> + 'static,
{ {
Self { Self {
id: world.register_system(system), id: world.register_system(system), // TODO: We never unregister the system
world, run_queue: Box::as_mut(&mut world.resource_mut::<DeferredSystemRunQueue>().0),
} }
} }
pub fn schedule(&self) { pub fn schedule(&self) {
// TODO: This is not sound. Pointer to world won't be valid across frames. unsafe { &mut *self.run_queue }.push(self.id);
unsafe { &mut *self.world }
.resource_mut::<DeferredSystemRunQueue>()
.0
.push(self.id);
} }
} }
unsafe impl Send for DeferredSystem {} unsafe impl Send for DeferredSystem {}
unsafe impl Sync for DeferredSystem {} unsafe impl Sync for DeferredSystem {}
pub struct OnDropUnregisterDeferredSystem(pub DeferredSystem); #[derive(Resource, Clone, Default)]
pub struct DeferredSystemRunQueue(pub Box<Vec<SystemId>>);
impl Drop for OnDropUnregisterDeferredSystem {
fn drop(&mut self) {
// TODO: This is not sound. Pointer to world won't be valid across frames.
unsafe { &mut *self.0.world }
.remove_system(self.0.id)
.unwrap();
}
}
#[derive(Resource, Default)]
pub struct DeferredSystemRunQueue(pub Vec<SystemId>);

View file

@ -1,7 +1,4 @@
use crate::{ use crate::{deferred_system::DeferredSystem, tick::EcsContext};
deferred_system::{DeferredSystem, OnDropUnregisterDeferredSystem},
tick::EcsContext,
};
use bevy::ecs::{ use bevy::ecs::{
system::{IntoSystem, Resource}, system::{IntoSystem, Resource},
world::World, world::World,
@ -29,10 +26,7 @@ impl DioxusUiHooks for ScopeState {
where where
S: IntoSystem<(), (), ()> + 'static, S: IntoSystem<(), (), ()> + 'static,
{ {
self.use_hook(|| { *self.use_hook(|| DeferredSystem::new(system, EcsContext::get_world(self)))
OnDropUnregisterDeferredSystem(DeferredSystem::new(system, EcsContext::get_world(self)))
})
.0
} }
} }

View file

@ -55,7 +55,7 @@ pub fn tick_dioxus_ui(world: &mut World) {
); );
} }
for system_id in mem::take(&mut world.resource_mut::<DeferredSystemRunQueue>().0) { for system_id in mem::take(&mut *world.resource_mut::<DeferredSystemRunQueue>().0) {
world.run_system(system_id).unwrap(); world.run_system(system_id).unwrap();
} }
} }