add missing event handlers, use common_ecs::System

This commit is contained in:
Isse 2024-02-07 12:21:04 +01:00
parent e94c21daa6
commit 857d924979
6 changed files with 65 additions and 96 deletions

View File

@ -493,6 +493,7 @@ fn handle_drop_all(
pos.0.y + rng.gen_range(5.0..10.0),
pos.0.z + 5.0,
)),
comp::Ori::default(),
comp::Vel(vel),
item,
None,

View File

@ -12,9 +12,9 @@ use common::{
WaypointArea,
},
event::{
CreateNpcEvent, CreateShipEvent, CreateTeleporterEvent, CreateWaypointEvent, EventBus,
InitializeCharacterEvent, InitializeSpectatorEvent, ShockwaveEvent, ShootEvent,
UpdateCharacterDataEvent,
CreateItemDropEvent, CreateNpcEvent, CreateObjectEvent, CreateShipEvent,
CreateTeleporterEvent, CreateWaypointEvent, EventBus, InitializeCharacterEvent,
InitializeSpectatorEvent, ShockwaveEvent, ShootEvent, UpdateCharacterDataEvent,
},
mounting::{Mounting, Volume, VolumeMounting, VolumePos},
outcome::Outcome,
@ -431,3 +431,34 @@ pub fn handle_create_teleporter(server: &mut Server, ev: CreateTeleporterEvent)
.create_teleporter(comp::Pos(ev.0), ev.1)
.build();
}
pub fn handle_create_item_drop(server: &mut Server, ev: CreateItemDropEvent) {
println!("Handle item drop event.");
dbg!(ev.vel);
server
.state
.create_item_drop(ev.pos, ev.ori, ev.vel, ev.item, ev.loot_owner);
}
pub fn handle_create_object(
server: &mut Server,
CreateObjectEvent {
pos,
vel,
body,
object,
item,
light_emitter,
stats,
}: CreateObjectEvent,
) {
server
.state
.create_object(pos, body)
.with(vel)
.maybe_with(object)
.maybe_with(item)
.maybe_with(light_emitter)
.maybe_with(stats)
.build();
}

View File

