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

View file

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

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();
}
}