VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
Damage.cpp
Go to the documentation of this file.
2
3#include <igameevents.h>
4
11#include <cstdint>
12#include <mathlib/vector.h>
13#include <shareddefs.h>
14#include <string>
15#include <string_view>
16#include <utility>
17
18namespace VoltMod
19{
20
21static_assert(DamageGeneric == DMG_GENERIC);
22static_assert(DamageCrush == DMG_CRUSH);
23static_assert(DamageBullet == DMG_BULLET);
24static_assert(DamageSlash == DMG_SLASH);
25static_assert(DamageBurn == DMG_BURN);
26static_assert(DamageFall == DMG_FALL);
27static_assert(DamageBlast == DMG_BLAST);
28static_assert(DamageClub == DMG_CLUB);
29static_assert(DamageShock == DMG_SHOCK);
30static_assert(DamageHeadshot == DMG_HEADSHOT);
31
32static void SetWeapon(IGameEvent& event, std::string_view weapon)
33{
34 event.SetString("weapon", std::string(weapon).c_str());
35}
36
37Damage::Damage(EntitySystem& entities, const Bindings& bindings, Interfaces& interfaces, GameEvents& events)
38 : _hook("Damage", [this] { return Install(); }),
39 Before(_hook.MakeLifecycle()),
40 _entities(entities),
41 _bindings(bindings),
42 _interfaces(interfaces),
43 _events(events)
44{}
45
46Result<Subscription> Damage::Install()
47{
48 const auto onTakeDamage = [this](CEntityInstance& victim, void* info, void*) { return OnTakeDamage(victim, info); };
49 return HookFunction("Damage", _bindings.TakeDamage, onTakeDamage);
50}
51
52HookResult<int64_t> Damage::OnTakeDamage(CEntityInstance& victim, void* rawInfo)
53{
54 auto* info = static_cast<EngineDamageInfo*>(rawInfo);
55 DamageHit hit{.Victim = Entity{_entities, &victim},
56 .Attacker = {static_cast<uint32_t>(info->Attacker.ToInt())},
57 .Inflictor = {static_cast<uint32_t>(info->Inflictor.ToInt())},
58 .Amount = info->Damage,
59 .Type = static_cast<uint32_t>(info->DamageType)};
60 Before.Raise(hit);
61 if (hit.Blocked)
62 {
64 }
65
66 if (hit.Amount != info->Damage)
67 {
68 // Keep the totalled damage in step with the edited amount, as CS2Fixes does.
69 if (info->Damage != 0.0f)
70 {
71 info->TotalledDamage *= hit.Amount / info->Damage;
72 }
73 info->Damage = hit.Amount;
74 }
75 info->DamageType = static_cast<int32_t>(hit.Type);
76 return {};
77}
78
80{
81 if (!_bindings.TakeDamage)
82 {
83 return std::unexpected(Error::Unsupported("the CBaseEntity::TakeDamageOld signature did not bind"));
84 }
85 if (!_bindings.BuildDamageInfo)
86 {
87 return std::unexpected(Error::Unsupported("the CTakeDamageInfo constructor signature did not bind"));
88 }
89 return {};
90}
91
92void Damage::Apply(const Entity& victim, const DamageInfo& info)
93{
94 if (!victim || !Available())
95 {
96 return;
97 }
98
99 CEntityInstance* attacker = _entities.Get(info.Attacker).Raw();
100 CEntityInstance* inflictor = _entities.Get(info.Inflictor).Raw();
101 // The engine drops a hit with no inflictor.
102 if (!inflictor)
103 {
104 inflictor = attacker;
105 }
106
107 // The engine warns about a hit with no position or push, and pushes nothing.
108 const Vector position = victim.Origin();
109 Vector push = position - Entity{_entities, inflictor}.Origin();
110 push.NormalizeInPlace();
111 push *= info.Amount;
112
113 EngineDamageInfo damage{};
114 _bindings.BuildDamageInfo(&damage, inflictor, attacker, nullptr, &push, &position, info.Amount,
115 static_cast<int>(info.Type), 0, nullptr);
116
117 EngineDamageResult result{};
118 result.OriginatingInfo = &damage;
119 result.HealthLost = static_cast<int32_t>(info.Amount);
120 result.DamageDealt = info.Amount;
121 result.PreModifiedDamage = info.Amount;
122 result.TotalledHealthLost = static_cast<int32_t>(info.Amount);
123 result.TotalledDamageDealt = info.Amount;
124
125 if (!info.Weapon.empty())
126 {
127 HookDeathEvents();
128 }
129 // A death handler may deal its own hit inside this one.
130 const DamageInfo* outer = std::exchange(_hit, &info);
131 _bindings.TakeDamage(victim.Raw(), &damage, &result);
132 _hit = outer;
133}
134
135void Damage::HookDeathEvents()
136{
137 if (_deathEvents || !_interfaces.GameEventManager)
138 {
139 return;
140 }
141 const auto onFireEvent = [this](IGameEventManager2& manager, IGameEvent* event, bool dontBroadcast) {
142 return OnFireEvent(manager, event, dontBroadcast);
143 };
144 _deathEvents = HookInterface(&IGameEventManager2::FireEvent, _interfaces.GameEventManager, onFireEvent);
145}
146
147HookResult<bool> Damage::OnFireEvent(IGameEventManager2& manager, IGameEvent* event, bool dontBroadcast)
148{
149 // Every server event passes here, mostly outside Apply.
150 if (!_hit || _hit->Weapon.empty())
151 {
152 return {};
153 }
154 if (!event || event->GetName() != PlayerDeath::EventName)
155 {
156 return {};
157 }
158 if (_hit->VictimWeapon.empty() || dontBroadcast)
159 {
160 SetWeapon(*event, _hit->Weapon);
161 return {};
162 }
163 SendDeath(*event, *_hit);
164 // Only the server's listeners: the clients have theirs.
165 return HookResult<bool>::Block(CallOriginal(&IGameEventManager2::FireEvent, &manager, event, true));
166}
167
168void Damage::SendDeath(IGameEvent& death, const DamageInfo& info)
169{
170 const int victim = death.GetPlayerSlot("userid").Get();
171 for (int slot = 0; slot < MaxPlayers; ++slot)
172 {
173 IGameEventListener2* listener = _events.GetClientLegacyListener(slot);
174 if (!listener)
175 {
176 continue;
177 }
178 SetWeapon(death, slot == victim ? info.VictimWeapon : info.Weapon);
179 listener->FireGameEvent(&death);
180 }
181 // The server's listeners read the icon path.
182 SetWeapon(death, info.Weapon);
183}
184
185} // namespace VoltMod
Event< DamageHit & > Before
Definition Damage.hpp:94
Status Available() const
Definition Damage.cpp:79
void Apply(const Entity &victim, const DamageInfo &info)
Definition Damage.cpp:92
Damage(EntitySystem &entities, const Bindings &bindings, Interfaces &interfaces, GameEvents &events)
Definition Damage.cpp:37
runtime.Entities: finds and creates entities. Everything it returns is valid for this frame only; see...
A live entity, valid for this frame only.
Definition Entity.hpp:40
Vector Origin() const
Definition Entity.cpp:106
CEntityInstance * Raw() const noexcept
Definition Entity.hpp:58
Creates, fires and listens to game events.
A hook before-handler's verdict.
static HookResult Block(Ret value)
constexpr uint32_t DamageCrush
Definition Damage.hpp:23
constexpr uint32_t DamageBullet
Definition Damage.hpp:24
constexpr uint32_t DamageFall
Definition Damage.hpp:27
constexpr uint32_t DamageHeadshot
Definition Damage.hpp:31
constexpr uint32_t DamageBurn
Definition Damage.hpp:26
constexpr uint32_t DamageShock
Definition Damage.hpp:30
constexpr uint32_t DamageSlash
Definition Damage.hpp:25
constexpr uint32_t DamageClub
Definition Damage.hpp:29
constexpr uint32_t DamageGeneric
Definition Damage.hpp:22
constexpr uint32_t DamageBlast
Definition Damage.hpp:28
Ret CallOriginal(Ret(Iface::*method)(Args...), Iface *instance, Passed &&... args)
Definition Hook.hpp:250
Result< Subscription > HookFunction(std::string_view name, const Fn< Ret(Object *, Args...)> &function, Before &&before, After &&after=nullptr)
Hook a signature-bound function at its entry.
Definition Hook.hpp:232
std::expected< void, Error > Status
Definition Result.hpp:67
std::expected< T, Error > Result
Definition Result.hpp:64
::Vector Vector
Definition Math.hpp:12
static void SetWeapon(IGameEvent &event, std::string_view weapon)
Definition Damage.cpp:32
Subscription HookInterface(Ret(Iface::*method)(Args...), Iface *instance, Before &&before, After &&after=nullptr)
Hook one virtual method of an engine interface for a subscription's lifetime.
Definition Hook.hpp:142
constexpr int MaxPlayers
Definition Slot.hpp:7
EntityRef Inflictor
what did it, such as a grenade or a turret; empty means the attacker
Definition Damage.hpp:38
uint32_t Type
Damage type bits (DamageTypes_t); combine with |. bits
Definition Damage.hpp:40
EntityRef Attacker
credited in the kill feed and player_death
Definition Damage.hpp:37
std::string_view Weapon
Definition Damage.hpp:43
EngineDamageInfo * OriginatingInfo
static Error Unsupported(std::string detail)
Definition Result.hpp:57
Centralized holder for all SDK interface pointers.
IGameEventManager2 * GameEventManager
static constexpr std::string_view EventName