veloren_common/comp/buff.rs
1use crate::{
2 combat::{
3 AttackEffect, AttackSource, AttackedModification, AttackedModifier, CombatBuff,
4 CombatBuffStrength, CombatEffect, CombatModification, CombatRequirement, ScalingKind,
5 StatEffect, StatEffectTarget,
6 },
7 comp::{Mass, Stats, aura::AuraKey, tool::ToolKind},
8 link::DynWeakLinkHandle,
9 match_some,
10 resources::{Secs, Time},
11 uid::Uid,
12};
13
14use core::cmp::Ordering;
15use enum_map::{Enum, EnumMap};
16use itertools::Either;
17use serde::{Deserialize, Serialize};
18use slotmap::{SlotMap, new_key_type};
19use specs::{Component, DerefFlaggedStorage, VecStorage};
20use strum::EnumIter;
21
22use super::Body;
23
24new_key_type! { pub struct BuffKey; }
25
26/// De/buff Kind.
27/// This is used to determine what effects a buff will have
28#[derive(
29 Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, PartialOrd, Ord, EnumIter, Enum,
30)]
31pub enum BuffKind {
32 // =================
33 // BUFFS
34 // =================
35 /// Restores health/time for some period.
36 /// Strength should be the healing per second.
37 Regeneration,
38 /// Restores health/time for some period for consumables.
39 /// Strength should be the healing per second.
40 Saturation,
41 /// Applied when drinking a potion.
42 /// Strength should be the healing per second.
43 Potion,
44 /// Increases movement speed and vulnerability to damage as well as
45 /// decreases the amount of damage dealt.
46 /// Movement speed increases linearly with strength 1.0 is an 100% increase
47 /// Damage vulnerability and damage reduction are both hard set to 100%
48 Agility,
49 /// Applied when resting (sitting at campfire or sleeping).
50 /// Strength is fraction of health restored per second.
51 RestingHeal,
52 /// Restores energy/time for some period.
53 /// Strength should be the energy regenerated per second.
54 EnergyRegen,
55 /// Generates combo over time for some period.
56 /// Strength should be the combo generated per second.
57 ComboGeneration,
58 /// Raises maximum energy.
59 /// Strength should be 10x the effect to max energy.
60 IncreaseMaxEnergy,
61 /// Raises maximum health.
62 /// Strength should be the effect to max health.
63 IncreaseMaxHealth,
64 /// Makes you immune to attacks.
65 /// Strength does not affect this buff.
66 Invulnerability,
67 /// Reduces incoming damage.
68 /// Strength scales the damage reduction non-linearly. 0.5 provides 50% DR,
69 /// 1.0 provides 67% DR.
70 ProtectingWard,
71 /// Increases movement speed and gives health regeneration.
72 /// Strength scales the movement speed linearly. 0.5 is 150% speed, 1.0 is
73 /// 200% speed. Provides regeneration at 10x the value of the strength.
74 Frenzied,
75 /// Increases movement and attack speed Strength scales strength of both
76 /// effects linearly. 0.5 is a 50% increase, 1.0 is a 100% increase.
77 Hastened,
78 /// Increases resistance to incoming poise, and poise damage dealt as health
79 /// is lost.
80 /// Strength scales the resistance non-linearly. 0.5 provides 50%, 1.0
81 /// provides 67%.
82 /// Strength scales the poise damage increase linearly, a strength of 1.0
83 /// and n health less from maximum health will cause poise damage to
84 /// increase by n%.
85 Fortitude,
86 /// Increases both attack damage and vulnerability to damage.
87 /// Damage increases linearly with strength, 1.0 is a 100% increase.
88 /// Damage reduction decreases linearly with strength, 1.0 is a 100%
89 /// decrease.
90 Reckless,
91 /// Provides immunity to burning and increases movement speed in lava.
92 /// Movement speed increases linearly with strength, 1.0 is a 100% increase.
93 // SalamanderAspect, TODO: Readd in second dwarven mine MR
94 /// Your attacks cause targets to receive the burning debuff
95 /// Strength of burning debuff is a fraction of the damage, fraction
96 /// increases linearly with strength
97 Flame,
98 /// Your attacks cause targets to receive the frozen debuff
99 /// Strength of frozen debuff is equal to the strength of this buff
100 Frigid,
101 /// Your attacks have lifesteal
102 /// Strength increases the fraction of damage restored as life
103 Lifesteal,
104 /// Your attacks against bleeding targets have lifesteal
105 /// Strength increases the fraction of damage restored as life
106 Bloodfeast,
107 /// Guarantees that the next attack is a precise hit. Does this kind of
108 /// hackily by adding 100% to the precision, will need to be adjusted if we
109 /// ever allow double precision hits instead of treating 100 as a
110 /// ceiling.
111 ImminentCritical,
112 /// Increases combo gain, every 1 strength increases combo per strike by 1,
113 /// rounds to nearest integer
114 Fury,
115 /// Allows attacks to ignore DR and increases energy reward
116 /// DR penetration is non-linear, 0.5 is 50% penetration and 1.0 is a 67%
117 /// penetration. Energy reward is increased linearly to strength, 1.0 is a
118 /// 150 % increase.
119 Sunderer,
120 /// Generates combo when damaged.
121 /// Combo generation is linear with strength, 1.0 is 5 combo generated
122 /// on being hit.
123 Defiance,
124 /// Increases both attack damage, vulnerability to damage, attack speed, and
125 /// movement speed Damage increases linearly with strength, 1.0 is a
126 /// 100% increase. Damage reduction decreases linearly with strength,
127 /// 1.0 is a 100% Attack speed increases non-linearly with strength, 0.5
128 /// is a 25% increase, 1.0 is a 33% increase Movement speed increases
129 /// non-linearly with strength, 0.5 is a 12.5% increase, 1.0 is a 16.7%
130 /// increase decrease.
131 Berserk,
132 /// Increases poise resistance and energy reward. However if killed, buffs
133 /// killer with Reckless buff. Poise resistance scales non-linearly with
134 /// strength, 0.5 is 50% and 1.0 is 67%. Energy reward scales linearly with
135 /// strength, 0.5 is +50% and 1.0 is +100% strength. Reckless buff reward
136 /// strength is equal to scornful taunt buff strength.
137 ScornfulTaunt,
138 /// Increases damage resistance, causes energy to be generated when damaged,
139 /// and decreases movement speed. Damage resistance increases non-linearly
140 /// with strength, 0.5 is 25% and 1.0 is 34%. Energy generation is linear
141 /// with strength, 1.0 is 10 energy per hit. Movement speed is decreased to
142 /// 70%.
143 Tenacity,
144 /// Applies to some debuffs that have strong CC effects. Automatically
145 /// gained upon receiving those debuffs, and causes future instances of
146 /// those debuffs to be applied with reduced duration.
147 /// Strength linearly decreases the duration of newly applied, affected
148 /// debuffs, 0.5 is a 50% reduction.
149 Resilience,
150 /// Causes the next attack to have precision of 1.0 if the target is not
151 /// wielding their weapon, and also generally increases damage.
152 /// Strength linearly increases the damage increase.
153 OwlTalon,
154 /// Causes the next projectile fired to have more knockback and poise
155 /// damage.
156 /// Strength linearly increases the knockback and poise damage applied to
157 /// the next projectile.
158 HeavyNock,
159 /// Causes the next projectile to both gain precision and restore more
160 /// energy.
161 /// Strength linearly increases the precision override and energy restored.
162 Heartseeker,
163 /// Causes projectile attacks to have more precision power, and to guarantee
164 /// a minimum precision multiplier.
165 /// Strength linearly increases both. The minimum precision power is
166 /// equivalent to the buff strength, and the additional precision power is
167 /// 50% of the buff strength.
168 EagleEye,
169 /// Causes the next projectile fired to debuff the target with ArdentHunted.
170 /// Projectiles fired at the target generate additional combo, and
171 /// increase energy reward by a percentage.
172 /// Strength linearly increases the amount of additional combo generated and
173 /// the additional energy reward.
174 ArdentHunter,
175 /// Causes the next projectile fired to do additional damage for every
176 /// debuff the target has that had been inflicted by the attacker when using
177 /// a bow.
178 /// Strength linearly increases the amount of additional damage.
179 SepticShot,
180 // =================
181 // DEBUFFS
182 // =================
183 /// Does damage to a creature over time.
184 /// Strength should be the DPS of the debuff.
185 /// Provides immunity against Frozen.
186 Burning,
187 /// Lowers health over time for some duration.
188 /// Strength should be the DPS of the debuff.
189 Bleeding,
190 /// Lower a creature's max health over time.
191 /// Strength only affects the target max health, 0.5 targets 50% of base
192 /// max, 1.0 targets 100% of base max.
193 Cursed,
194 /// Reduces movement speed and causes bleeding damage.
195 /// Strength scales the movement speed debuff non-linearly. 0.5 is 50%
196 /// speed, 1.0 is 33% speed. Bleeding is at 4x the value of the strength.
197 Crippled,
198 /// Slows movement and attack speed and increases poise damage received.
199 /// Strength scales the attack speed debuff non-linearly. 0.5 is ~50%
200 /// speed, 1.0 is 33% speed. Movement speed debuff is scaled to be slightly
201 /// smaller than attack speed debuff. Received poise damage scales linearly,
202 /// 1.0 is a 100% increase.
203 /// Provides immunity against Heatstroke and Chilled.
204 Frozen,
205 /// Makes you wet and causes you to have reduced friction on the ground.
206 /// Strength scales the friction you ignore non-linearly. 0.5 is 50% ground
207 /// friction, 1.0 is 33% ground friction.
208 /// Provides immunity against Burning.
209 Wet,
210 /// Makes you move slower.
211 /// Strength scales the movement speed debuff non-linearly. 0.5 is 50%
212 /// speed, 1.0 is 33% speed.
213 Ensnared,
214 /// Drain stamina to a creature over time.
215 /// Strength should be the energy per second of the debuff.
216 Poisoned,
217 /// Results from having an attack parried.
218 /// Causes your attack speed to be slower to emulate the recover duration of
219 /// an ability being lengthened.
220 Parried,
221 /// Results from drinking a potion.
222 /// Decreases the health gained from subsequent potions.
223 PotionSickness,
224 /// Slows movement speed and reduces energy reward.
225 /// Both scales non-linearly to strength, 0.5 lead to movespeed reduction
226 /// by 25% and energy reward reduced by 150%, 1.0 lead to MS reduction by
227 /// 33.3% and energy reward reduced by 200%. Energy reward can't be
228 /// reduced by more than 200%, to a minimum value of -100%.
229 Heatstroke,
230 /// Reduces movement speed to 0.
231 /// Strength increases the relative mass of the creature that can be
232 /// targeted. A strength of 1.0 means that a creature of the same mass gets
233 /// rooted for the full duration. A strength of 2.0 means a creature of
234 /// twice the mass gets rooted for the full duration. If the target's mass
235 /// is higher than the strength allows for, duration gets reduced using a
236 /// mutiplier from the ratio of masses.
237 Rooted,
238 /// Slows movement speed and reduces energy reward
239 /// Both scale non-linearly with strength, 0.5 leads to 50% reduction of
240 /// energy reward and 33% reduction of move speed. 1.0 leads to 67%
241 /// reduction of energy reward and 50% reduction of move speed.
242 Winded,
243 /// Prevents use of auxiliary abilities.
244 /// Does not scale with strength
245 Amnesia,
246 /// Increases amount of poise damage received
247 /// Scales linearly with strength, 1.0 leads to 100% more poise damage
248 /// received
249 OffBalance,
250 /// Decreases movement speed and increases amount of poise damage received.
251 /// Movement speed decreases non-linearly with strength, 0.5 leads to a 25%
252 /// reduction, 1.0 leads to a 33% reduction. Poise damage received scales
253 /// linearly with strength, 1.0 leads to 100% more poise damage.
254 /// Provides immunity to Heatstroke.
255 Chilled,
256 /// Increases combo generation and energy reward when hit with projectiles.
257 /// Strength linearly increases the amount of additional combo generated and
258 /// the additional energy reward.
259 ArdentHunted,
260 // =================
261 // COMPLEX
262 // =================
263 /// Changed into another body.
264 Polymorphed,
265}
266
267/// Tells a little more about the buff kind than simple buff/debuff
268#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub enum BuffDescriptor {
270 /// Simple positive buffs, like `BuffKind::Saturation`
271 SimplePositive,
272 /// Simple negative buffs, like `BuffKind::Bleeding`
273 SimpleNegative,
274 /// Buffs that require unusual data that can't be governed just by strength
275 /// and duration, like `BuffKind::Polymorhped`
276 Complex,
277 // For future additions, we may want to tell about non-obvious buffs,
278 // like Agility.
279 // Also maybe extend Complex to differentiate between Positive, Negative
280 // and Neutral buffs?
281 // For now, Complex is assumed to be neutral/non-obvious.
282}
283
284impl BuffKind {
285 /// Tells a little more about buff kind than simple buff/debuff
286 ///
287 /// Read more in [BuffDescriptor].
288 pub fn differentiate(self) -> BuffDescriptor {
289 match self {
290 BuffKind::Regeneration
291 | BuffKind::Saturation
292 | BuffKind::Potion
293 | BuffKind::Agility
294 | BuffKind::RestingHeal
295 | BuffKind::Frenzied
296 | BuffKind::EnergyRegen
297 | BuffKind::ComboGeneration
298 | BuffKind::IncreaseMaxEnergy
299 | BuffKind::IncreaseMaxHealth
300 | BuffKind::Invulnerability
301 | BuffKind::ProtectingWard
302 | BuffKind::Hastened
303 | BuffKind::Fortitude
304 | BuffKind::Reckless
305 | BuffKind::Flame
306 | BuffKind::Frigid
307 | BuffKind::Lifesteal
308 //| BuffKind::SalamanderAspect
309 | BuffKind::ImminentCritical
310 | BuffKind::Fury
311 | BuffKind::Sunderer
312 | BuffKind::Defiance
313 | BuffKind::Bloodfeast
314 | BuffKind::Berserk
315 | BuffKind::ScornfulTaunt
316 | BuffKind::Tenacity
317 | BuffKind::Resilience
318 | BuffKind::OwlTalon
319 | BuffKind::HeavyNock
320 | BuffKind::Heartseeker
321 | BuffKind::EagleEye
322 | BuffKind::ArdentHunter
323 | BuffKind::SepticShot => BuffDescriptor::SimplePositive,
324 BuffKind::Bleeding
325 | BuffKind::Cursed
326 | BuffKind::Burning
327 | BuffKind::Crippled
328 | BuffKind::Frozen
329 | BuffKind::Wet
330 | BuffKind::Ensnared
331 | BuffKind::Poisoned
332 | BuffKind::Parried
333 | BuffKind::PotionSickness
334 | BuffKind::Heatstroke
335 | BuffKind::Rooted
336 | BuffKind::Winded
337 | BuffKind::Amnesia
338 | BuffKind::OffBalance
339 | BuffKind::Chilled
340 | BuffKind::ArdentHunted => BuffDescriptor::SimpleNegative,
341 BuffKind::Polymorphed => BuffDescriptor::Complex,
342 }
343 }
344
345 /// Checks if buff is buff or debuff.
346 pub fn is_buff(self) -> bool {
347 match self.differentiate() {
348 BuffDescriptor::SimplePositive => true,
349 BuffDescriptor::SimpleNegative | BuffDescriptor::Complex => false,
350 }
351 }
352
353 pub fn is_simple(self) -> bool {
354 match self.differentiate() {
355 BuffDescriptor::SimplePositive | BuffDescriptor::SimpleNegative => true,
356 BuffDescriptor::Complex => false,
357 }
358 }
359
360 /// Checks if buff should queue.
361 pub fn queues(self) -> bool { matches!(self, BuffKind::Saturation) }
362
363 /// Checks if the buff can affect other buff effects applied in the same
364 /// tick.
365 pub fn affects_subsequent_buffs(self) -> bool {
366 matches!(
367 self,
368 BuffKind::PotionSickness /* | BuffKind::SalamanderAspect */
369 )
370 }
371
372 /// Checks if multiple instances of the buff should be processed, instead of
373 /// only the strongest.
374 pub fn stacks(self) -> bool { matches!(self, BuffKind::PotionSickness | BuffKind::Resilience) }
375
376 pub fn effects(&self, data: &BuffData, source_entity: Option<Uid>) -> Vec<BuffEffect> {
377 // Normalized nonlinear scaling
378 // TODO: Do we want to make denominator term parameterized. Come back to if we
379 // add nn_scaling3.
380 let nn_scaling = |a: f32| a.abs() / (a.abs() + 0.5) * a.signum();
381 let nn_scaling2 = |a: f32| a.abs() / (a.abs() + 1.0) * a.signum();
382 let instance = rand::random();
383 match self {
384 BuffKind::Bleeding => vec![BuffEffect::HealthChangeOverTime {
385 rate: -data.strength,
386 kind: ModifierKind::Additive,
387 instance,
388 tick_dur: Secs(0.5),
389 }],
390 BuffKind::Regeneration => vec![BuffEffect::HealthChangeOverTime {
391 rate: data.strength,
392 kind: ModifierKind::Additive,
393 instance,
394 tick_dur: Secs(1.0),
395 }],
396 BuffKind::Saturation => vec![BuffEffect::HealthChangeOverTime {
397 rate: data.strength,
398 kind: ModifierKind::Additive,
399 instance,
400 tick_dur: Secs(3.0),
401 }],
402 BuffKind::Potion => {
403 vec![BuffEffect::HealthChangeOverTime {
404 rate: data.strength,
405 kind: ModifierKind::Additive,
406 instance,
407 tick_dur: Secs(0.1),
408 }]
409 },
410 BuffKind::Agility => vec![
411 BuffEffect::MovementSpeed(1.0 + data.strength),
412 BuffEffect::DamageReduction(-1.0),
413 BuffEffect::AttackDamage(0.0),
414 ],
415 BuffKind::RestingHeal => vec![BuffEffect::HealthChangeOverTime {
416 rate: data.strength,
417 kind: ModifierKind::Multiplicative,
418 instance,
419 tick_dur: Secs(2.0),
420 }],
421 BuffKind::Cursed => vec![
422 BuffEffect::MaxHealthChangeOverTime {
423 rate: -1.0,
424 kind: ModifierKind::Additive,
425 target_fraction: 1.0 - data.strength,
426 },
427 BuffEffect::HealthChangeOverTime {
428 rate: -1.0,
429 kind: ModifierKind::Additive,
430 instance,
431 tick_dur: Secs(0.5),
432 },
433 ],
434 BuffKind::EnergyRegen => vec![BuffEffect::EnergyChangeOverTime {
435 rate: data.strength,
436 kind: ModifierKind::Additive,
437 tick_dur: Secs(0.25),
438 reset_rate_on_tick: false,
439 }],
440 BuffKind::ComboGeneration => {
441 let target_tick_dur = 0.25;
442 // Combo per tick must be an integer
443 let nearest_valid_tick_dur =
444 (data.strength as f64 * target_tick_dur).round() / data.strength as f64;
445
446 vec![BuffEffect::ComboChangeOverTime {
447 rate: data.strength,
448 tick_dur: Secs(nearest_valid_tick_dur),
449 }]
450 },
451 BuffKind::IncreaseMaxEnergy => vec![BuffEffect::MaxEnergyModifier {
452 value: data.strength,
453 kind: ModifierKind::Additive,
454 }],
455 BuffKind::IncreaseMaxHealth => vec![BuffEffect::MaxHealthModifier {
456 value: data.strength,
457 kind: ModifierKind::Additive,
458 }],
459 BuffKind::Invulnerability => vec![BuffEffect::DamageReduction(1.0)],
460 BuffKind::ProtectingWard => vec![BuffEffect::DamageReduction(
461 // Causes non-linearity in effect strength, but necessary
462 // to allow for tool power and other things to affect the
463 // strength. 0.5 also still provides 50% damage reduction.
464 nn_scaling(data.strength),
465 )],
466 BuffKind::Burning => vec![
467 BuffEffect::HealthChangeOverTime {
468 rate: -data.strength,
469 kind: ModifierKind::Additive,
470 instance,
471 tick_dur: Secs(0.25),
472 },
473 BuffEffect::BuffImmunity(BuffKind::Frozen),
474 ],
475 BuffKind::Poisoned => vec![BuffEffect::EnergyChangeOverTime {
476 rate: -data.strength,
477 kind: ModifierKind::Additive,
478 tick_dur: Secs(0.5),
479 reset_rate_on_tick: true,
480 }],
481 BuffKind::Crippled => vec![
482 BuffEffect::MovementSpeed(1.0 - nn_scaling(data.strength)),
483 BuffEffect::HealthChangeOverTime {
484 rate: -data.strength * 4.0,
485 kind: ModifierKind::Additive,
486 instance,
487 tick_dur: Secs(0.5),
488 },
489 ],
490 BuffKind::Frenzied => vec![
491 BuffEffect::MovementSpeed(1.0 + data.strength),
492 BuffEffect::HealthChangeOverTime {
493 rate: data.strength * 10.0,
494 kind: ModifierKind::Additive,
495 instance,
496 tick_dur: Secs(1.0),
497 },
498 ],
499 BuffKind::Frozen => vec![
500 BuffEffect::MovementSpeed(f32::powf(1.0 - nn_scaling(data.strength), 1.1)),
501 BuffEffect::AttackSpeed(1.0 - nn_scaling(data.strength)),
502 BuffEffect::PoiseReduction(-data.strength),
503 BuffEffect::BuffImmunity(BuffKind::Heatstroke),
504 BuffEffect::BuffImmunity(BuffKind::Chilled),
505 ],
506 BuffKind::Chilled => vec![
507 BuffEffect::MovementSpeed(1.0 - 0.5 * nn_scaling(data.strength)),
508 BuffEffect::PoiseReduction(-data.strength),
509 BuffEffect::BuffImmunity(BuffKind::Heatstroke),
510 ],
511 BuffKind::Wet => vec![
512 BuffEffect::GroundFriction(1.0 - nn_scaling(data.strength)),
513 BuffEffect::BuffImmunity(BuffKind::Burning),
514 ],
515 BuffKind::Ensnared => vec![BuffEffect::MovementSpeed(1.0 - nn_scaling(data.strength))],
516 BuffKind::Hastened => vec![
517 BuffEffect::MovementSpeed(1.0 + data.strength),
518 BuffEffect::AttackSpeed(1.0 + data.strength),
519 ],
520 BuffKind::Fortitude => vec![
521 BuffEffect::PoiseReduction(nn_scaling(data.strength)),
522 BuffEffect::PoiseDamageFromLostHealth(data.strength),
523 ],
524 BuffKind::Parried => vec![BuffEffect::PrecisionVulnerabilityOverride(0.75)],
525 BuffKind::PotionSickness => vec![BuffEffect::ItemEffectReduction(data.strength)],
526 BuffKind::Reckless => vec![
527 BuffEffect::DamageReduction(-data.strength),
528 BuffEffect::AttackDamage(1.0 + data.strength),
529 ],
530 BuffKind::Polymorphed => {
531 let mut effects = Vec::new();
532 if let Some(MiscBuffData::Body(body)) = data.misc_data {
533 effects.push(BuffEffect::BodyChange(body));
534 }
535 effects
536 },
537 BuffKind::Flame => vec![BuffEffect::AttackEffect(AttackEffect::new(
538 None,
539 CombatEffect::Buff(CombatBuff {
540 kind: BuffKind::Burning,
541 dur_secs: data.secondary_duration.unwrap_or(Secs(5.0)),
542 strength: CombatBuffStrength::DamageFraction(data.strength),
543 chance: 1.0,
544 }),
545 ))],
546 BuffKind::Frigid => vec![BuffEffect::AttackEffect(AttackEffect::new(
547 None,
548 CombatEffect::Buff(CombatBuff {
549 kind: BuffKind::Frozen,
550 dur_secs: data.secondary_duration.unwrap_or(Secs(5.0)),
551 strength: CombatBuffStrength::Value(data.strength),
552 chance: 1.0,
553 }),
554 ))],
555 BuffKind::Lifesteal => vec![BuffEffect::AttackEffect(AttackEffect::new(
556 None,
557 CombatEffect::Lifesteal(data.strength),
558 ))],
559 /*BuffKind::SalamanderAspect => vec![
560 BuffEffect::BuffImmunity(BuffKind::Burning),
561 BuffEffect::SwimSpeed(1.0 + data.strength),
562 ],*/
563 BuffKind::Bloodfeast => vec![BuffEffect::AttackEffect(
564 AttackEffect::new(None, CombatEffect::Lifesteal(data.strength))
565 .with_requirement(CombatRequirement::TargetHasBuff(BuffKind::Bleeding)),
566 )],
567 BuffKind::ImminentCritical => vec![BuffEffect::PrecisionModifier(None, 1.0, false)],
568 BuffKind::Fury => vec![BuffEffect::AttackEffect(
569 AttackEffect::new(None, CombatEffect::Combo(data.strength.round() as i32))
570 .with_requirement(CombatRequirement::AnyDamage),
571 )],
572 BuffKind::Sunderer => vec![
573 BuffEffect::MitigationsPenetration(nn_scaling(data.strength)),
574 BuffEffect::EnergyReward(1.0 + 1.5 * data.strength),
575 ],
576 BuffKind::Defiance => vec![BuffEffect::DamagedEffect(StatEffect::new(
577 StatEffectTarget::Target,
578 CombatEffect::Combo((data.strength * 5.0).round() as i32),
579 ))],
580 BuffKind::Berserk => vec![
581 BuffEffect::DamageReduction(-data.strength),
582 BuffEffect::AttackDamage(1.0 + data.strength),
583 BuffEffect::AttackSpeed(1.0 + nn_scaling(data.strength) / 2.0),
584 BuffEffect::MovementSpeed(1.0 + nn_scaling(data.strength) / 4.0),
585 ],
586 BuffKind::Heatstroke => vec![
587 BuffEffect::MovementSpeed(1.0 - nn_scaling(data.strength) * 0.5),
588 BuffEffect::EnergyReward((1.0 - nn_scaling(data.strength) * 3.0).max(-1.0)),
589 ],
590 BuffKind::ScornfulTaunt => vec![
591 BuffEffect::PoiseReduction(nn_scaling(data.strength)),
592 BuffEffect::EnergyReward(1.0 + data.strength),
593 BuffEffect::DeathEffect(StatEffect::new(
594 StatEffectTarget::Attacker,
595 CombatEffect::Buff(CombatBuff {
596 kind: BuffKind::Reckless,
597 dur_secs: data.duration.unwrap_or(Secs(10.0)),
598 strength: CombatBuffStrength::Value(data.strength),
599 chance: 1.0,
600 }),
601 )),
602 ],
603 BuffKind::Rooted => vec![BuffEffect::MovementSpeed(0.0)],
604 BuffKind::Winded => vec![
605 BuffEffect::MovementSpeed(1.0 - nn_scaling2(data.strength)),
606 BuffEffect::EnergyReward(1.0 - nn_scaling(data.strength)),
607 ],
608 BuffKind::Amnesia => vec![BuffEffect::DisableAuxiliaryAbilities],
609 BuffKind::OffBalance => vec![BuffEffect::PoiseReduction(-data.strength)],
610 BuffKind::Tenacity => vec![
611 BuffEffect::DamageReduction(nn_scaling(data.strength) / 2.0),
612 BuffEffect::MovementSpeed(0.7),
613 BuffEffect::DamagedEffect(StatEffect::new(
614 StatEffectTarget::Target,
615 CombatEffect::Energy(data.strength * 10.0),
616 )),
617 ],
618 BuffKind::Resilience => vec![BuffEffect::CrowdControlResistance(data.strength)],
619 BuffKind::OwlTalon => vec![
620 BuffEffect::PrecisionModifier(Some(CombatRequirement::TargetUnwielded), 0.8, false),
621 BuffEffect::AttackDamage(1.0 + data.strength),
622 ],
623 BuffKind::HeavyNock => {
624 let range_mod = CombatModification::RangeWeakening {
625 start_dist: 5.0,
626 end_dist: 50.0,
627 min_str: 0.3,
628 };
629 let poise = AttackEffect::new(None, CombatEffect::Poise(35.0 * data.strength))
630 .with_requirement(CombatRequirement::AnyDamage)
631 .with_requirement(CombatRequirement::AttackSource(AttackSource::Projectile))
632 .with_modification(range_mod);
633 vec![
634 BuffEffect::KnockbackMult(data.strength * 5.0),
635 BuffEffect::AttackEffect(poise),
636 BuffEffect::AttackDamage(0.75), // TODO: has no effect on damage?
637 ]
638 },
639 BuffKind::Heartseeker => {
640 let energy =
641 AttackEffect::new(None, CombatEffect::EnergyReward(14.0 * data.strength))
642 .with_requirement(CombatRequirement::AnyDamage)
643 .with_requirement(CombatRequirement::AttackSource(
644 AttackSource::Projectile,
645 ));
646 vec![
647 BuffEffect::PrecisionModifier(
648 Some(CombatRequirement::AttackSource(AttackSource::Projectile)),
649 data.strength * 1.2,
650 false,
651 ),
652 BuffEffect::AttackEffect(energy),
653 ]
654 },
655 BuffKind::EagleEye => {
656 vec![
657 BuffEffect::PrecisionModifier(
658 Some(CombatRequirement::AttackSource(AttackSource::Projectile)),
659 data.strength,
660 false,
661 ),
662 BuffEffect::PrecisionPowerMult(1.0 + data.strength * 0.5),
663 BuffEffect::EnergyReward(0.25 + data.strength * 0.25),
664 ]
665 },
666 BuffKind::ArdentHunter => vec![BuffEffect::AttackEffect(
667 AttackEffect::new(
668 None,
669 CombatEffect::Buff(CombatBuff {
670 kind: BuffKind::ArdentHunted,
671 dur_secs: data.secondary_duration.unwrap_or(Secs(60.0)),
672 strength: CombatBuffStrength::Value(data.strength),
673 chance: 1.0,
674 }),
675 )
676 .with_requirement(CombatRequirement::AttackSource(AttackSource::Projectile)),
677 )],
678 BuffKind::ArdentHunted => {
679 let projectile_req = CombatRequirement::AttackSource(AttackSource::Projectile);
680 let mut energy_reward_effect =
681 AttackedModification::new(AttackedModifier::EnergyReward(data.strength))
682 .with_requirement(projectile_req);
683 let mut damage_mult_effect =
684 AttackedModification::new(AttackedModifier::DamageMultiplier(data.strength))
685 .with_requirement(projectile_req);
686 if let Some(uid) = source_entity {
687 let attacker_req = CombatRequirement::Attacker(uid);
688 energy_reward_effect = energy_reward_effect.with_requirement(attacker_req);
689 damage_mult_effect = damage_mult_effect.with_requirement(attacker_req);
690 }
691 vec![
692 BuffEffect::AttackedModification(energy_reward_effect),
693 BuffEffect::AttackedModification(damage_mult_effect),
694 ]
695 },
696 BuffKind::SepticShot => vec![BuffEffect::AttackEffect(
697 AttackEffect::new(None, CombatEffect::DebuffsVulnerable {
698 mult: data.strength,
699 scaling: ScalingKind::Sqrt,
700 filter_attacker: true,
701 filter_weapon: Some(ToolKind::Bow),
702 })
703 .with_requirement(CombatRequirement::AttackSource(AttackSource::Projectile)),
704 )],
705 }
706 }
707
708 fn extend_cat_ids(&self, mut cat_ids: Vec<BuffCategory>) -> Vec<BuffCategory> {
709 // TODO: Remove clippy allow after another buff needs this
710 #[expect(clippy::single_match)]
711 match self {
712 BuffKind::PotionSickness => {
713 cat_ids.push(BuffCategory::PersistOnDowned);
714 },
715 _ => {},
716 }
717 cat_ids
718 }
719
720 fn modify_data(
721 &self,
722 mut data: BuffData,
723 source_mass: Option<&Mass>,
724 dest_info: DestInfo,
725 source: BuffSource,
726 ) -> BuffData {
727 // TODO: Remove clippy allow after another buff needs this
728 #[expect(clippy::single_match)]
729 match self {
730 BuffKind::Rooted => {
731 let source_mass = source_mass.map_or(50.0, |m| m.0);
732 let dest_mass = dest_info.mass.map_or(50.0, |m| m.0);
733 let low_clamp = (0.25 + data.strength * 0.25).clamp(0.0, 1.0);
734 let high_clamp = (1.0 + data.strength * 0.5).max(1.0);
735 let ratio = (source_mass / dest_mass).clamp(low_clamp, high_clamp);
736 data.duration = data.duration.map(|dur| Secs(dur.0 * ratio as f64));
737 },
738 _ => {},
739 }
740 if self.resilience_ccr_strength(data).is_some() {
741 let dur_mult = dest_info
742 .stats
743 .map_or(1.0, |s| (1.0 - s.crowd_control_resistance).max(0.0));
744 data.duration = data.duration.map(|dur| dur * dur_mult as f64);
745 }
746 self.apply_item_effect_reduction(&mut data, source, dest_info);
747 data
748 }
749
750 /// If a buff kind should also give resilience when applied, return the
751 /// strength that resilience should have, otherwise return None
752 pub fn resilience_ccr_strength(&self, data: BuffData) -> Option<f32> {
753 match_some!(self,
754 BuffKind::Amnesia => 0.3,
755 BuffKind::Frozen => data.strength,
756 BuffKind::Winded => data.strength / 3.0,
757 BuffKind::Rooted => data.duration.map_or(0.1, |dur| dur.0 as f32 / 10.0),
758 )
759 }
760
761 pub fn apply_item_effect_reduction(
762 &self,
763 data: &mut BuffData,
764 source: BuffSource,
765 dest_info: DestInfo,
766 ) {
767 if !matches!(source, BuffSource::Item) {
768 return;
769 }
770 let item_effect_reduction = dest_info.stats.map_or(1.0, |s| s.item_effect_reduction);
771 match self {
772 BuffKind::Potion | BuffKind::Agility => {
773 data.strength *= item_effect_reduction;
774 },
775 BuffKind::Burning | BuffKind::Frozen | BuffKind::Resilience => {
776 data.duration = data.duration.map(|dur| dur * item_effect_reduction as f64);
777 },
778 _ => {},
779 };
780 }
781}
782
783// Struct used to store data relevant to a buff
784#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
785#[serde(deny_unknown_fields, default)]
786pub struct BuffData {
787 pub strength: f32,
788 #[serde(default)]
789 pub duration: Option<Secs>,
790 #[serde(default)]
791 pub delay: Option<Secs>,
792 /// Used for buffs that have rider buffs (e.g. Flame, Frigid)
793 #[serde(default)]
794 pub secondary_duration: Option<Secs>,
795 /// Used to add random data to buffs if needed (e.g. polymorphed)
796 #[serde(default)]
797 pub misc_data: Option<MiscBuffData>,
798}
799
800impl Default for BuffData {
801 fn default() -> Self { Self::new(0.0, Some(Secs(0.0))) }
802}
803
804#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
805pub enum MiscBuffData {
806 Body(Body),
807}
808
809impl BuffData {
810 pub fn new(strength: f32, duration: Option<Secs>) -> Self {
811 Self {
812 strength,
813 duration,
814 delay: None,
815 secondary_duration: None,
816 misc_data: None,
817 }
818 }
819
820 pub fn with_delay(mut self, delay: Secs) -> Self {
821 self.delay = Some(delay);
822 self
823 }
824
825 pub fn with_secondary_duration(mut self, sec_dur: Secs) -> Self {
826 self.secondary_duration = Some(sec_dur);
827 self
828 }
829
830 pub fn with_misc_data(mut self, misc_data: MiscBuffData) -> Self {
831 self.misc_data = Some(misc_data);
832 self
833 }
834}
835
836/// De/buff category ID.
837/// Similar to `BuffKind`, but to mark a category (for more generic usage, like
838/// positive/negative buffs).
839#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
840pub enum BuffCategory {
841 Natural,
842 Physical,
843 Magical,
844 Divine,
845 PersistOnDowned,
846 PersistOnDeath,
847 FromActiveAura(Uid, AuraKey),
848 FromLink(DynWeakLinkHandle),
849 RemoveOnAttack,
850 RemoveOnLoadoutChange,
851 SelfBuff,
852}
853
854#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
855pub enum ModifierKind {
856 Additive,
857 Multiplicative,
858}
859
860/// Data indicating and configuring behaviour of a de/buff.
861#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
862pub enum BuffEffect {
863 /// Periodically damages or heals entity
864 HealthChangeOverTime {
865 rate: f32,
866 kind: ModifierKind,
867 instance: u64,
868 tick_dur: Secs,
869 },
870 /// Periodically consume entity energy
871 EnergyChangeOverTime {
872 rate: f32,
873 kind: ModifierKind,
874 tick_dur: Secs,
875 reset_rate_on_tick: bool,
876 },
877 /// Periodically change entity combo
878 ComboChangeOverTime {
879 rate: f32,
880 tick_dur: Secs,
881 },
882 /// Changes maximum health by a certain amount
883 MaxHealthModifier {
884 value: f32,
885 kind: ModifierKind,
886 },
887 /// Changes maximum energy by a certain amount
888 MaxEnergyModifier {
889 value: f32,
890 kind: ModifierKind,
891 },
892 /// Reduces damage after armor is accounted for by this fraction
893 DamageReduction(f32),
894 /// Gradually changes an entities max health over time
895 MaxHealthChangeOverTime {
896 rate: f32,
897 kind: ModifierKind,
898 target_fraction: f32,
899 },
900 /// Modifies move speed of target
901 MovementSpeed(f32),
902 /// Modifies attack speed of target
903 AttackSpeed(f32),
904 /// Modifies recovery speed of target
905 RecoverySpeed(f32),
906 /// Modifies ground friction of target
907 GroundFriction(f32),
908 /// Reduces poise damage taken after armor is accounted for by this fraction
909 PoiseReduction(f32),
910 /// Increases poise damage dealt when health is lost
911 PoiseDamageFromLostHealth(f32),
912 /// Modifier to the amount of damage dealt with attacks
913 AttackDamage(f32),
914 /// Adds a precision modifier applied to an attack if the condition
915 /// is met, also allows for the modifier to optionally override other
916 /// precision bonuses
917 PrecisionModifier(Option<CombatRequirement>, f32, bool),
918 /// Overrides the precision multiplier applied to an incoming attack
919 PrecisionVulnerabilityOverride(f32),
920 /// Changes body.
921 BodyChange(Body),
922 BuffImmunity(BuffKind),
923 SwimSpeed(f32),
924 /// Add an attack effect to attacks made while buff is active
925 AttackEffect(AttackEffect),
926 /// Increases poise damage dealt by attacks
927 AttackPoise(f32),
928 /// Ignores some damage reduction on target
929 MitigationsPenetration(f32),
930 /// Modifies energy rewarded on successful strikes
931 EnergyReward(f32),
932 /// Add an effect to the entity when damaged by an attack
933 DamagedEffect(StatEffect),
934 /// Add an effect to the entity when killed
935 DeathEffect(StatEffect),
936 /// Prevents use of auxiliary abilities
937 DisableAuxiliaryAbilities,
938 /// Reduces duration of crowd control debuffs
939 CrowdControlResistance(f32),
940 /// Reduces the strength or duration of item buff
941 ItemEffectReduction(f32),
942 /// Adds an effect that modifies how attacks are applied to this entity
943 AttackedModification(AttackedModification),
944 /// Multiplies the precision damage applied to attacks made
945 PrecisionPowerMult(f32),
946 /// Multiplies knockback dealt by attacks
947 KnockbackMult(f32),
948}
949
950/// Actual de/buff.
951/// Buff can timeout after some time if `time` is Some. If `time` is None,
952/// Buff will last indefinitely, until removed manually (by some action, like
953/// uncursing).
954///
955/// Buff has a kind, which is used to determine the effects in a builder
956/// function.
957///
958/// To provide more classification info when needed,
959/// buff can be in one or more buff category.
960#[derive(Clone, Debug, Serialize, Deserialize)]
961pub struct Buff {
962 pub kind: BuffKind,
963 pub data: BuffData,
964 pub cat_ids: Vec<BuffCategory>,
965 pub end_time: Option<Time>,
966 pub start_time: Time,
967 pub effects: Vec<BuffEffect>,
968 pub source: BuffSource,
969}
970
971/// Information about whether buff addition or removal was requested.
972/// This to implement "on_add" and "on_remove" hooks for constant buffs.
973#[derive(Clone, Debug)]
974pub enum BuffChange {
975 /// Adds this buff.
976 Add(Buff),
977 /// Removes all buffs with this ID.
978 RemoveByKind(BuffKind),
979 /// Removes all buffs with this ID, but not debuffs.
980 RemoveFromController(BuffKind),
981 /// Removes buffs of these indices, should only be called when buffs expire
982 RemoveByKey(Vec<BuffKey>),
983 /// Removes buffs of these categories (first vec is of categories of which
984 /// all are required, second vec is of categories of which at least one is
985 /// required, third vec is of categories that will not be removed)
986 RemoveByCategory {
987 all_required: Vec<BuffCategory>,
988 any_required: Vec<BuffCategory>,
989 none_required: Vec<BuffCategory>,
990 },
991 /// Refreshes durations of all buffs with this kind.
992 Refresh(BuffKind),
993}
994
995impl Buff {
996 /// Builder function for buffs
997 pub fn new(
998 kind: BuffKind,
999 data: BuffData,
1000 cat_ids: Vec<BuffCategory>,
1001 source: BuffSource,
1002 time: Time,
1003 dest_info: DestInfo,
1004 // Create source_info if we need more parameters from source
1005 source_mass: Option<&Mass>,
1006 ) -> Self {
1007 let data = kind.modify_data(data, source_mass, dest_info, source);
1008 let source_uid = if let BuffSource::Character { by, .. } = source {
1009 Some(by)
1010 } else {
1011 None
1012 };
1013 let effects = kind.effects(&data, source_uid);
1014 let cat_ids = kind.extend_cat_ids(cat_ids);
1015 let start_time = Time(time.0 + data.delay.map_or(0.0, |delay| delay.0));
1016 let end_time = if cat_ids.iter().any(|cat_id| {
1017 matches!(
1018 cat_id,
1019 BuffCategory::FromActiveAura(..) | BuffCategory::FromLink(_)
1020 )
1021 }) {
1022 None
1023 } else {
1024 data.duration.map(|dur| Time(start_time.0 + dur.0))
1025 };
1026 Buff {
1027 kind,
1028 data,
1029 cat_ids,
1030 start_time,
1031 end_time,
1032 effects,
1033 source,
1034 }
1035 }
1036
1037 /// Calculate how much time has elapsed since the buff was applied
1038 pub fn elapsed(&self, time: Time) -> Secs { Secs(time.0 - self.start_time.0) }
1039}
1040
1041impl PartialOrd for Buff {
1042 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1043 if self == other {
1044 Some(Ordering::Equal)
1045 } else if self.data.strength > other.data.strength {
1046 Some(Ordering::Greater)
1047 } else if self.data.strength < other.data.strength {
1048 Some(Ordering::Less)
1049 } else if self.data.delay.is_none() && other.data.delay.is_some() {
1050 Some(Ordering::Greater)
1051 } else if self.data.delay.is_some() && other.data.delay.is_none() {
1052 Some(Ordering::Less)
1053 } else if compare_end_time(self.end_time, other.end_time) {
1054 Some(Ordering::Greater)
1055 } else if compare_end_time(other.end_time, self.end_time) {
1056 Some(Ordering::Less)
1057 } else {
1058 None
1059 }
1060 }
1061}
1062
1063fn compare_end_time(a: Option<Time>, b: Option<Time>) -> bool {
1064 a.is_none_or(|time_a| b.is_some_and(|time_b| time_a.0 > time_b.0))
1065}
1066
1067impl PartialEq for Buff {
1068 fn eq(&self, other: &Self) -> bool {
1069 self.data.strength == other.data.strength
1070 && self.end_time == other.end_time
1071 && self.start_time == other.start_time
1072 }
1073}
1074
1075/// Source of the de/buff
1076#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
1077pub enum BuffSource {
1078 /// Applied by a character
1079 Character {
1080 by: Uid,
1081 tool_kind: Option<ToolKind>,
1082 },
1083 /// Applied by world, like a poisonous fumes from a swamp
1084 World,
1085 /// Applied by command
1086 Command,
1087 /// Applied by an item
1088 Item,
1089 /// Applied by another buff (like an after-effect)
1090 Buff,
1091 /// Applied by a block
1092 Block,
1093 /// Some other source
1094 Unknown,
1095}
1096
1097/// Component holding all de/buffs that gets resolved each tick.
1098/// On each tick, remaining time of buffs get lowered and
1099/// buff effect of each buff is applied or not, depending on the `BuffEffect`
1100/// (specs system will decide based on `BuffEffect`, to simplify
1101/// implementation). TODO: Something like `once` flag for `Buff` to remove the
1102/// dependence on `BuffEffect` enum?
1103///
1104/// In case of one-time buffs, buff effects will be applied on addition
1105/// and undone on removal of the buff (by the specs system).
1106/// Example could be decreasing max health, which, if repeated each tick,
1107/// would be probably an undesired effect).
1108#[derive(Clone, Debug, Serialize, Deserialize, Default)]
1109pub struct Buffs {
1110 /// Maps kinds of buff to currently applied buffs of that kind and
1111 /// the time that the first buff was added (time gets reset if entity no
1112 /// longer has buffs of that kind)
1113 pub kinds: EnumMap<BuffKind, Option<(Vec<BuffKey>, Time)>>,
1114 // All buffs currently present on an entity
1115 pub buffs: SlotMap<BuffKey, Buff>,
1116}
1117
1118impl Buffs {
1119 fn sort_kind(&mut self, kind: BuffKind) {
1120 if let Some(buff_order) = self.kinds[kind].as_mut() {
1121 if buff_order.0.is_empty() {
1122 self.kinds[kind] = None;
1123 } else {
1124 let buffs = &self.buffs;
1125 // Intentionally sorted in reverse so that the strongest buffs are earlier in
1126 // the vector
1127 buff_order
1128 .0
1129 .sort_by(|a, b| buffs[*b].partial_cmp(&buffs[*a]).unwrap_or(Ordering::Equal));
1130 }
1131 }
1132 }
1133
1134 pub fn remove_kind(&mut self, kind: BuffKind) {
1135 if let Some((buff_keys, _)) = self.kinds[kind].as_ref() {
1136 for key in buff_keys {
1137 self.buffs.remove(*key);
1138 }
1139 self.kinds[kind] = None;
1140 }
1141 }
1142
1143 pub fn insert(&mut self, buff: Buff, current_time: Time) -> BuffKey {
1144 let kind = buff.kind;
1145 // Try to find another overlaping non-queueable buff with same data, cat_ids and
1146 // source.
1147 let other_key = if kind.queues() {
1148 None
1149 } else {
1150 self.kinds[kind].as_ref().and_then(|(keys, _)| {
1151 keys.iter()
1152 .find(|key| {
1153 self.buffs.get(**key).is_some_and(|other_buff| {
1154 other_buff.data == buff.data
1155 && other_buff.cat_ids == buff.cat_ids
1156 && other_buff.source == buff.source
1157 && other_buff
1158 .end_time
1159 .is_none_or(|end_time| end_time.0 >= buff.start_time.0)
1160 })
1161 })
1162 .copied()
1163 })
1164 };
1165
1166 // If another buff with the same fields is found, update end_time and effects
1167 let key = if !kind.stacks()
1168 && let Some((other_buff, key)) =
1169 other_key.and_then(|key| Some((self.buffs.get_mut(key)?, key)))
1170 {
1171 other_buff.end_time = buff.end_time;
1172 other_buff.effects = buff.effects;
1173 key
1174 // Otherwise, insert a new buff
1175 } else {
1176 let key = self.buffs.insert(buff);
1177 self.kinds[kind]
1178 .get_or_insert_with(|| (Vec::new(), current_time))
1179 .0
1180 .push(key);
1181 key
1182 };
1183
1184 self.sort_kind(kind);
1185 if kind.queues() {
1186 self.delay_queueable_buffs(kind, current_time);
1187 }
1188 key
1189 }
1190
1191 pub fn contains(&self, kind: BuffKind) -> bool { self.kinds[kind].is_some() }
1192
1193 pub fn contains_any(&self, kinds: &[BuffKind]) -> bool {
1194 kinds.iter().any(|kind| self.contains(*kind))
1195 }
1196
1197 // Iterate through buffs of a given kind in effect order (most powerful first)
1198 pub fn iter_kind(&self, kind: BuffKind) -> impl Iterator<Item = (BuffKey, &Buff)> + '_ {
1199 self.kinds[kind]
1200 .as_ref()
1201 .map(|keys| keys.0.iter())
1202 .unwrap_or_else(|| [].iter())
1203 .map(move |&key| (key, &self.buffs[key]))
1204 }
1205
1206 // Iterates through all active buffs (the most powerful buff of each
1207 // non-stacking kind, and all of the stacking ones)
1208 pub fn iter_active(&self) -> impl Iterator<Item = impl Iterator<Item = &Buff>> + '_ {
1209 self.kinds
1210 .iter()
1211 .filter_map(|(kind, keys)| keys.as_ref().map(|keys| (kind, keys)))
1212 .map(move |(kind, keys)| {
1213 if kind.stacks() {
1214 // Iterate stackable buffs in reverse order to show the timer of the soonest one
1215 // to expire
1216 Either::Left(keys.0.iter().filter_map(|key| self.buffs.get(*key)).rev())
1217 } else {
1218 Either::Right(self.buffs.get(keys.0[0]).into_iter())
1219 }
1220 })
1221 }
1222
1223 // Gets most powerful buff of a given kind
1224 pub fn remove(&mut self, buff_key: BuffKey) {
1225 if let Some(buff) = self.buffs.remove(buff_key) {
1226 let kind = buff.kind;
1227 self.kinds[kind]
1228 .as_mut()
1229 .map(|keys| keys.0.retain(|key| *key != buff_key));
1230 self.sort_kind(kind);
1231 }
1232 }
1233
1234 fn delay_queueable_buffs(&mut self, kind: BuffKind, current_time: Time) {
1235 let mut next_start_time: Option<Time> = None;
1236 debug_assert!(kind.queues());
1237 if let Some(buffs) = self.kinds[kind].as_mut() {
1238 buffs.0.iter().for_each(|key| {
1239 if let Some(buff) = self.buffs.get_mut(*key) {
1240 // End time only being updated when there is some next_start_time will
1241 // technically cause buffs to "end early" if they have a weaker strength than a
1242 // buff with an infinite duration, but this is fine since those buffs wouldn't
1243 // matter anyways
1244 if let Some(next_start_time) = next_start_time {
1245 // Delays buff so that it has the same progress it has now at the time the
1246 // previous buff would end.
1247 //
1248 // Shift should be relative to current time, unless the buff is delayed and
1249 // hasn't started yet
1250 let reference_time = current_time.0.max(buff.start_time.0);
1251 // If buff has a delay, ensure that queueables shuffling queue does not
1252 // potentially allow skipping delay
1253 buff.start_time = Time(next_start_time.0.max(buff.start_time.0));
1254 buff.end_time = buff.end_time.map(|end| {
1255 Time(end.0 + next_start_time.0.max(reference_time) - reference_time)
1256 });
1257 }
1258 next_start_time = buff.end_time;
1259 }
1260 })
1261 }
1262 }
1263}
1264
1265impl Component for Buffs {
1266 type Storage = DerefFlaggedStorage<Self, VecStorage<Self>>;
1267}
1268
1269#[derive(Default, Copy, Clone)]
1270pub struct DestInfo<'a> {
1271 pub stats: Option<&'a Stats>,
1272 pub mass: Option<&'a Mass>,
1273}
1274
1275#[cfg(test)]
1276pub mod tests {
1277 use crate::comp::buff::*;
1278
1279 #[cfg(test)]
1280 fn create_test_queueable_buff(buff_data: BuffData, time: Time) -> Buff {
1281 // Change to another buff that queues if we ever add one and remove saturation,
1282 // otherwise maybe add a test buff kind?
1283 debug_assert!(BuffKind::Saturation.queues());
1284 Buff::new(
1285 BuffKind::Saturation,
1286 buff_data,
1287 Vec::new(),
1288 BuffSource::Unknown,
1289 time,
1290 DestInfo::default(),
1291 None,
1292 )
1293 }
1294
1295 #[test]
1296 /// Tests a number of buffs with various progresses that queue to ensure
1297 /// queue has correct total duration
1298 fn test_queueable_buffs_three() {
1299 let mut buff_comp: Buffs = Default::default();
1300 let buff_data = BuffData::new(1.0, Some(Secs(10.0)));
1301 let time_a = Time(0.0);
1302 buff_comp.insert(create_test_queueable_buff(buff_data, time_a), time_a);
1303 let time_b = Time(6.0);
1304 buff_comp.insert(create_test_queueable_buff(buff_data, time_b), time_b);
1305 let time_c = Time(11.0);
1306 buff_comp.insert(create_test_queueable_buff(buff_data, time_c), time_c);
1307 // Check that all buffs have an end_time less than or equal to 30, and that at
1308 // least one has an end_time greater than or equal to 30.
1309 //
1310 // This should be true because 3 buffs that each lasted for 10 seconds were
1311 // inserted at various times, so the total duration should be 30 seconds.
1312 assert!(
1313 buff_comp
1314 .buffs
1315 .values()
1316 .all(|b| b.end_time.unwrap().0 < 30.01)
1317 );
1318 assert!(
1319 buff_comp
1320 .buffs
1321 .values()
1322 .any(|b| b.end_time.unwrap().0 > 29.99)
1323 );
1324 }
1325
1326 #[test]
1327 /// Tests that if a buff had a delay but will start soon, and an immediate
1328 /// queueable buff is added, delayed buff has correct start time
1329 fn test_queueable_buff_delay_start() {
1330 let mut buff_comp: Buffs = Default::default();
1331 let queued_buff_data = BuffData::new(1.0, Some(Secs(10.0))).with_delay(Secs(10.0));
1332 let buff_data = BuffData::new(1.0, Some(Secs(10.0)));
1333 let time_a = Time(0.0);
1334 buff_comp.insert(create_test_queueable_buff(queued_buff_data, time_a), time_a);
1335 let time_b = Time(6.0);
1336 buff_comp.insert(create_test_queueable_buff(buff_data, time_b), time_b);
1337 // Check that all buffs have an end_time less than or equal to 26, and that at
1338 // least one has an end_time greater than or equal to 26.
1339 //
1340 // This should be true because the first buff added had a delay of 10 seconds
1341 // and a duration of 10 seconds, the second buff added at 6 seconds had no
1342 // delay, and a duration of 10 seconds. When it finishes at 16 seconds the first
1343 // buff is past the delay time so should finish at 26 seconds.
1344 assert!(
1345 buff_comp
1346 .buffs
1347 .values()
1348 .all(|b| b.end_time.unwrap().0 < 26.01)
1349 );
1350 assert!(
1351 buff_comp
1352 .buffs
1353 .values()
1354 .any(|b| b.end_time.unwrap().0 > 25.99)
1355 );
1356 }
1357
1358 #[test]
1359 /// Tests that if a buff had a long delay, a short immediate queueable buff
1360 /// does not move delayed buff start or end times
1361 fn test_queueable_buff_long_delay() {
1362 let mut buff_comp: Buffs = Default::default();
1363 let queued_buff_data = BuffData::new(1.0, Some(Secs(10.0))).with_delay(Secs(50.0));
1364 let buff_data = BuffData::new(1.0, Some(Secs(10.0)));
1365 let time_a = Time(0.0);
1366 buff_comp.insert(create_test_queueable_buff(queued_buff_data, time_a), time_a);
1367 let time_b = Time(10.0);
1368 buff_comp.insert(create_test_queueable_buff(buff_data, time_b), time_b);
1369 // Check that all buffs have either an end time less than or equal to 20 seconds
1370 // XOR a start time greater than or equal to 50 seconds, that all buffs have a
1371 // start time less than or equal to 50 seconds, that all buffs have an end time
1372 // less than or equal to 60 seconds, and that at least one buff has an end time
1373 // greater than or equal to 60 seconds
1374 //
1375 // This should be true because the first buff has a delay of 50 seconds, the
1376 // second buff added has no delay at 10 seconds and lasts 10 seconds, so should
1377 // end at 20 seconds and not affect the start time of the delayed buff, and
1378 // since the delayed buff was not affected the end time should be 10 seconds
1379 // after the start time: 60 seconds != used here to emulate xor
1380 assert!(
1381 buff_comp
1382 .buffs
1383 .values()
1384 .all(|b| (b.end_time.unwrap().0 < 20.01) != (b.start_time.0 > 49.99))
1385 );
1386 assert!(buff_comp.buffs.values().all(|b| b.start_time.0 < 50.01));
1387 assert!(
1388 buff_comp
1389 .buffs
1390 .values()
1391 .all(|b| b.end_time.unwrap().0 < 60.01)
1392 );
1393 assert!(
1394 buff_comp
1395 .buffs
1396 .values()
1397 .any(|b| b.end_time.unwrap().0 > 59.99)
1398 );
1399 }
1400}