@ -6,9 +6,11 @@ use crate::{
skillset::SkillGroupKind,
BuffKind, BuffSource, PhysicsState,
},
error,
rtsim::RtSim,
state_ext::StateExt,
sys::terrain::SAFE_ZONE_RADIUS,
Settings, SpawnPoint,
Server, Settings, SpawnPoint,
};
use common::{
combat,
@ -60,14 +62,13 @@ use tracing::{debug, warn};
use vek::{Vec2, Vec3};
use world::World;
use super::{event_dispatch, trade::notify_agent_simple, ServerEvent};
use super::{event_dispatch, ServerEvent};
pub(super) fn register_event_systems(builder: &mut DispatcherBuilder) {
event_dispatch::<PoiseChangeEvent>(builder);
event_dispatch::<HealthChangeEvent>(builder);
event_dispatch::<KnockbackEvent>(builder);
event_dispatch::<DestroyEvent>(builder);
event_dispatch::<DeleteEvent>(builder);
event_dispatch::<LandOnGroundEvent>(builder);
event_dispatch::<RespawnEvent>(builder);
event_dispatch::<ExplosionEvent>(builder);
@ -89,6 +90,13 @@ pub(super) fn register_event_systems(builder: &mut DispatcherBuilder) {
event_dispatch::<StartTeleportingEvent>(builder);
}
pub fn handle_delete(server: &mut Server, DeleteEvent(entity): DeleteEvent) {
let _ = server
.state_mut()
.delete_entity_recorded(entity)
.map_err(|e| error!(?e, ?entity, "Failed to delete destroyed entity"));
}
#[derive(Hash, Eq, PartialEq)]
enum DamageContrib {
Solo(EcsEntity),
@ -625,14 +633,14 @@ impl ServerEvent for DestroyEvent {
let mut item_offset_spiral =
Spiral2d::new().map(|offset| offset.as_::<f32>() * 0.5);
let mut rng = rand::thread_rng();
let mut spawn_item = |item, loot_owner| {
let offset = item_offset_spiral.next().unwrap_or_default();
// TODO: convert
create_item_drop.emit(CreateItemDropEvent {
pos: Pos(pos.0 + Vec3::unit_z() * 0.25 + offset),
vel: vel.copied().unwrap_or(comp::Vel(Vec3::zero())),
// TODO: Random
ori: comp::Ori::default(),
ori: comp::Ori::from(Dir::random_2d(&mut rng)),
item,
loot_owner: if let Some(loot_owner) = loot_owner {
debug!(
@ -737,86 +745,6 @@ impl ServerEvent for DestroyEvent {
}
}
/// Delete an entity without any special actions (this is generally used for
/// temporarily unloading an entity when it leaves the view distance). As much
/// as possible, this function should simply make an entity cease to exist.
impl ServerEvent for DeleteEvent {
type SystemData<'a> = (
Entities<'a>,
Write<'a, comp::group::GroupManager>,
Write<'a, Trades>,
Read<'a, IdMaps>,
WriteStorage<'a, Group>,
WriteStorage<'a, Agent>,
ReadStorage<'a, Uid>,
ReadStorage<'a, Client>,
ReadStorage<'a, comp::MapMarker>,
ReadStorage<'a, Alignment>,
);
fn handle(
events: impl ExactSizeIterator<Item = Self>,
(
entities,
mut group_manager,
mut trades,
id_maps,
mut groups,
mut agents,
uids,
clients,
map_markers,
alignments,
): Self::SystemData<'_>,
) {
// TODO: Deal with duplication here and state_ext::delete_entity_recorded and
// called functions there.
for ev in events {
// Remove entity from a group if they are in one.
group_manager.entity_deleted(
ev.0,
&mut groups,
&alignments,
&uids,
&entities,
&mut |entity, group_change| {
clients
.get(entity)
.and_then(|c| {
group_change
.try_map_ref(|e| uids.get(*e).copied())
.map(|g| (g, c))
})
.map(|(g, c)| {
super::update_map_markers(&map_markers, &uids, c, &group_change);
c.send_fallible(ServerGeneral::GroupUpdate(g));
});
},
);
// Cancel trades
if let Some(uid) = uids.get(ev.0) {
let active_trade = match trades.entity_trades.get(uid) {
Some(n) => *n,
None => continue,
};
let to_notify = trades.decline_trade(active_trade, *uid);
to_notify.and_then(|u| id_maps.uid_entity(u)).map(|e| {
if let Some(c) = clients.get(e) {
c.send_fallible(ServerGeneral::FinishedTrade(TradeResult::Declined));
}
notify_agent_simple(
&mut agents,
e,
AgentEvent::FinishedTrade(TradeResult::Declined),
);
});
}
}
}
}
impl ServerEvent for LandOnGroundEvent {
type SystemData<'a> = (
Read<'a, Time>,

View File

@ -413,7 +413,6 @@ impl ServerEvent for InventoryManipEvent {
) + Vec3::one().with_z(0.0) * 0.5,
),
vel: comp::Vel(Vec3::zero()),
// TODO: Randomize
ori: data.orientations.get(entity).copied().unwrap_or_default(),
item,
loot_owner: Some(LootOwner::new(LootOwnerKind::Player(*uid), false)),

View File

@ -16,10 +16,11 @@ pub(crate) use trade::cancel_trades_for;
use self::{
entity_creation::{
handle_create_npc, handle_create_ship, handle_create_teleporter, handle_create_waypoint,
handle_initialize_character, handle_initialize_spectator, handle_loaded_character_data,
handle_shockwave, handle_shoot,
handle_create_item_drop, handle_create_npc, handle_create_object, handle_create_ship,
handle_create_teleporter, handle_create_waypoint, handle_initialize_character,
handle_initialize_spectator, handle_loaded_character_data, handle_shockwave, handle_shoot,
},
entity_manipulation::handle_delete,
interaction::handle_tame_pet,
mounting::{handle_mount, handle_mount_volume, handle_unmount},
player::{
@ -52,15 +53,18 @@ impl<T> Default for EventHandler<T> {
fn default() -> Self { Self(PhantomData) }
}
impl<'a, T: ServerEvent> specs::System<'a> for EventHandler<T> {
impl<'a, T: ServerEvent> common_ecs::System<'a> for EventHandler<T> {
type SystemData = (
ReadExpect<'a, crate::metrics::ServerEventMetrics>,
WriteExpect<'a, EventBus<T>>,
T::SystemData<'a>,
);
fn run(&mut self, (metrics, mut ev, data): Self::SystemData) {
span!(_guard, "Run event system {}", T::NAME);
const NAME: &'static str = T::NAME;
const ORIGIN: common_ecs::Origin = common_ecs::Origin::Server;
const PHASE: common_ecs::Phase = common_ecs::Phase::Apply;
fn run(_job: &mut common_ecs::Job<Self>, (metrics, mut ev, data): Self::SystemData) {
span!(guard, "Recv events");
let events = ev.recv_all_mut();
drop(guard);
@ -81,7 +85,7 @@ impl<'a, T: ServerEvent> specs::System<'a> for EventHandler<T> {
fn event_dispatch<T: ServerEvent>(builder: &mut DispatcherBuilder) {
// TODO: We currently don't consider the order of these event. But as
// some events produce other events that might be worth doing.
builder.add(EventHandler::<T>::default(), T::NAME, &[]);
common_ecs::dispatch::<EventHandler<T>>(builder, &[]);
}
pub fn register_event_systems(builder: &mut DispatcherBuilder) {
@ -136,6 +140,9 @@ impl Server {
self.handle_serial_events(handle_shockwave);
self.handle_serial_events(handle_create_waypoint);
self.handle_serial_events(handle_create_teleporter);
self.handle_serial_events(handle_create_item_drop);
self.handle_serial_events(handle_create_object);
self.handle_serial_events(handle_delete);
self.handle_serial_events(handle_character_delete);
self.handle_serial_events(|this, ev: ExitIngameEvent| {

View File

@ -72,6 +72,7 @@ pub trait StateExt {
fn create_item_drop(
&mut self,
pos: comp::Pos,
ori: comp::Ori,
vel: comp::Vel,
item: Item,
loot_owner: Option<LootOwner>,
@ -338,6 +339,7 @@ impl StateExt for State {
fn create_item_drop(
&mut self,
pos: comp::Pos,
ori: comp::Ori,
vel: comp::Vel,
item: Item,
loot_owner: Option<LootOwner>,
@ -400,6 +402,7 @@ impl StateExt for State {
.create_entity_synced()
.with(item)
.with(pos)
.with(ori)
.with(vel)
.with(item_drop.orientation(&mut thread_rng()))
.with(item_drop.mass())