1use crate::{
2 comp::{
3 Body, UtteranceKind, biped_large, biped_small, bird_medium, humanoid, object,
4 quadruped_low, quadruped_medium, quadruped_small, ship,
5 },
6 path::Chaser,
7 rtsim::{self, NpcInput, RtSimController},
8 trade::{PendingTrade, ReducedInventory, SiteId, SitePrices, TradeId, TradeResult},
9 uid::Uid,
10};
11use enum_map::EnumMap;
12use serde::{Deserialize, Serialize};
13use specs::{Component, DerefFlaggedStorage, Entity as EcsEntity};
14use std::{collections::VecDeque, fmt};
15use vek::*;
16
17use super::{Group, Pos};
18
19pub const DEFAULT_INTERACTION_TIME: f32 = 3.0;
20pub const TRADE_INTERACTION_TIME: f32 = 300.0;
21const SECONDS_BEFORE_FORGET_SOUNDS: f64 = 180.0;
22
23const ACTIONSTATE_NUMBER_OF_CONCURRENT_TIMERS: usize = 5;
32const ACTIONSTATE_NUMBER_OF_CONCURRENT_COUNTERS: usize = 5;
36const ACTIONSTATE_NUMBER_OF_CONCURRENT_INT_COUNTERS: usize = 5;
40const ACTIONSTATE_NUMBER_OF_CONCURRENT_CONDITIONS: usize = 5;
43const ACTIONSTATE_NUMBER_OF_CONCURRENT_POSITIONS: usize = 5;
45
46#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
47pub enum Alignment {
48 Wild,
50 Enemy,
52 Npc,
54 Tame,
56 Owned(Uid),
58 Passive,
60}
61
62#[derive(Copy, Clone, Debug, PartialEq, Eq)]
63pub enum Mark {
64 Merchant,
65 Guard,
66}
67
68impl Alignment {
69 pub fn hostile_towards(self, other: Alignment) -> bool {
71 match (self, other) {
72 (Alignment::Passive, _) => false,
73 (_, Alignment::Passive) => false,
74 (Alignment::Enemy, Alignment::Enemy) => false,
75 (Alignment::Enemy, Alignment::Wild) => false,
76 (Alignment::Wild, Alignment::Enemy) => false,
77 (Alignment::Wild, Alignment::Wild) => false,
78 (Alignment::Npc, Alignment::Wild) => false,
79 (Alignment::Npc, Alignment::Enemy) => true,
80 (_, Alignment::Enemy) => true,
81 (Alignment::Enemy, _) => true,
82 _ => false,
83 }
84 }
85
86 pub fn passive_towards(self, other: Alignment) -> bool {
88 match (self, other) {
89 (Alignment::Enemy, Alignment::Enemy) => true,
90 (Alignment::Owned(a), Alignment::Owned(b)) if a == b => true,
91 (Alignment::Npc, Alignment::Npc) => true,
92 (Alignment::Npc, Alignment::Tame) => true,
93 (Alignment::Enemy, Alignment::Wild) => true,
94 (Alignment::Wild, Alignment::Enemy) => true,
95 (Alignment::Tame, Alignment::Npc) => true,
96 (Alignment::Tame, Alignment::Tame) => true,
97 (_, Alignment::Passive) => true,
98 _ => false,
99 }
100 }
101
102 pub fn friendly_towards(self, other: Alignment) -> bool {
104 match (self, other) {
105 (Alignment::Enemy, Alignment::Enemy) => true,
106 (Alignment::Owned(a), Alignment::Owned(b)) if a == b => true,
107 (Alignment::Npc, Alignment::Npc) => true,
108 (Alignment::Npc, Alignment::Tame) => true,
109 (Alignment::Tame, Alignment::Npc) => true,
110 (Alignment::Tame, Alignment::Tame) => true,
111 (_, Alignment::Passive) => true,
112 _ => false,
113 }
114 }
115
116 pub fn group(&self) -> Option<Group> {
119 match self {
120 Alignment::Wild => None,
121 Alignment::Passive => None,
122 Alignment::Enemy => Some(super::group::ENEMY),
123 Alignment::Npc | Alignment::Tame => Some(super::group::NPC),
124 Alignment::Owned(_) => None,
125 }
126 }
127}
128
129impl Component for Alignment {
130 type Storage = DerefFlaggedStorage<Self, specs::VecStorage<Self>>;
131}
132
133bitflags::bitflags! {
134 #[derive(Clone, Copy, Debug, Default)]
135 pub struct BehaviorCapability: u8 {
136 const SPEAK = 0b00000001;
137 const TRADE = 0b00000010;
138 }
139}
140bitflags::bitflags! {
141 #[derive(Clone, Copy, Debug, Default)]
142 pub struct BehaviorState: u8 {
143 const TRADING = 0b00000001;
144 const TRADING_ISSUER = 0b00000010;
145 }
146}
147
148#[derive(Default, Copy, Clone, Debug)]
149pub enum TradingBehavior {
150 #[default]
151 None,
152 RequireBalanced {
153 trade_site: SiteId,
154 },
155 AcceptFood,
156}
157
158impl TradingBehavior {
159 fn can_trade(&self, alignment: Option<Alignment>, counterparty: Uid) -> bool {
160 match self {
161 TradingBehavior::RequireBalanced { .. } => true,
162 TradingBehavior::AcceptFood => alignment == Some(Alignment::Owned(counterparty)),
163 TradingBehavior::None => false,
164 }
165 }
166}
167
168#[derive(Default, Copy, Clone, Debug)]
174pub struct Behavior {
175 capabilities: BehaviorCapability,
176 state: BehaviorState,
177 pub trading_behavior: TradingBehavior,
178}
179
180impl From<BehaviorCapability> for Behavior {
181 fn from(capabilities: BehaviorCapability) -> Self {
182 Behavior {
183 capabilities,
184 state: BehaviorState::default(),
185 trading_behavior: TradingBehavior::None,
186 }
187 }
188}
189
190impl Behavior {
191 #[must_use]
194 pub fn maybe_with_capabilities(
195 mut self,
196 maybe_capabilities: Option<BehaviorCapability>,
197 ) -> Self {
198 if let Some(capabilities) = maybe_capabilities {
199 self.allow(capabilities)
200 }
201 self
202 }
203
204 #[must_use]
207 pub fn with_trade_site(mut self, trade_site: Option<SiteId>) -> Self {
208 if let Some(trade_site) = trade_site {
209 self.trading_behavior = TradingBehavior::RequireBalanced { trade_site };
210 }
211 self
212 }
213
214 pub fn allow(&mut self, capabilities: BehaviorCapability) {
216 self.capabilities.set(capabilities, true)
217 }
218
219 pub fn deny(&mut self, capabilities: BehaviorCapability) {
221 self.capabilities.set(capabilities, false)
222 }
223
224 pub fn can(&self, capabilities: BehaviorCapability) -> bool {
226 self.capabilities.contains(capabilities)
227 }
228
229 pub fn can_trade(&self, alignment: Option<Alignment>, counterparty: Uid) -> bool {
231 self.trading_behavior.can_trade(alignment, counterparty)
232 }
233
234 pub fn set(&mut self, state: BehaviorState) { self.state.set(state, true) }
236
237 pub fn unset(&mut self, state: BehaviorState) { self.state.set(state, false) }
239
240 pub fn is(&self, state: BehaviorState) -> bool { self.state.contains(state) }
242
243 pub fn trade_site(&self) -> Option<SiteId> {
245 if let TradingBehavior::RequireBalanced { trade_site } = self.trading_behavior {
246 Some(trade_site)
247 } else {
248 None
249 }
250 }
251}
252
253#[derive(Clone, Debug, Default)]
254pub struct Psyche {
255 pub flee_health: f32,
258 pub sight_dist: f32,
261 pub listen_dist: f32,
263 pub aggro_dist: Option<f32>,
267 pub idle_wander_factor: f32,
270 pub aggro_range_multiplier: f32,
277 pub should_stop_pursuing: bool,
281}
282
283impl<'a> From<&'a Body> for Psyche {
284 fn from(body: &'a Body) -> Self {
285 Self {
286 flee_health: match body {
287 Body::Humanoid(humanoid) => match humanoid.species {
288 humanoid::Species::Danari => 0.4,
289 humanoid::Species::Dwarf => 0.3,
290 humanoid::Species::Elf => 0.4,
291 humanoid::Species::Human => 0.4,
292 humanoid::Species::Orc => 0.3,
293 humanoid::Species::Draugr => 0.3,
294 },
295 Body::QuadrupedSmall(quadruped_small) => match quadruped_small.species {
296 quadruped_small::Species::Pig => 0.5,
297 quadruped_small::Species::Fox => 0.3,
298 quadruped_small::Species::Sheep => 0.25,
299 quadruped_small::Species::Boar => 0.1,
300 quadruped_small::Species::Skunk => 0.4,
301 quadruped_small::Species::Cat => 0.99,
302 quadruped_small::Species::Batfox => 0.1,
303 quadruped_small::Species::Raccoon => 0.4,
304 quadruped_small::Species::Hyena => 0.1,
305 quadruped_small::Species::Dog => 0.8,
306 quadruped_small::Species::Rabbit | quadruped_small::Species::Jackalope => 0.25,
307 quadruped_small::Species::Truffler => 0.08,
308 quadruped_small::Species::Hare => 0.3,
309 quadruped_small::Species::Goat => 0.3,
310 quadruped_small::Species::Porcupine => 0.2,
311 quadruped_small::Species::Turtle => 0.4,
312 quadruped_small::Species::Beaver => 0.2,
313 quadruped_small::Species::Rat
316 | quadruped_small::Species::TreantSapling
317 | quadruped_small::Species::Holladon
318 | quadruped_small::Species::MossySnail => 0.0,
319 _ => 1.0,
320 },
321 Body::QuadrupedMedium(quadruped_medium) => match quadruped_medium.species {
322 quadruped_medium::Species::Antelope => 0.15,
324 quadruped_medium::Species::Donkey => 0.05,
325 quadruped_medium::Species::Horse => 0.15,
326 quadruped_medium::Species::Mouflon => 0.1,
327 quadruped_medium::Species::Zebra => 0.1,
328 quadruped_medium::Species::Barghest
332 | quadruped_medium::Species::Bear
333 | quadruped_medium::Species::Bristleback
334 | quadruped_medium::Species::Bonerattler => 0.0,
335 quadruped_medium::Species::Cattle => 0.1,
336 quadruped_medium::Species::Frostfang => 0.07,
337 quadruped_medium::Species::Grolgar => 0.0,
338 quadruped_medium::Species::Highland => 0.05,
339 quadruped_medium::Species::Kelpie => 0.35,
340 quadruped_medium::Species::Lion => 0.0,
341 quadruped_medium::Species::Moose => 0.15,
342 quadruped_medium::Species::Panda => 0.35,
343 quadruped_medium::Species::Saber
344 | quadruped_medium::Species::Tarasque
345 | quadruped_medium::Species::Tiger => 0.0,
346 quadruped_medium::Species::Tuskram => 0.1,
347 quadruped_medium::Species::Wolf => 0.2,
348 quadruped_medium::Species::Yak => 0.09,
349 quadruped_medium::Species::Akhlut
351 | quadruped_medium::Species::Catoblepas
352 | quadruped_medium::Species::ClaySteed
353 | quadruped_medium::Species::Dreadhorn
354 | quadruped_medium::Species::Hirdrasil
355 | quadruped_medium::Species::Mammoth
356 | quadruped_medium::Species::Ngoubou
357 | quadruped_medium::Species::Roshwalr => 0.0,
358 _ => 0.15,
359 },
360 Body::QuadrupedLow(quadruped_low) => match quadruped_low.species {
361 quadruped_low::Species::Pangolin => 0.3,
363 quadruped_low::Species::Tortoise => 0.1,
365 _ => 0.0,
367 },
368 Body::BipedSmall(biped_small) => match biped_small.species {
369 biped_small::Species::Gnarling => 0.2,
370 biped_small::Species::Mandragora => 0.1,
371 biped_small::Species::Adlet => 0.2,
372 biped_small::Species::Haniwa => 0.1,
373 biped_small::Species::Sahagin => 0.1,
374 biped_small::Species::Myrmidon => 0.0,
375 biped_small::Species::TreasureEgg => 9.9,
376 biped_small::Species::Husk
377 | biped_small::Species::Boreal
378 | biped_small::Species::IronDwarf
379 | biped_small::Species::Flamekeeper
380 | biped_small::Species::Irrwurz
381 | biped_small::Species::GoblinThug
382 | biped_small::Species::GoblinChucker
383 | biped_small::Species::GoblinRuffian
384 | biped_small::Species::GreenLegoom
385 | biped_small::Species::OchreLegoom
386 | biped_small::Species::PurpleLegoom
387 | biped_small::Species::RedLegoom
388 | biped_small::Species::UmberLegoom
389 | biped_small::Species::ShamanicSpirit
390 | biped_small::Species::Jiangshi
391 | biped_small::Species::Bushly
392 | biped_small::Species::Cactid
393 | biped_small::Species::BloodmoonHeiress
394 | biped_small::Species::Bloodservant
395 | biped_small::Species::Harlequin
396 | biped_small::Species::GnarlingChieftain => 0.0,
397
398 _ => 0.5,
399 },
400 Body::BirdMedium(bird_medium) => match bird_medium.species {
401 bird_medium::Species::SnowyOwl => 0.4,
402 bird_medium::Species::HornedOwl => 0.4,
403 bird_medium::Species::Duck => 0.6,
404 bird_medium::Species::Cockatiel => 0.6,
405 bird_medium::Species::Chicken => 0.5,
406 bird_medium::Species::Bat => 0.1,
407 bird_medium::Species::Penguin => 0.5,
408 bird_medium::Species::Goose => 0.4,
409 bird_medium::Species::Peacock => 0.3,
410 bird_medium::Species::Eagle => 0.2,
411 bird_medium::Species::Parrot => 0.8,
412 bird_medium::Species::Crow => 0.4,
413 bird_medium::Species::Dodo => 0.8,
414 bird_medium::Species::Parakeet => 0.8,
415 bird_medium::Species::Puffin => 0.8,
416 bird_medium::Species::Toucan => 0.4,
417 bird_medium::Species::BloodmoonBat => 0.0,
418 bird_medium::Species::VampireBat => 0.0,
419 },
420 Body::BirdLarge(_) => 0.0,
421 Body::FishSmall(_) => 1.0,
422 Body::FishMedium(_) => 0.75,
423 Body::BipedLarge(_) => 0.0,
424 Body::Object(_) => 0.0,
425 Body::Item(_) => 0.0,
426 Body::Golem(_) => 0.0,
427 Body::Theropod(_) => 0.0,
428 Body::Ship(_) => 0.0,
429 Body::Dragon(_) => 0.0,
430 Body::Arthropod(_) => 0.0,
431 Body::Crustacean(_) => 0.0,
432 Body::Plugin(body) => body.flee_health(),
433 },
434 sight_dist: match body {
435 Body::BirdLarge(_) => 250.0,
436 Body::BipedLarge(biped_large) => match biped_large.species {
437 biped_large::Species::Gigasfrost | biped_large::Species::Gigasfire => 200.0,
438 _ => 100.0,
439 },
440 _ => 40.0,
441 },
442 listen_dist: 30.0,
443 aggro_dist: match body {
444 Body::Humanoid(_) => Some(20.0),
445 _ => None, },
447 idle_wander_factor: 1.0,
448 aggro_range_multiplier: 1.0,
449 should_stop_pursuing: match body {
450 Body::BirdLarge(_) => false,
451 Body::BipedLarge(biped_large) => !matches!(
452 biped_large.species,
453 biped_large::Species::Gigasfrost | biped_large::Species::Gigasfire
454 ),
455 Body::BirdMedium(bird_medium) => {
456 !matches!(bird_medium.species, bird_medium::Species::BloodmoonBat)
459 },
460 _ => true,
461 },
462 }
463 }
464}
465
466impl Psyche {
467 pub fn search_dist(&self) -> f32 {
470 self.sight_dist.max(self.listen_dist) * self.aggro_range_multiplier
471 }
472}
473
474#[derive(Clone, Debug)]
475pub enum AgentEvent {
477 Talk(Uid),
479 TradeInvite(Uid),
480 TradeAccepted(Uid),
481 FinishedTrade(TradeResult),
482 UpdatePendingTrade(
483 Box<(
485 TradeId,
486 PendingTrade,
487 SitePrices,
488 [Option<ReducedInventory>; 2],
489 )>,
490 ),
491 ServerSound(Sound),
492 Hurt,
493 Dialogue(Uid, rtsim::Dialogue<true>),
494}
495
496#[derive(Copy, Clone, Debug)]
497pub struct Sound {
498 pub kind: SoundKind,
499 pub pos: Vec3<f32>,
500 pub vol: f32,
501 pub time: f64,
502}
503
504impl Sound {
505 pub fn new(kind: SoundKind, pos: Vec3<f32>, vol: f32, time: f64) -> Self {
506 Sound {
507 kind,
508 pos,
509 vol,
510 time,
511 }
512 }
513
514 #[must_use]
515 pub fn with_new_vol(mut self, new_vol: f32) -> Self {
516 self.vol = new_vol;
517
518 self
519 }
520}
521
522#[derive(Copy, Clone, Debug)]
523pub enum SoundKind {
524 Unknown,
525 Utterance(UtteranceKind, Body),
526 Movement,
527 Melee,
528 Projectile,
529 Explosion,
530 Beam,
531 Shockwave,
532 Mine,
533 Trap,
534}
535
536#[derive(Clone, Copy, Debug)]
537pub struct Target {
538 pub target: EcsEntity,
539 pub hostile: bool,
541 pub selected_at: f64,
543 pub aggro_on: bool,
545 pub last_known_pos: Option<Vec3<f32>>,
546}
547
548impl Target {
549 pub fn new(
550 target: EcsEntity,
551 hostile: bool,
552 selected_at: f64,
553 aggro_on: bool,
554 last_known_pos: Option<Vec3<f32>>,
555 ) -> Self {
556 Self {
557 target,
558 hostile,
559 selected_at,
560 aggro_on,
561 last_known_pos,
562 }
563 }
564}
565
566#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, enum_map::Enum)]
567pub enum TimerAction {
568 Interact,
569 Warn,
570}
571
572#[derive(Clone, Debug, Default)]
577pub struct Timer {
578 action_starts: EnumMap<TimerAction, Option<f64>>,
579 last_action: Option<TimerAction>,
580}
581
582impl Timer {
583 pub fn reset(&mut self, action: TimerAction) -> bool {
586 self.action_starts[action].take().is_some()
587 }
588
589 pub fn start(&mut self, time: f64, action: TimerAction) {
591 self.action_starts[action] = Some(time);
592 self.last_action = Some(action);
593 }
594
595 pub fn progress(&mut self, time: f64, action: TimerAction) {
598 if self.last_action != Some(action) {
599 self.start(time, action);
600 }
601 }
602
603 pub fn time_of_last(&self, action: TimerAction) -> Option<f64> { self.action_starts[action] }
605
606 pub fn time_since_exceeds(&self, time: f64, action: TimerAction, timeout: f64) -> bool {
609 self.time_of_last(action)
610 .is_none_or(|last_time| (time - last_time).max(0.0) > timeout)
611 }
612
613 pub fn timeout_elapsed(
616 &mut self,
617 time: f64,
618 action: TimerAction,
619 timeout: f64,
620 ) -> Option<bool> {
621 if self.time_since_exceeds(time, action, timeout) {
622 Some(self.reset(action))
623 } else {
624 self.progress(time, action);
625 None
626 }
627 }
628}
629
630#[derive(Clone, Debug)]
632pub struct Agent {
633 pub rtsim_controller: RtSimController,
634 pub patrol_origin: Option<Vec3<f32>>,
635 pub target: Option<Target>,
636 pub chaser: Chaser,
637 pub behavior: Behavior,
638 pub psyche: Psyche,
639 pub inbox: VecDeque<AgentEvent>,
640 pub combat_state: ActionState,
641 pub behavior_state: ActionState,
642 pub timer: Timer,
643 pub bearing: Vec2<f32>,
644 pub sounds_heard: Vec<Sound>,
645 pub multi_pid_controllers: Option<PidControllers<16>>,
646 pub mark: Option<Mark>,
647 pub flee_from_pos: Option<Pos>,
651 pub awareness: Awareness,
652 pub stay_pos: Option<Pos>,
653 pub rtsim_outbox: Option<VecDeque<NpcInput>>,
655}
656
657#[derive(Serialize, Deserialize)]
658pub struct SharedChaser {
659 pub nodes: Vec<Vec3<f32>>,
660 pub goal: Option<Vec3<f32>>,
661}
662
663#[derive(Clone, Debug)]
664pub struct Awareness {
666 level: f32,
667 reached: bool,
668}
669impl fmt::Display for Awareness {
670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:.2}", self.level) }
671}
672impl Awareness {
673 const ALERT: f32 = 1.0;
674 const HIGH: f32 = 0.6;
675 const LOW: f32 = 0.1;
676 const MEDIUM: f32 = 0.3;
677 const UNAWARE: f32 = 0.0;
678
679 pub fn new(level: f32) -> Self {
680 Self {
681 level: level.clamp(Self::UNAWARE, Self::ALERT),
682 reached: false,
683 }
684 }
685
686 pub fn level(&self) -> f32 { self.level }
688
689 pub fn state(&self) -> AwarenessState {
692 if self.level == Self::ALERT {
693 AwarenessState::Alert
694 } else if self.level.is_between(Self::HIGH, Self::ALERT) {
695 AwarenessState::High
696 } else if self.level.is_between(Self::MEDIUM, Self::HIGH) {
697 AwarenessState::Medium
698 } else if self.level.is_between(Self::LOW, Self::MEDIUM) {
699 AwarenessState::Low
700 } else {
701 AwarenessState::Unaware
702 }
703 }
704
705 pub fn reached(&self) -> bool { self.reached }
707
708 pub fn change_by(&mut self, amount: f32) {
709 self.level = (self.level + amount).clamp(Self::UNAWARE, Self::ALERT);
710
711 if self.state() == AwarenessState::Alert {
712 self.reached = true;
713 } else if self.state() == AwarenessState::Unaware {
714 self.reached = false;
715 }
716 }
717
718 pub fn set_maximally_aware(&mut self) {
719 self.reached = true;
720 self.level = Self::ALERT;
721 }
722}
723
724#[derive(Clone, Debug, PartialOrd, PartialEq, Eq)]
725pub enum AwarenessState {
726 Unaware = 0,
727 Low = 1,
728 Medium = 2,
729 High = 3,
730 Alert = 4,
731}
732
733#[derive(Clone, Debug, Default)]
738pub struct ActionState {
739 pub timers: [f32; ACTIONSTATE_NUMBER_OF_CONCURRENT_TIMERS],
740 pub counters: [f32; ACTIONSTATE_NUMBER_OF_CONCURRENT_COUNTERS],
741 pub conditions: [bool; ACTIONSTATE_NUMBER_OF_CONCURRENT_CONDITIONS],
742 pub int_counters: [u8; ACTIONSTATE_NUMBER_OF_CONCURRENT_INT_COUNTERS],
743 pub positions: [Option<Vec3<f32>>; ACTIONSTATE_NUMBER_OF_CONCURRENT_POSITIONS],
744 pub initialized: bool,
745}
746
747impl Agent {
748 pub fn from_body(body: &Body) -> Self {
750 Agent {
751 rtsim_controller: RtSimController::default(),
752 patrol_origin: None,
753 target: None,
754 chaser: Chaser::default(),
755 behavior: Behavior::default(),
756 psyche: Psyche::from(body),
757 inbox: VecDeque::new(),
758 combat_state: ActionState::default(),
759 behavior_state: ActionState::default(),
760 timer: Timer::default(),
761 bearing: Vec2::zero(),
762 sounds_heard: Vec::new(),
763 multi_pid_controllers: None,
764 mark: None,
765 flee_from_pos: None,
766 stay_pos: None,
767 awareness: Awareness::new(0.0),
768 rtsim_outbox: None,
769 }
770 }
771
772 #[must_use]
773 pub fn with_patrol_origin(mut self, origin: Vec3<f32>) -> Self {
774 self.patrol_origin = Some(origin);
775 self
776 }
777
778 #[must_use]
779 pub fn with_behavior(mut self, behavior: Behavior) -> Self {
780 self.behavior = behavior;
781 self
782 }
783
784 #[must_use]
785 pub fn with_no_flee_if(mut self, condition: bool) -> Self {
786 if condition {
787 self.psyche.flee_health = 0.0;
788 }
789 self
790 }
791
792 pub fn set_no_flee(&mut self) { self.psyche.flee_health = 0.0; }
793
794 #[must_use]
796 pub fn with_destination(mut self, pos: Vec3<f32>) -> Self {
797 self.psyche.flee_health = 0.0;
798 self.rtsim_controller = RtSimController::with_destination(pos);
799 self.behavior.allow(BehaviorCapability::SPEAK);
800 self
801 }
802
803 #[must_use]
804 pub fn with_idle_wander_factor(mut self, idle_wander_factor: f32) -> Self {
805 self.psyche.idle_wander_factor = idle_wander_factor;
806 self
807 }
808
809 pub fn with_aggro_range_multiplier(mut self, aggro_range_multiplier: f32) -> Self {
810 self.psyche.aggro_range_multiplier = aggro_range_multiplier;
811 self
812 }
813
814 #[must_use]
815 pub fn with_altitude_pid_controller(mut self, mpid: PidControllers<16>) -> Self {
816 self.multi_pid_controllers = Some(mpid);
817 self
818 }
819
820 #[must_use]
822 pub fn with_aggro_no_warn(mut self) -> Self {
823 self.psyche.aggro_dist = None;
824 self
825 }
826
827 pub fn forget_old_sounds(&mut self, time: f64) {
828 if !self.sounds_heard.is_empty() {
829 self.sounds_heard
831 .retain(|&sound| time - sound.time <= SECONDS_BEFORE_FORGET_SOUNDS);
832 }
833 }
834
835 pub fn allowed_to_speak(&self) -> bool { self.behavior.can(BehaviorCapability::SPEAK) }
836}
837
838impl Component for Agent {
839 type Storage = specs::DenseVecStorage<Self>;
840}
841
842#[cfg(test)]
843mod tests {
844 use super::{Agent, Behavior, BehaviorCapability, BehaviorState, Body, humanoid};
845
846 #[test]
849 pub fn behavior_basic() {
850 let mut b = Behavior::default();
851 assert!(!b.can(BehaviorCapability::SPEAK));
853 b.allow(BehaviorCapability::SPEAK);
854 assert!(b.can(BehaviorCapability::SPEAK));
855 b.deny(BehaviorCapability::SPEAK);
856 assert!(!b.can(BehaviorCapability::SPEAK));
857 assert!(!b.is(BehaviorState::TRADING));
859 b.set(BehaviorState::TRADING);
860 assert!(b.is(BehaviorState::TRADING));
861 b.unset(BehaviorState::TRADING);
862 assert!(!b.is(BehaviorState::TRADING));
863 let b = Behavior::from(BehaviorCapability::SPEAK);
865 assert!(b.can(BehaviorCapability::SPEAK));
866 }
867
868 #[test]
870 pub fn enable_flee() {
871 let body = Body::Humanoid(humanoid::Body::random());
872 let mut agent = Agent::from_body(&body);
873
874 agent.psyche.flee_health = 1.0;
875 agent = agent.with_no_flee_if(false);
876 assert_eq!(agent.psyche.flee_health, 1.0);
877 }
878
879 #[test]
881 pub fn set_no_flee() {
882 let body = Body::Humanoid(humanoid::Body::random());
883 let mut agent = Agent::from_body(&body);
884
885 agent.psyche.flee_health = 1.0;
886 agent.set_no_flee();
887 assert_eq!(agent.psyche.flee_health, 0.0);
888 }
889
890 #[test]
891 pub fn with_aggro_no_warn() {
892 let body = Body::Humanoid(humanoid::Body::random());
893 let mut agent = Agent::from_body(&body);
894
895 agent.psyche.aggro_dist = Some(1.0);
896 agent = agent.with_aggro_no_warn();
897 assert_eq!(agent.psyche.aggro_dist, None);
898 }
899}
900
901#[derive(Clone)]
908pub struct PidController<F: Fn(f32, f32) -> f32, const NUM_SAMPLES: usize> {
909 pub kp: f32,
911 pub ki: f32,
913 pub kd: f32,
915 pub sp: f32,
917 pv_samples: [(f64, f32); NUM_SAMPLES],
919 pv_idx: usize,
921 integral_error: f64,
923 e: F,
926}
927
928impl<F: Fn(f32, f32) -> f32, const NUM_SAMPLES: usize> fmt::Debug
929 for PidController<F, NUM_SAMPLES>
930{
931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
932 f.debug_struct("PidController")
933 .field("kp", &self.kp)
934 .field("ki", &self.ki)
935 .field("kd", &self.kd)
936 .field("sp", &self.sp)
937 .field("pv_samples", &self.pv_samples)
938 .field("pv_idx", &self.pv_idx)
939 .finish()
940 }
941}
942
943impl<F: Fn(f32, f32) -> f32, const NUM_SAMPLES: usize> PidController<F, NUM_SAMPLES> {
944 pub fn new(kp: f32, ki: f32, kd: f32, sp: f32, time: f64, e: F) -> Self {
947 Self {
948 kp,
949 ki,
950 kd,
951 sp,
952 pv_samples: [(time, sp); NUM_SAMPLES],
953 pv_idx: 0,
954 integral_error: 0.0,
955 e,
956 }
957 }
958
959 pub fn add_measurement(&mut self, time: f64, pv: f32) {
961 self.pv_idx += 1;
962 self.pv_idx %= NUM_SAMPLES;
963 self.pv_samples[self.pv_idx] = (time, pv);
964 self.update_integral_err();
965 }
966
967 pub fn calc_err(&self) -> f32 {
971 self.kp * self.proportional_err()
972 + self.ki * self.integral_err()
973 + self.kd * self.derivative_err()
974 }
975
976 pub fn proportional_err(&self) -> f32 { (self.e)(self.sp, self.pv_samples[self.pv_idx].1) }
979
980 pub fn integral_err(&self) -> f32 { self.integral_error as f32 }
985
986 fn update_integral_err(&mut self) {
987 let f = |x| (self.e)(self.sp, x) as f64;
988 let (a, x0) = self.pv_samples[(self.pv_idx + NUM_SAMPLES - 1) % NUM_SAMPLES];
989 let (b, x1) = self.pv_samples[self.pv_idx];
990 let dx = b - a;
991 if dx < 5.0 {
994 self.integral_error += dx * (f(x1) + f(x0)) / 2.0;
995 }
996 }
997
998 pub fn limit_integral_windup<W>(&mut self, f: W)
1004 where
1005 W: Fn(&mut f64),
1006 {
1007 f(&mut self.integral_error);
1008 }
1009
1010 pub fn derivative_err(&self) -> f32 {
1016 let f = |x| (self.e)(self.sp, x);
1017 let (a, x0) = self.pv_samples[(self.pv_idx + NUM_SAMPLES - 1) % NUM_SAMPLES];
1018 let (b, x1) = self.pv_samples[self.pv_idx];
1019 let h = b - a;
1020 if h == 0.0 {
1021 0.0
1022 } else {
1023 (f(x1) - f(x0)) / h as f32
1024 }
1025 }
1026}
1027
1028#[derive(Copy, Clone, Debug, PartialEq)]
1030pub enum FlightMode {
1031 Braking(BrakingMode),
1034 FlyThrough,
1037}
1038
1039#[derive(Default, Copy, Clone, Debug, PartialEq)]
1042pub enum BrakingMode {
1043 #[default]
1048 Normal,
1049 Precise,
1054}
1055
1056#[derive(Clone)]
1059pub struct PidControllers<const NUM_SAMPLES: usize> {
1060 pub mode: FlightMode,
1061 pub x_controller: Option<PidController<fn(f32, f32) -> f32, NUM_SAMPLES>>,
1063 pub y_controller: Option<PidController<fn(f32, f32) -> f32, NUM_SAMPLES>>,
1064 pub z_controller: Option<PidController<fn(f32, f32) -> f32, NUM_SAMPLES>>,
1065}
1066
1067impl<const NUM_SAMPLES: usize> fmt::Debug for PidControllers<NUM_SAMPLES> {
1068 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1069 f.debug_struct("PidControllers")
1070 .field("mode", &self.mode)
1071 .field("x_controller", &self.x_controller)
1072 .field("y_controller", &self.y_controller)
1073 .field("z_controller", &self.z_controller)
1074 .finish()
1075 }
1076}
1077
1078impl<const NUM_SAMPLES: usize> PidControllers<NUM_SAMPLES> {
1082 pub fn new(mode: FlightMode) -> Self {
1083 Self {
1084 mode,
1085 x_controller: None,
1086 y_controller: None,
1087 z_controller: None,
1088 }
1089 }
1090
1091 pub fn new_multi_pid_controllers(mode: FlightMode, travel_to: Vec3<f32>) -> PidControllers<16> {
1092 let mut mpid = PidControllers::new(mode);
1093 if matches!(mode, FlightMode::Braking(_)) {
1096 let (kp, ki, kd) = pid_coefficients_for_mode(mode, false);
1098 mpid.x_controller = Some(PidController::new(
1099 kp,
1100 ki,
1101 kd,
1102 travel_to.x,
1103 0.0,
1104 |sp, pv| sp - pv,
1105 ));
1106 mpid.y_controller = Some(PidController::new(
1107 kp,
1108 ki,
1109 kd,
1110 travel_to.y,
1111 0.0,
1112 |sp, pv| sp - pv,
1113 ));
1114 }
1115 let (kp, ki, kd) = pid_coefficients_for_mode(mode, true);
1117 mpid.z_controller = Some(PidController::new(
1118 kp,
1119 ki,
1120 kd,
1121 travel_to.z,
1122 0.0,
1123 |sp, pv| sp - pv,
1124 ));
1125 mpid
1126 }
1127
1128 #[inline(always)]
1129 pub fn add_x_measurement(&mut self, time: f64, pv: f32) {
1130 if let Some(controller) = &mut self.x_controller {
1131 controller.add_measurement(time, pv);
1132 }
1133 }
1134
1135 #[inline(always)]
1136 pub fn add_y_measurement(&mut self, time: f64, pv: f32) {
1137 if let Some(controller) = &mut self.y_controller {
1138 controller.add_measurement(time, pv);
1139 }
1140 }
1141
1142 #[inline(always)]
1143 pub fn add_z_measurement(&mut self, time: f64, pv: f32) {
1144 if let Some(controller) = &mut self.z_controller {
1145 controller.add_measurement(time, pv);
1146 }
1147 }
1148
1149 #[inline(always)]
1150 pub fn add_measurement(&mut self, time: f64, pos: Vec3<f32>) {
1151 if let Some(controller) = &mut self.x_controller {
1152 controller.add_measurement(time, pos.x);
1153 }
1154 if let Some(controller) = &mut self.y_controller {
1155 controller.add_measurement(time, pos.y);
1156 }
1157 if let Some(controller) = &mut self.z_controller {
1158 controller.add_measurement(time, pos.z);
1159 }
1160 }
1161
1162 #[inline(always)]
1163 pub fn calc_err_x(&self) -> Option<f32> {
1164 self.x_controller
1165 .as_ref()
1166 .map(|controller| controller.calc_err())
1167 }
1168
1169 #[inline(always)]
1170 pub fn calc_err_y(&self) -> Option<f32> {
1171 self.y_controller
1172 .as_ref()
1173 .map(|controller| controller.calc_err())
1174 }
1175
1176 #[inline(always)]
1177 pub fn calc_err_z(&self) -> Option<f32> {
1178 self.z_controller
1179 .as_ref()
1180 .map(|controller| controller.calc_err())
1181 }
1182
1183 #[inline(always)]
1184 pub fn limit_windup_x<F>(&mut self, f: F)
1185 where
1186 F: Fn(&mut f64),
1187 {
1188 if let Some(controller) = &mut self.x_controller {
1189 controller.limit_integral_windup(f);
1190 }
1191 }
1192
1193 #[inline(always)]
1194 pub fn limit_windup_y<F>(&mut self, f: F)
1195 where
1196 F: Fn(&mut f64),
1197 {
1198 if let Some(controller) = &mut self.y_controller {
1199 controller.limit_integral_windup(f);
1200 }
1201 }
1202
1203 #[inline(always)]
1204 pub fn limit_windup_z<F>(&mut self, f: F)
1205 where
1206 F: Fn(&mut f64),
1207 {
1208 if let Some(controller) = &mut self.z_controller {
1209 controller.limit_integral_windup(f);
1210 }
1211 }
1212}
1213
1214pub fn pid_coefficients(body: &Body) -> Option<(f32, f32, f32)> {
1217 match body {
1219 Body::Ship(ship::Body::AirBalloon) => {
1220 let kp = 1.0;
1221 let ki = 0.1;
1222 let kd = 0.8;
1223 Some((kp, ki, kd))
1224 },
1225 Body::Object(object::Body::Crux) => Some((0.9, 0.3, 1.0)),
1226 _ => None,
1227 }
1228}
1229
1230pub fn pid_coefficients_for_mode(mode: FlightMode, z_axis: bool) -> (f32, f32, f32) {
1232 match mode {
1233 FlightMode::FlyThrough => {
1234 if z_axis {
1235 (1.0, 0.4, 0.25)
1236 } else {
1237 (0.0, 0.0, 0.0)
1238 }
1239 },
1240 FlightMode::Braking(braking_mode) => match braking_mode {
1241 BrakingMode::Normal => (1.0, 0.3, 0.4),
1242 BrakingMode::Precise => (0.9, 0.3, 1.0),
1243 },
1244 }
1245}