Skip to content

Commit

Permalink
Add helper to read entity
Browse files Browse the repository at this point in the history
Better encapsulates the unsafe code.
  • Loading branch information
Shatur committed Nov 15, 2024
1 parent d1491ac commit 0efa807
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,10 +322,7 @@ fn apply_init_components(
.entity_map
.get_by_server_or_insert(server_entity, || world.spawn(Replicated).id());

let world_cell = world.as_unsafe_world_cell();
// SAFETY: have write access and the cell used only to get entities.
let mut client_entity = unsafe { DeferredEntity::new(world_cell, client_entity) };
let mut commands = Commands::new_from_entities(params.queue, world_cell.entities());
let (mut client_entity, mut commands) = read_entity(world, params.queue, client_entity);
params
.entity_markers
.read(params.command_markers, &*client_entity);
Expand Down Expand Up @@ -432,10 +429,7 @@ fn apply_update_components(
continue;
};

let world_cell = world.as_unsafe_world_cell();
// SAFETY: have write access and the cell used only to get entities.
let mut client_entity = unsafe { DeferredEntity::new(world_cell, client_entity) };
let mut commands = Commands::new_from_entities(params.queue, world_cell.entities());
let (mut client_entity, mut commands) = read_entity(world, params.queue, client_entity);
params
.entity_markers
.read(params.command_markers, &*client_entity);
Expand Down Expand Up @@ -513,6 +507,20 @@ fn apply_update_components(
Ok(())
}

/// Splits world access into entity that disallows structural ECS changes and commands.
fn read_entity<'w, 's>(
world: &'w mut World,
queue: &'s mut CommandQueue,
client_entity: Entity,
) -> (DeferredEntity<'w>, Commands<'w, 's>) {
let world_cell = world.as_unsafe_world_cell();
// SAFETY: have write access and the cell used only to get entities.
let client_entity = unsafe { DeferredEntity::new(world_cell, client_entity) };
let commands = Commands::new_from_entities(queue, world_cell.entities());

(client_entity, commands)
}

/// Deserializes `entity` from compressed index and generation.
///
/// For details see
Expand Down

0 comments on commit 0efa807

Please sign in to comment.