veloren_common/
event.rs

1use crate::{
2    Explosion,
3    character::CharacterId,
4    combat::{AttackSource, AttackTarget, CombatEffect, DeathEffects, RiderEffects},
5    comp::{
6        self, DisconnectReason, LootOwner, Ori, Pos, UnresolvedChatMsg, Vel,
7        ability::Dodgeable,
8        agent::Sound,
9        beam,
10        invite::{InviteKind, InviteResponse},
11        slot::EquipSlot,
12    },
13    generation::{EntityInfo, SpecialEntity},
14    interaction::Interaction,
15    lottery::LootSpec,
16    mounting::VolumePos,
17    outcome::Outcome,
18    resources::{BattleMode, Secs},
19    rtsim::{self, RtSimEntity},
20    states::basic_summon::BeamPillarIndicatorSpecifier,
21    terrain::SpriteKind,
22    trade::{TradeAction, TradeId},
23    uid::Uid,
24    util::Dir,
25};
26use serde::{Deserialize, Serialize};
27use specs::Entity as EcsEntity;
28use std::{collections::VecDeque, sync::Mutex, time::Duration};
29use uuid::Uuid;
30use vek::*;
31
32pub type SiteId = u64;
33/// Plugin identifier (sha256)
34pub type PluginHash = [u8; 32];
35
36pub enum LocalEvent {
37    /// Applies upward force to entity's `Vel`
38    Jump(EcsEntity, f32),
39    /// Applies the `impulse` to `entity`'s `Vel`
40    ApplyImpulse {
41        entity: EcsEntity,
42        impulse: Vec3<f32>,
43    },
44    /// Applies `vel` velocity to `entity`
45    Boost { entity: EcsEntity, vel: Vec3<f32> },
46    /// Creates an outcome
47    CreateOutcome(Outcome),
48}
49
50#[derive(Clone, Debug, Default, Deserialize, Serialize)]
51pub struct UpdateCharacterMetadata {
52    pub skill_set_persistence_load_error: Option<comp::skillset::SkillsPersistenceError>,
53}
54
55pub struct NpcBuilder {
56    pub stats: comp::Stats,
57    pub skill_set: comp::SkillSet,
58    pub health: Option<comp::Health>,
59    pub poise: comp::Poise,
60    pub inventory: comp::inventory::Inventory,
61    pub body: comp::Body,
62    pub agent: Option<comp::Agent>,
63    pub alignment: comp::Alignment,
64    pub scale: comp::Scale,
65    pub anchor: Option<comp::Anchor>,
66    pub loot: LootSpec<String>,
67    pub pets: Vec<(NpcBuilder, Vec3<f32>)>,
68    pub rtsim_entity: Option<RtSimEntity>,
69    pub projectile: Option<comp::Projectile>,
70    pub heads: Option<comp::body::parts::Heads>,
71    pub death_effects: Option<DeathEffects>,
72    pub rider_effects: Option<RiderEffects>,
73    pub rider: Option<Box<Self>>,
74}
75
76impl NpcBuilder {
77    pub fn new(stats: comp::Stats, body: comp::Body, alignment: comp::Alignment) -> Self {
78        Self {
79            stats,
80            skill_set: comp::SkillSet::default(),
81            health: None,
82            poise: comp::Poise::new(body),
83            inventory: comp::Inventory::with_empty(),
84            body,
85            agent: None,
86            alignment,
87            scale: comp::Scale(1.0),
88            anchor: None,
89            loot: LootSpec::Nothing,
90            rtsim_entity: None,
91            projectile: None,
92            pets: Vec::new(),
93            heads: None,
94            death_effects: None,
95            rider_effects: None,
96            rider: None,
97        }
98    }
99
100    pub fn with_rider(mut self, rider: impl Into<Option<NpcBuilder>>) -> Self {
101        let rider: Option<NpcBuilder> = rider.into();
102        self.rider = rider.map(Box::new);
103        self
104    }
105
106    pub fn with_heads(mut self, heads: impl Into<Option<comp::body::parts::Heads>>) -> Self {
107        self.heads = heads.into();
108        self
109    }
110
111    pub fn with_health(mut self, health: impl Into<Option<comp::Health>>) -> Self {
112        self.health = health.into();
113        self
114    }
115
116    pub fn with_poise(mut self, poise: comp::Poise) -> Self {
117        self.poise = poise;
118        self
119    }
120
121    pub fn with_agent(mut self, agent: impl Into<Option<comp::Agent>>) -> Self {
122        self.agent = agent.into();
123        self
124    }
125
126    pub fn with_anchor(mut self, anchor: comp::Anchor) -> Self {
127        self.anchor = Some(anchor);
128        self
129    }
130
131    pub fn with_rtsim(mut self, rtsim: RtSimEntity) -> Self {
132        self.rtsim_entity = Some(rtsim);
133        self
134    }
135
136    pub fn with_projectile(mut self, projectile: impl Into<Option<comp::Projectile>>) -> Self {
137        self.projectile = projectile.into();
138        self
139    }
140
141    pub fn with_scale(mut self, scale: comp::Scale) -> Self {
142        self.scale = scale;
143        self
144    }
145
146    pub fn with_inventory(mut self, inventory: comp::Inventory) -> Self {
147        self.inventory = inventory;
148        self
149    }
150
151    pub fn with_skill_set(mut self, skill_set: comp::SkillSet) -> Self {
152        self.skill_set = skill_set;
153        self
154    }
155
156    pub fn with_loot(mut self, loot: LootSpec<String>) -> Self {
157        self.loot = loot;
158        self
159    }
160
161    pub fn with_pets(mut self, pets: Vec<(NpcBuilder, Vec3<f32>)>) -> Self {
162        self.pets = pets;
163        self
164    }
165
166    pub fn with_death_effects(mut self, death_effects: Option<DeathEffects>) -> Self {
167        self.death_effects = death_effects;
168        self
169    }
170
171    pub fn with_rider_effects(mut self, rider_effects: Option<RiderEffects>) -> Self {
172        self.rider_effects = rider_effects;
173        self
174    }
175}
176
177// These events are generated only by server systems
178//
179// TODO: we may want to move these into the server crate, this may allow moving
180// other types out of `common` and would also narrow down where we know specific
181// events will be emitted (if done it should probably be setup so they can
182// easily be moved back here if needed).
183
184pub struct ClientDisconnectEvent(pub EcsEntity, pub DisconnectReason);
185
186pub struct ClientDisconnectWithoutPersistenceEvent(pub EcsEntity);
187
188pub struct CommandEvent(pub EcsEntity, pub String, pub Vec<String>);
189
190pub struct CreateSpecialEntityEvent {
191    pub pos: Vec3<f32>,
192    pub entity: SpecialEntity,
193}
194
195pub struct CreateShipEvent {
196    pub pos: Pos,
197    pub ori: Ori,
198    pub ship: comp::ship::Body,
199    pub rtsim_entity: Option<RtSimEntity>,
200    pub driver: Option<NpcBuilder>,
201}
202
203pub struct CreateItemDropEvent {
204    pub pos: Pos,
205    pub vel: Vel,
206    pub ori: Ori,
207    pub item: comp::PickupItem,
208    pub loot_owner: Option<LootOwner>,
209}
210
211pub struct CreateObjectEvent {
212    pub pos: Pos,
213    pub vel: Vel,
214    pub body: comp::object::Body,
215    pub object: Option<comp::Object>,
216    pub item: Option<comp::PickupItem>,
217    pub light_emitter: Option<comp::LightEmitter>,
218    pub stats: Option<comp::Stats>,
219}
220
221/// Inserts default components for a character when loading into the game.
222pub struct InitializeCharacterEvent {
223    pub entity: EcsEntity,
224    pub character_id: CharacterId,
225    pub requested_view_distances: crate::ViewDistances,
226}
227
228pub struct InitializeSpectatorEvent(pub EcsEntity, pub crate::ViewDistances);
229
230pub struct UpdateCharacterDataEvent {
231    pub entity: EcsEntity,
232    pub components: (
233        comp::Body,
234        Option<comp::Hardcore>,
235        comp::Stats,
236        comp::SkillSet,
237        comp::Inventory,
238        Option<comp::Waypoint>,
239        Vec<(comp::Pet, comp::Body, comp::Stats)>,
240        comp::ActiveAbilities,
241        Option<comp::MapMarker>,
242    ),
243    pub metadata: UpdateCharacterMetadata,
244}
245
246pub struct ExitIngameEvent {
247    pub entity: EcsEntity,
248}
249
250pub struct RequestSiteInfoEvent {
251    pub entity: EcsEntity,
252    pub id: SiteId,
253}
254
255pub struct TamePetEvent {
256    pub pet_entity: EcsEntity,
257    pub owner_entity: EcsEntity,
258}
259
260pub struct UpdateMapMarkerEvent {
261    pub entity: EcsEntity,
262    pub update: comp::MapMarkerChange,
263}
264
265pub struct MakeAdminEvent {
266    pub entity: EcsEntity,
267    pub admin: comp::Admin,
268    pub uuid: Uuid,
269}
270
271pub struct DeleteCharacterEvent {
272    pub entity: EcsEntity,
273    pub requesting_player_uuid: String,
274    pub character_id: CharacterId,
275}
276
277pub struct TeleportToPositionEvent {
278    pub entity: EcsEntity,
279    pub position: Vec3<f32>,
280}
281
282pub struct RequestPluginsEvent {
283    pub entity: EcsEntity,
284    pub plugins: Vec<PluginHash>,
285}
286
287pub struct SetBattleModeEvent {
288    pub entity: EcsEntity,
289    pub battle_mode: BattleMode,
290}
291
292// These events are generated in common systems in addition to server systems
293// (but note on the client the event buses aren't registered and these events
294// aren't actually emitted).
295
296pub struct ChatEvent {
297    pub msg: UnresolvedChatMsg,
298    // We warn when the server tries to generate non plain `Content` messags
299    // that appear from a player since we currently filter those out.
300    //
301    // But we don't want to spam warnings if this is from a client, so track that here.
302    pub from_client: bool,
303}
304
305pub struct CreateNpcEvent {
306    pub pos: Pos,
307    pub ori: Ori,
308    pub npc: NpcBuilder,
309}
310
311pub struct CreateNpcGroupEvent {
312    pub npcs: Vec<CreateNpcEvent>,
313}
314
315pub struct CreateAuraEntityEvent {
316    pub auras: comp::Auras,
317    pub pos: Pos,
318    pub creator_uid: Uid,
319    pub duration: Option<Secs>,
320}
321
322pub struct ExplosionEvent {
323    pub pos: Vec3<f32>,
324    pub explosion: Explosion,
325    pub owner: Option<Uid>,
326}
327
328pub struct BonkEvent {
329    pub pos: Vec3<f32>,
330    pub owner: Option<Uid>,
331    pub target: Option<Uid>,
332}
333
334pub struct HealthChangeEvent {
335    pub entity: EcsEntity,
336    pub change: comp::HealthChange,
337}
338
339pub struct KillEvent {
340    pub entity: EcsEntity,
341}
342
343pub struct HelpDownedEvent {
344    pub helper: Option<Uid>,
345    pub target: Uid,
346}
347
348pub struct DownedEvent {
349    pub entity: EcsEntity,
350}
351
352pub struct PoiseChangeEvent {
353    pub entity: EcsEntity,
354    pub change: comp::PoiseChange,
355}
356
357pub struct DeleteEvent(pub EcsEntity);
358
359pub struct DestroyEvent {
360    pub entity: EcsEntity,
361    pub cause: comp::HealthChange,
362}
363
364pub struct InventoryManipEvent(pub EcsEntity, pub comp::InventoryManip);
365
366pub struct GroupManipEvent(pub EcsEntity, pub comp::GroupManip);
367
368pub struct RespawnEvent(pub EcsEntity);
369
370pub struct ShootEvent {
371    pub entity: Option<EcsEntity>,
372    pub pos: Pos,
373    pub dir: Dir,
374    pub body: comp::Body,
375    pub light: Option<comp::LightEmitter>,
376    pub projectile: comp::Projectile,
377    pub speed: f32,
378    pub object: Option<comp::Object>,
379}
380
381pub struct ThrowEvent {
382    pub entity: EcsEntity,
383    pub pos: Pos,
384    pub dir: Dir,
385    pub light: Option<comp::LightEmitter>,
386    pub projectile: comp::Projectile,
387    pub speed: f32,
388    pub object: Option<comp::Object>,
389    pub equip_slot: EquipSlot,
390}
391
392pub struct ShockwaveEvent {
393    pub properties: comp::shockwave::Properties,
394    pub pos: Pos,
395    pub ori: Ori,
396}
397
398pub struct KnockbackEvent {
399    pub entity: EcsEntity,
400    pub impulse: Vec3<f32>,
401}
402
403pub struct LandOnGroundEvent {
404    pub entity: EcsEntity,
405    pub vel: Vec3<f32>,
406    pub surface_normal: Vec3<f32>,
407}
408
409pub struct SetLanternEvent(pub EcsEntity, pub bool);
410
411pub struct NpcInteractEvent(pub EcsEntity, pub EcsEntity);
412
413pub struct DialogueEvent(pub EcsEntity, pub EcsEntity, pub rtsim::Dialogue);
414
415pub struct InviteResponseEvent(pub EcsEntity, pub InviteResponse);
416
417pub struct InitiateInviteEvent(pub EcsEntity, pub Uid, pub InviteKind);
418
419pub struct ProcessTradeActionEvent(pub EcsEntity, pub TradeId, pub TradeAction);
420
421pub enum MountEvent {
422    MountEntity(EcsEntity, EcsEntity),
423    MountVolume(EcsEntity, VolumePos),
424    Unmount(EcsEntity),
425}
426
427pub struct SetPetStayEvent(pub EcsEntity, pub EcsEntity, pub bool);
428
429pub struct PossessEvent(pub Uid, pub Uid);
430
431pub struct TransformEvent {
432    pub target_entity: Uid,
433    pub entity_info: EntityInfo,
434    /// If set to false, players wont be transformed unless with a Possessor
435    /// presence kind
436    pub allow_players: bool,
437    /// Whether the entity should be deleted if transforming fails (only applies
438    /// to non-players)
439    pub delete_on_failure: bool,
440}
441
442pub struct StartInteractionEvent(pub Interaction);
443
444pub struct AuraEvent {
445    pub entity: EcsEntity,
446    pub aura_change: comp::AuraChange,
447}
448
449pub struct BuffEvent {
450    pub entity: EcsEntity,
451    pub buff_change: comp::BuffChange,
452}
453
454pub struct EnergyChangeEvent {
455    pub entity: EcsEntity,
456    pub change: f32,
457    pub reset_rate: bool,
458}
459
460pub struct ComboChangeEvent {
461    pub entity: EcsEntity,
462    pub change: i32,
463}
464
465pub struct ParryHookEvent {
466    pub defender: EcsEntity,
467    pub attacker: Option<EcsEntity>,
468    pub source: AttackSource,
469    pub poise_multiplier: f32,
470}
471
472/// Attempt to mine a block, turning it into an item.
473pub struct MineBlockEvent {
474    pub entity: EcsEntity,
475    pub pos: Vec3<i32>,
476    pub tool: Option<comp::tool::ToolKind>,
477}
478
479pub struct TeleportToEvent {
480    pub entity: EcsEntity,
481    pub target: Uid,
482    pub max_range: Option<f32>,
483}
484
485pub struct SoundEvent {
486    pub sound: Sound,
487}
488
489pub struct CreateSpriteEvent {
490    pub pos: Vec3<i32>,
491    pub sprite: SpriteKind,
492    pub del_timeout: Option<(f32, f32)>,
493}
494
495pub struct EntityAttackedHookEvent {
496    pub entity: EcsEntity,
497    pub attacker: Option<EcsEntity>,
498}
499
500pub struct ChangeAbilityEvent {
501    pub entity: EcsEntity,
502    pub slot: usize,
503    pub auxiliary_key: comp::ability::AuxiliaryKey,
504    pub new_ability: comp::ability::AuxiliaryAbility,
505}
506
507pub struct ChangeStanceEvent {
508    pub entity: EcsEntity,
509    pub stance: comp::Stance,
510}
511
512pub struct PermanentChange {
513    pub expected_old_body: comp::Body,
514}
515
516pub struct ChangeBodyEvent {
517    pub entity: EcsEntity,
518    pub new_body: comp::Body,
519    /// Is Some if this change should be persisted.
520    ///
521    /// Only applies to player characters.
522    pub permanent_change: Option<PermanentChange>,
523}
524
525pub struct RemoveLightEmitterEvent {
526    pub entity: EcsEntity,
527}
528
529pub struct StartTeleportingEvent {
530    pub entity: EcsEntity,
531    pub portal: EcsEntity,
532}
533
534pub struct ToggleSpriteLightEvent {
535    pub entity: EcsEntity,
536    pub pos: Vec3<i32>,
537    pub enable: bool,
538}
539
540pub struct RegrowHeadEvent {
541    pub entity: EcsEntity,
542}
543
544pub struct SummonBeamPillarsEvent {
545    pub summoner: EcsEntity,
546    pub target: AttackTarget,
547    pub buildup_duration: Duration,
548    pub attack_duration: Duration,
549    pub beam_duration: Duration,
550    pub radius: f32,
551    pub height: f32,
552    pub damage: f32,
553    pub damage_effect: Option<CombatEffect>,
554    pub dodgeable: Dodgeable,
555    pub tick_rate: f32,
556    pub specifier: beam::FrontendSpecifier,
557    pub indicator_specifier: BeamPillarIndicatorSpecifier,
558}
559
560struct EventBusInner<E> {
561    queue: VecDeque<E>,
562    /// Saturates to u8::MAX and is never reset.
563    ///
564    /// Used in the first tick to check for if certain event types are handled
565    /// and only handled once.
566    #[cfg(debug_assertions)]
567    recv_count: u8,
568}
569
570pub struct EventBus<E> {
571    inner: Mutex<EventBusInner<E>>,
572}
573
574impl<E> Default for EventBus<E> {
575    fn default() -> Self {
576        Self {
577            inner: Mutex::new(EventBusInner {
578                queue: VecDeque::new(),
579                #[cfg(debug_assertions)]
580                recv_count: 0,
581            }),
582        }
583    }
584}
585
586impl<E> EventBus<E> {
587    pub fn emitter(&self) -> Emitter<'_, E> {
588        Emitter {
589            bus: self,
590            events: VecDeque::new(),
591        }
592    }
593
594    pub fn emit_now(&self, event: E) {
595        self.inner.lock().expect("Poisoned").queue.push_back(event);
596    }
597
598    pub fn recv_all(&self) -> impl ExactSizeIterator<Item = E> + use<E> {
599        {
600            let mut guard = self.inner.lock().expect("Poisoned");
601            #[cfg(debug_assertions)]
602            {
603                guard.recv_count = guard.recv_count.saturating_add(1);
604            }
605            core::mem::take(&mut guard.queue)
606        }
607        .into_iter()
608    }
609
610    pub fn recv_all_mut(&mut self) -> impl ExactSizeIterator<Item = E> + use<E> {
611        let inner = self.inner.get_mut().expect("Poisoned");
612        #[cfg(debug_assertions)]
613        {
614            inner.recv_count = inner.recv_count.saturating_add(1);
615        }
616        core::mem::take(&mut inner.queue).into_iter()
617    }
618
619    #[cfg(debug_assertions)]
620    pub fn recv_count(&mut self) -> u8 { self.inner.get_mut().expect("Poisoned").recv_count }
621}
622
623pub struct Emitter<'a, E> {
624    bus: &'a EventBus<E>,
625    pub events: VecDeque<E>,
626}
627
628impl<E> Emitter<'_, E> {
629    pub fn emit(&mut self, event: E) { self.events.push_back(event); }
630
631    pub fn emit_many(&mut self, events: impl IntoIterator<Item = E>) { self.events.extend(events); }
632
633    pub fn append(&mut self, other: &mut VecDeque<E>) { self.events.append(other) }
634
635    pub fn append_vec(&mut self, vec: Vec<E>) {
636        if self.events.is_empty() {
637            self.events = vec.into();
638        } else {
639            self.events.extend(vec);
640        }
641    }
642}
643
644impl<E> Drop for Emitter<'_, E> {
645    fn drop(&mut self) {
646        if !self.events.is_empty() {
647            let mut guard = self.bus.inner.lock().expect("Poision");
648            guard.queue.append(&mut self.events);
649        }
650    }
651}
652
653pub trait EmitExt<E> {
654    fn emit(&mut self, event: E);
655    fn emit_many(&mut self, events: impl IntoIterator<Item = E>);
656}
657
658/// Define ecs read data for event busses. And a way to convert them all to
659/// emitters.
660///
661/// # Example:
662/// ```
663/// mod some_mod_is_necessary_for_the_test {
664///     use veloren_common::event_emitters;
665///     pub struct Foo;
666///     pub struct Bar;
667///     pub struct Baz;
668///     event_emitters!(
669///       pub struct ReadEvents[EventEmitters] {
670///           foo: Foo, bar: Bar, baz: Baz,
671///       }
672///     );
673/// }
674/// ```
675#[macro_export]
676macro_rules! event_emitters {
677    ($($vis:vis struct $read_data:ident[$emitters:ident] { $($ev_ident:ident: $ty:ty),+ $(,)? })+) => {
678        mod event_emitters {
679            use super::*;
680            use specs::shred;
681            $(
682            #[derive(specs::SystemData)]
683            pub struct $read_data<'a> {
684                $($ev_ident: Option<specs::Read<'a, $crate::event::EventBus<$ty>>>),+
685            }
686
687            impl<'a> $read_data<'a> {
688                pub fn get_emitters(&self) -> $emitters<'_> {
689                    $emitters {
690                        $($ev_ident: self.$ev_ident.as_ref().map(|e| e.emitter())),+
691                    }
692                }
693            }
694
695            pub struct $emitters<'a> {
696                $($ev_ident: Option<$crate::event::Emitter<'a, $ty>>),+
697            }
698
699            impl<'a> $emitters<'a> {
700                #[expect(unused)]
701                pub fn append(&mut self, mut other: Self) {
702                    $(
703                        self.$ev_ident.as_mut().zip(other.$ev_ident).map(|(a, mut b)| a.append(&mut b.events));
704                    )+
705                }
706            }
707
708            $(
709                impl<'a> $crate::event::EmitExt<$ty> for $emitters<'a> {
710                    fn emit(&mut self, event: $ty) { self.$ev_ident.as_mut().map(|e| e.emit(event)); }
711                    fn emit_many(&mut self, events: impl IntoIterator<Item = $ty>) { self.$ev_ident.as_mut().map(|e| e.emit_many(events)); }
712                }
713            )+
714            )+
715        }
716        $(
717            $vis use event_emitters::{$read_data, $emitters};
718        )+
719    }
720}