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