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