1use crate::{
2 Explosion,
3 character::CharacterId,
4 combat::{AttackSource, AttackTarget, CombatEffect, DeathEffects, RiderEffects},
5 comp::{
6 self, ArcProperties, 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;
33pub type PluginHash = [u8; 32];
35
36pub enum LocalEvent {
37 Jump(EcsEntity, f32),
39 ApplyImpulse {
41 entity: EcsEntity,
42 impulse: Vec3<f32>,
43 },
44 Boost { entity: EcsEntity, vel: Vec3<f32> },
46 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
177pub 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
221pub 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
282#[cfg(feature = "plugins")]
283pub struct RequestPluginsEvent {
284 pub entity: EcsEntity,
285 pub plugins: Vec<PluginHash>,
286}
287
288pub struct SetBattleModeEvent {
289 pub entity: EcsEntity,
290 pub battle_mode: BattleMode,
291}
292
293pub struct ChatEvent {
298 pub msg: UnresolvedChatMsg,
299 pub from_client: bool,
304}
305
306pub struct CreateNpcEvent {
307 pub pos: Pos,
308 pub ori: Ori,
309 pub npc: NpcBuilder,
310}
311
312pub struct CreateNpcGroupEvent {
313 pub npcs: Vec<CreateNpcEvent>,
314}
315
316pub struct CreateAuraEntityEvent {
317 pub auras: comp::Auras,
318 pub pos: Pos,
319 pub creator_uid: Uid,
320 pub duration: Option<Secs>,
321}
322
323pub struct ExplosionEvent {
324 pub pos: Vec3<f32>,
325 pub explosion: Explosion,
326 pub owner: Option<Uid>,
327}
328
329pub struct ArcingEvent {
330 pub arc: ArcProperties,
331 pub owner: Option<Uid>,
332 pub target: Uid,
333 pub pos: Pos,
334}
335
336pub struct BonkEvent {
337 pub pos: Vec3<f32>,
338 pub owner: Option<Uid>,
339 pub target: Option<Uid>,
340}
341
342pub struct HealthChangeEvent {
343 pub entity: EcsEntity,
344 pub change: comp::HealthChange,
345}
346
347pub struct KillEvent {
348 pub entity: EcsEntity,
349}
350
351pub struct HelpDownedEvent {
352 pub helper: Option<Uid>,
353 pub target: Uid,
354}
355
356pub struct DownedEvent {
357 pub entity: EcsEntity,
358}
359
360pub struct PoiseChangeEvent {
361 pub entity: EcsEntity,
362 pub change: comp::PoiseChange,
363}
364
365pub struct DeleteEvent(pub EcsEntity);
366
367pub struct DestroyEvent {
368 pub entity: EcsEntity,
369 pub cause: comp::HealthChange,
370}
371
372pub struct InventoryManipEvent(pub EcsEntity, pub comp::InventoryManip);
373
374pub struct GroupManipEvent(pub EcsEntity, pub comp::GroupManip);
375
376pub struct RespawnEvent(pub EcsEntity);
377
378pub struct ShootEvent {
379 pub entity: Option<EcsEntity>,
381 pub source_vel: Option<Vel>,
382 pub pos: Pos,
383 pub dir: Dir,
384 pub body: comp::Body,
385 pub light: Option<comp::LightEmitter>,
386 pub projectile: comp::Projectile,
387 pub speed: f32,
388 pub object: Option<comp::Object>,
389 pub marker: Option<comp::FrontendMarker>,
390}
391
392pub struct ThrowEvent {
393 pub entity: EcsEntity,
394 pub pos: Pos,
395 pub dir: Dir,
396 pub light: Option<comp::LightEmitter>,
397 pub projectile: comp::Projectile,
398 pub speed: f32,
399 pub object: Option<comp::Object>,
400 pub equip_slot: EquipSlot,
401}
402
403pub struct ShockwaveEvent {
404 pub properties: comp::shockwave::Properties,
405 pub pos: Pos,
406 pub ori: Ori,
407}
408
409pub struct KnockbackEvent {
410 pub entity: EcsEntity,
411 pub impulse: Vec3<f32>,
412}
413
414pub struct LandOnGroundEvent {
415 pub entity: EcsEntity,
416 pub vel: Vec3<f32>,
417 pub surface_normal: Vec3<f32>,
418}
419
420pub struct SetLanternEvent(pub EcsEntity, pub bool);
421
422pub struct NpcInteractEvent(pub EcsEntity, pub EcsEntity);
423
424pub struct DialogueEvent(pub EcsEntity, pub EcsEntity, pub rtsim::Dialogue);
425
426pub struct InviteResponseEvent(pub EcsEntity, pub InviteResponse);
427
428pub struct InitiateInviteEvent(pub EcsEntity, pub Uid, pub InviteKind);
429
430pub struct ProcessTradeActionEvent(pub EcsEntity, pub TradeId, pub TradeAction);
431
432pub enum MountEvent {
433 MountEntity(EcsEntity, EcsEntity),
434 MountVolume(EcsEntity, VolumePos),
435 Unmount(EcsEntity),
436}
437
438pub struct SetPetStayEvent(pub EcsEntity, pub EcsEntity, pub bool);
439
440pub struct PossessEvent(pub Uid, pub Uid);
441
442pub struct TransformEvent {
443 pub target_entity: Uid,
444 pub entity_info: EntityInfo,
445 pub allow_players: bool,
448 pub delete_on_failure: bool,
451}
452
453pub struct StartInteractionEvent(pub Interaction);
454
455pub struct AuraEvent {
456 pub entity: EcsEntity,
457 pub aura_change: comp::AuraChange,
458}
459
460pub struct BuffEvent {
461 pub entity: EcsEntity,
462 pub buff_change: comp::BuffChange,
463}
464
465pub struct EnergyChangeEvent {
466 pub entity: EcsEntity,
467 pub change: f32,
468 pub reset_rate: bool,
469}
470
471pub struct ComboChangeEvent {
472 pub entity: EcsEntity,
473 pub change: i32,
474}
475
476pub struct ParryHookEvent {
477 pub defender: EcsEntity,
478 pub attacker: Option<EcsEntity>,
479 pub source: AttackSource,
480 pub poise_multiplier: f32,
481}
482
483pub struct MineBlockEvent {
485 pub entity: EcsEntity,
486 pub pos: Vec3<i32>,
487 pub tool: Option<comp::tool::ToolKind>,
488}
489
490pub struct TeleportToEvent {
491 pub entity: EcsEntity,
492 pub target: Uid,
493 pub max_range: Option<f32>,
494}
495
496pub struct SoundEvent {
497 pub sound: Sound,
498}
499
500pub struct CreateSpriteEvent {
501 pub pos: Vec3<i32>,
502 pub sprite: SpriteKind,
503 pub del_timeout: Option<(f32, f32)>,
504}
505
506pub struct EntityAttackedHookEvent {
507 pub entity: EcsEntity,
508 pub attacker: Option<EcsEntity>,
509 pub attack_dir: Dir,
510 pub damage_dealt: f32,
511 pub attack_source: AttackSource,
512}
513
514pub struct ChangeAbilityEvent {
515 pub entity: EcsEntity,
516 pub slot: usize,
517 pub auxiliary_key: comp::ability::AuxiliaryKey,
518 pub new_ability: comp::ability::AuxiliaryAbility,
519}
520
521pub struct ChangeStanceEvent {
522 pub entity: EcsEntity,
523 pub stance: comp::Stance,
524}
525
526pub struct PermanentChange {
527 pub expected_old_body: comp::Body,
528}
529
530pub struct ChangeBodyEvent {
531 pub entity: EcsEntity,
532 pub new_body: comp::Body,
533 pub permanent_change: Option<PermanentChange>,
537}
538
539pub struct RemoveLightEmitterEvent {
540 pub entity: EcsEntity,
541}
542
543pub struct StartTeleportingEvent {
544 pub entity: EcsEntity,
545 pub portal: EcsEntity,
546}
547
548pub struct ToggleSpriteLightEvent {
549 pub entity: EcsEntity,
550 pub pos: Vec3<i32>,
551 pub enable: bool,
552}
553
554pub struct RegrowHeadEvent {
555 pub entity: EcsEntity,
556}
557
558pub struct SummonBeamPillarsEvent {
559 pub summoner: EcsEntity,
560 pub target: AttackTarget,
561 pub buildup_duration: Duration,
562 pub attack_duration: Duration,
563 pub beam_duration: Duration,
564 pub radius: f32,
565 pub height: f32,
566 pub damage: f32,
567 pub damage_effect: Option<CombatEffect>,
568 pub dodgeable: Dodgeable,
569 pub tick_rate: f32,
570 pub specifier: beam::FrontendSpecifier,
571 pub indicator_specifier: BeamPillarIndicatorSpecifier,
572}
573
574struct EventBusInner<E> {
575 queue: VecDeque<E>,
576 #[cfg(debug_assertions)]
581 recv_count: u8,
582}
583
584pub struct EventBus<E> {
585 inner: Mutex<EventBusInner<E>>,
586}
587
588impl<E> Default for EventBus<E> {
589 fn default() -> Self {
590 Self {
591 inner: Mutex::new(EventBusInner {
592 queue: VecDeque::new(),
593 #[cfg(debug_assertions)]
594 recv_count: 0,
595 }),
596 }
597 }
598}
599
600impl<E> EventBus<E> {
601 pub fn emitter(&self) -> Emitter<'_, E> {
602 Emitter {
603 bus: self,
604 events: VecDeque::new(),
605 }
606 }
607
608 pub fn emit_now(&self, event: E) {
609 self.inner.lock().expect("Poisoned").queue.push_back(event);
610 }
611
612 pub fn recv_all(&self) -> impl ExactSizeIterator<Item = E> + use<E> {
613 {
614 let mut guard = self.inner.lock().expect("Poisoned");
615 #[cfg(debug_assertions)]
616 {
617 guard.recv_count = guard.recv_count.saturating_add(1);
618 }
619 core::mem::take(&mut guard.queue)
620 }
621 .into_iter()
622 }
623
624 pub fn recv_all_mut(&mut self) -> impl ExactSizeIterator<Item = E> + use<E> {
625 let inner = self.inner.get_mut().expect("Poisoned");
626 #[cfg(debug_assertions)]
627 {
628 inner.recv_count = inner.recv_count.saturating_add(1);
629 }
630 core::mem::take(&mut inner.queue).into_iter()
631 }
632
633 #[cfg(debug_assertions)]
634 pub fn recv_count(&mut self) -> u8 { self.inner.get_mut().expect("Poisoned").recv_count }
635}
636
637pub struct Emitter<'a, E> {
638 bus: &'a EventBus<E>,
639 pub events: VecDeque<E>,
640}
641
642impl<E> Emitter<'_, E> {
643 pub fn emit(&mut self, event: E) { self.events.push_back(event); }
644
645 pub fn emit_many(&mut self, events: impl IntoIterator<Item = E>) { self.events.extend(events); }
646
647 pub fn append(&mut self, other: &mut VecDeque<E>) { self.events.append(other) }
648
649 pub fn append_vec(&mut self, vec: Vec<E>) {
650 if self.events.is_empty() {
651 self.events = vec.into();
652 } else {
653 self.events.extend(vec);
654 }
655 }
656}
657
658impl<E> Drop for Emitter<'_, E> {
659 fn drop(&mut self) {
660 if !self.events.is_empty() {
661 let mut guard = self.bus.inner.lock().expect("Poision");
662 guard.queue.append(&mut self.events);
663 }
664 }
665}
666
667pub trait EmitExt<E> {
668 fn emit(&mut self, event: E);
669 fn emit_many(&mut self, events: impl IntoIterator<Item = E>);
670}
671
672#[macro_export]
690macro_rules! event_emitters {
691 ($($vis:vis struct $read_data:ident[$emitters:ident] { $($(#[$($tt:tt)*])? $ev_ident:ident: $ty:ty),+ $(,)? })+) => {
692 mod event_emitters {
693 use super::*;
694 use specs::shred;
695 $(
696 #[derive(specs::SystemData)]
697 pub struct $read_data<'a> {
698 $($(#[$($tt)*])? $ev_ident: Option<specs::Read<'a, $crate::event::EventBus<$ty>>>),+
699 }
700
701 impl<'a> $read_data<'a> {
702 pub fn get_emitters(&self) -> $emitters<'_> {
703 $emitters {
704 $($(#[$($tt)*])? $ev_ident: self.$ev_ident.as_ref().map(|e| e.emitter())),+
705 }
706 }
707 }
708
709 pub struct $emitters<'a> {
710 $($(#[$($tt)*])? $ev_ident: Option<$crate::event::Emitter<'a, $ty>>),+
711 }
712
713 impl<'a> $emitters<'a> {
714 #[expect(unused)]
715 pub fn append(&mut self, mut other: Self) {
716 $(
717 $(#[$($tt)*])?
718 {self.$ev_ident.as_mut().zip(other.$ev_ident).map(|(a, mut b)| a.append(&mut b.events));}
719 )+
720 }
721 }
722
723 $(
724 $(#[$($tt)*])?
725 impl<'a> $crate::event::EmitExt<$ty> for $emitters<'a> {
726 fn emit(&mut self, event: $ty) { self.$ev_ident.as_mut().map(|e| e.emit(event)); }
727 fn emit_many(&mut self, events: impl IntoIterator<Item = $ty>) { self.$ev_ident.as_mut().map(|e| e.emit_many(events)); }
728 }
729 )+
730 )+
731 }
732 $(
733 $vis use event_emitters::{$read_data, $emitters};
734 )+
735 }
736}