source_sdk_2013 0.1.0-alpha.4

Higher-level bindings for the Source SDK.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Owned damage descriptions and TF2 critical-hit controls.
//!
//! Damage hooks must copy `CTakeDamageInfo` before changing it: the engine
//! passes a C++ const reference, which can also point into another plugin's
//! immutable storage. [`DamageInfo`] preserves the complete native record
//! without forming a Rust reference to engine memory.

use crate::Server;
use crate::entities::{Entity, EntityHandle};
use std::fmt;
use std::mem::{MaybeUninit, offset_of};
use std::ops::{BitAnd, BitOr, BitOrAssign, Not};
use std::ptr::NonNull;

/// The classification in `CTakeDamageInfo::ECritType`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum CriticalHit {
	#[default]
	None = sys::CTakeDamageInfo_ECritType_CRIT_NONE as i32,
	Mini = sys::CTakeDamageInfo_ECritType_CRIT_MINI as i32,
	Full = sys::CTakeDamageInfo_ECritType_CRIT_FULL as i32,
}

/// Independently permit full critical hits and mini critical hits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CriticalPolicy {
	pub full: bool,
	pub mini: bool,
}

impl CriticalPolicy {
	pub const ALLOW_ALL: Self = Self {
		full: true,
		mini: true,
	};

	pub const DISABLE_ALL: Self = Self {
		full: false,
		mini: false,
	};
}

impl Default for CriticalPolicy {
	fn default() -> Self {
		Self::ALLOW_ALL
	}
}

/// A native damage record owned by Rust. It contains serial-numbered entity
/// handles, not borrowed entity pointers, so a copy can be retained for logs.
/// Setters panic on non-finite floats or handles whose entity index is outside
/// the engine's table. Damage amount must also fit the engine's signed health
/// arithmetic. Damage callbacks contain these panics before returning to C++.
///
/// The SDK's constructor leaves its unused statistics field and padding
/// uninitialized. Keeping a `MaybeUninit` record and copying bytes preserves
/// them without ever claiming the entire native record is initialized.
pub struct DamageInfo {
	raw: MaybeUninit<sys::CTakeDamageInfo>,
}

/// Source's damage bitmask. Unknown and game-specific bits are preserved.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DamageType(pub u32);

impl DamageType {
	pub const ALWAYS_GIB: Self = Self(1 << 13);
	pub const BLAST: Self = Self(1 << 6);
	pub const BUCKSHOT: Self = Self(1 << 29);
	pub const BULLET: Self = Self(1 << 1);
	pub const BURN: Self = Self(1 << 3);
	pub const CLUB: Self = Self(1 << 7);

	/// TF2's `DMG_CRITICAL` aliases `DMG_ACID`. Both full and mini critical
	/// hits carry it after TF2 has computed their damage bonus.
	pub const CRITICAL: Self = Self(1 << 20);

	pub const CRUSH: Self = Self(1 << 0);
	pub const DIRECT: Self = Self(1 << 28);
	pub const DROWN: Self = Self(1 << 14);
	pub const FALL: Self = Self(1 << 5);
	pub const GENERIC: Self = Self(0);
	pub const NEVER_GIB: Self = Self(1 << 12);
	pub const PREVENT_PHYSICS_FORCE: Self = Self(1 << 11);
	pub const SHOCK: Self = Self(1 << 8);
	pub const SLASH: Self = Self(1 << 2);

	/// TF2's `DMG_USEDISTANCEMOD`.
	pub const USE_DISTANCE_MOD: Self = Self(1 << 21);

	/// TF2's `DMG_USE_HITLOCATIONS`.
	pub const USE_HIT_LOCATIONS: Self = Self(1 << 25);

	pub const fn contains(self, other: Self) -> bool {
		self.0 & other.0 == other.0
	}
}

impl BitAnd for DamageType {
	type Output = Self;

	fn bitand(self, rhs: Self) -> Self {
		Self(self.0 & rhs.0)
	}
}

impl BitOr for DamageType {
	type Output = Self;

	fn bitor(self, rhs: Self) -> Self {
		Self(self.0 | rhs.0)
	}
}

impl BitOrAssign for DamageType {
	fn bitor_assign(&mut self, rhs: Self) {
		self.0 |= rhs.0;
	}
}

impl Not for DamageType {
	type Output = Self;

	fn not(self) -> Self {
		Self(!self.0)
	}
}

macro_rules! scalar {
	($get:ident, $set:ident, $field:ident, $ty:ty) => {
		scalar!($get, $set, $field, $ty, |_: $ty| true);
	};
	($get:ident, $set:ident, $field:ident, $ty:ty, $valid:expr) => {
		pub fn $get(&self) -> $ty {
			// SAFETY: Native constructors initialize this field, and our
			// constructor initializes the complete record. This is owned memory.
			unsafe { (&raw const (*self.raw.as_ptr()).$field).read() }
		}
		pub fn $set(&mut self, value: $ty) {
			assert!(
				($valid)(value),
				"invalid damage field: {}",
				stringify!($field)
			);
			// SAFETY: This field lies in our allocated native record.
			unsafe { (&raw mut (*self.raw.as_mut_ptr()).$field).write(value) };
		}
	};
}

/// A scoped victim plus an owned copy of its damage arguments.
#[derive(Debug)]
pub struct DamageEvent<'s> {
	pub victim: Entity<'s>,
	pub info: DamageInfo,
}

impl<'s> DamageEvent<'s> {
	/// Adapts native damage-hook arguments to scoped Rust values.
	///
	/// # Safety
	/// `victim` must be a live entity belonging to `server` and remain live
	/// for `'s`. `info` must satisfy [`DamageInfo::copy_from_raw`]. The call
	/// must obey the main-thread and reentrancy contract of [`Server::new`].
	pub unsafe fn from_raw(
		_server: Server<'s>,
		victim: NonNull<sys::CBaseEntity>,
		info: NonNull<sys::CTakeDamageInfo>,
	) -> Self {
		Self {
			// SAFETY: The caller supplies the entity's callback lifetime.
			victim: unsafe { Entity::from_raw(victim) },
			// SAFETY: The caller vouches for the native damage arguments.
			info: unsafe { DamageInfo::copy_from_raw(info) },
		}
	}
}

impl DamageInfo {
	/// Conservative per-hit limit for values edited through this API. This is
	/// an API limit, not a TF2 limit: one million still leaves more than 700
	/// times headroom below `i32::MAX` after TF2's ordinary 3x critical bonus.
	/// It keeps edited values away from float-to-int conversion boundaries and
	/// ordinary health subtraction overflow. Later game/attribute multipliers
	/// are outside this record's control and must themselves remain valid.
	pub const MAX_DAMAGE: f32 = 1_000_000.0;

	/// Constructs a damage record with no attacker, weapon, force or position.
	/// Set the relevant handles before submitting it to the game.
	pub fn new(amount: f32, damage_type: DamageType) -> Self {
		// All-zero bytes are valid for this POD record. Native handles need
		// their explicit invalid sentinel, and base damage uses FLT_MAX.
		let mut result = Self {
			raw: MaybeUninit::zeroed(),
		};
		result.set_amount(amount);
		result.set_max_damage(amount);
		result.set_base_damage(f32::MAX);
		result.set_damage_type(damage_type);
		result.set_attacker(EntityHandle::INVALID);
		result.set_inflictor(EntityHandle::INVALID);
		result.set_weapon(EntityHandle::INVALID);
		result.set_bonus_provider(EntityHandle::INVALID);
		result.set_ammo_type(-1);
		result
	}

	/// Copies a live native record, including bytes not exposed by this API.
	///
	/// # Safety
	/// `raw` must point to a live `CTakeDamageInfo` matching the target SDK ABI,
	/// with its constructor-initialized fields valid, for the duration of the
	/// copy. No other thread may write it concurrently.
	pub unsafe fn copy_from_raw(raw: NonNull<sys::CTakeDamageInfo>) -> Self {
		let mut result = Self {
			raw: MaybeUninit::uninit(),
		};
		// SAFETY: Both allocations hold a complete native record and cannot
		// overlap. A byte copy preserves uninitialized bytes as such.
		unsafe { std::ptr::copy_nonoverlapping(raw.as_ptr(), result.raw.as_mut_ptr(), 1) };
		result
	}

	fn valid_damage(value: f32) -> bool {
		value.is_finite() && (0.0..=Self::MAX_DAMAGE).contains(&value)
	}

	/// Native read-only pointer, valid until this value is moved or dropped.
	pub fn as_ptr(&self) -> *const sys::CTakeDamageInfo {
		self.raw.as_ptr()
	}

	scalar!(amount, set_amount, m_flDamage, f32, Self::valid_damage);
	scalar!(
		max_damage,
		set_max_damage,
		m_flMaxDamage,
		f32,
		Self::valid_damage
	);
	scalar!(
		base_damage,
		set_base_damage,
		m_flBaseDamage,
		f32,
		|value: f32| value == f32::MAX || Self::valid_damage(value)
	);
	scalar!(
		damage_bonus,
		set_damage_bonus,
		m_flDamageBonus,
		f32,
		Self::valid_damage
	);
	scalar!(custom_damage, set_custom_damage, m_iDamageCustom, i32);
	scalar!(ammo_type, set_ammo_type, m_iAmmoType, i32);
	scalar!(
		force_friendly_fire,
		set_force_friendly_fire,
		m_bForceFriendlyFire,
		bool
	);

	/// Removes a disallowed hit's recorded critical bonus after TF2's rules
	/// have computed it. Returns whether the record changed. Full and mini
	/// critical hits are independently controlled.
	///
	/// Call this at `OnTakeDamage_Alive`, not on incoming, unscaled damage.
	/// TF2's recorded bonus includes its critical distance compensation. This
	/// removes that bonus; it does not rerun earlier attribute, distance,
	/// assist-statistics or audiovisual processing. Later resistance rules
	/// can still change the resulting health loss.
	pub fn apply_critical_policy(&mut self, policy: CriticalPolicy) -> bool {
		let denied = match self.critical_hit() {
			Some(CriticalHit::Full) => !policy.full,
			Some(CriticalHit::Mini) => !policy.mini,
			_ => false,
		};
		if denied {
			self.set_amount((self.amount() - self.damage_bonus()).max(0.0));
			self.set_damage_bonus(0.0);
			self.set_bonus_provider(EntityHandle::INVALID);
			self.set_incoming_critical(CriticalHit::None);
		}
		denied
	}

	pub fn attacker(&self) -> EntityHandle {
		self.handle(offset_of!(sys::CTakeDamageInfo, m_hAttacker))
	}

	pub fn critical_hit(&self) -> Option<CriticalHit> {
		// SAFETY: Constructor-initialized scalar in owned memory.
		match unsafe { (&raw const (*self.as_ptr()).m_eCritType).read() } {
			0 => Some(CriticalHit::None),
			1 => Some(CriticalHit::Mini),
			2 => Some(CriticalHit::Full),
			_ => None,
		}
	}

	pub fn damage_type(&self) -> DamageType {
		// SAFETY: Constructor-initialized scalar in owned memory.
		DamageType(unsafe { (&raw const (*self.as_ptr()).m_bitsDamageType).read() } as u32)
	}

	fn handle(&self, offset: usize) -> EntityHandle {
		// SAFETY: Offsets below identify constructor-initialized CBaseHandle
		// fields, whose sole member is a u32 on both supported ABIs.
		EntityHandle::from_raw(unsafe {
			self.as_ptr().cast::<u8>().add(offset).cast::<u32>().read()
		})
	}

	pub fn inflictor(&self) -> EntityHandle {
		self.handle(offset_of!(sys::CTakeDamageInfo, m_hInflictor))
	}

	pub fn scale_amount(&mut self, factor: f32) {
		self.set_amount(self.amount() * factor);
	}

	pub fn set_attacker(&mut self, handle: EntityHandle) {
		self.set_handle(offset_of!(sys::CTakeDamageInfo, m_hAttacker), handle);
	}

	fn set_bonus_provider(&mut self, handle: EntityHandle) {
		self.set_handle(
			offset_of!(sys::CTakeDamageInfo, m_hDamageBonusProvider),
			handle,
		);
	}

	pub fn set_damage_type(&mut self, value: DamageType) {
		// SAFETY: Scalar field in our allocated record; retain all 32 bits.
		unsafe { (&raw mut (*self.raw.as_mut_ptr()).m_bitsDamageType).write(value.0 as i32) };
	}

	fn set_handle(&mut self, offset: usize, handle: EntityHandle) {
		assert!(
			handle
				.index()
				.is_none_or(|index| index < EntityHandle::SLOTS),
			"damage handle index exceeds the entity table"
		);
		// SAFETY: As above, in uniquely owned storage.
		unsafe {
			self.raw
				.as_mut_ptr()
				.cast::<u8>()
				.add(offset)
				.cast::<u32>()
				.write(handle.to_raw())
		};
	}

	/// Selects an incoming critical classification before TF2 calculates the
	/// bonus. This does not multiply damage. Game conditions and attributes
	/// can still promote or suppress the hit later; use a late damage hook to
	/// enforce a policy on the computed hit.
	pub fn set_incoming_critical(&mut self, critical: CriticalHit) {
		self.write_critical(critical);
		let ordinary = self.damage_type() & !DamageType::CRITICAL;
		self.set_damage_type(if critical == CriticalHit::Full {
			ordinary | DamageType::CRITICAL
		} else {
			ordinary
		});
	}

	pub fn set_inflictor(&mut self, handle: EntityHandle) {
		self.set_handle(offset_of!(sys::CTakeDamageInfo, m_hInflictor), handle);
	}

	pub fn set_weapon(&mut self, handle: EntityHandle) {
		self.set_handle(offset_of!(sys::CTakeDamageInfo, m_hWeapon), handle);
	}

	pub fn weapon(&self) -> EntityHandle {
		self.handle(offset_of!(sys::CTakeDamageInfo, m_hWeapon))
	}

	fn write_critical(&mut self, critical: CriticalHit) {
		// SAFETY: Scalar field in our owned record, with a valid native value.
		unsafe { (&raw mut (*self.raw.as_mut_ptr()).m_eCritType).write(critical as _) };
	}
}

impl Clone for DamageInfo {
	fn clone(&self) -> Self {
		// SAFETY: Our record was constructed here or copied under this contract.
		unsafe { Self::copy_from_raw(NonNull::new(self.as_ptr().cast_mut()).unwrap()) }
	}
}

impl fmt::Debug for DamageInfo {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("DamageInfo")
			.field("amount", &self.amount())
			.field("damage_type", &self.damage_type())
			.field("critical_hit", &self.critical_hit())
			.field("attacker", &self.attacker())
			.field("weapon", &self.weapon())
			.finish_non_exhaustive()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn all_editable_damage_scalars_are_bounded_except_the_base_damage_sentinel() {
		let setters: [fn(&mut DamageInfo, f32); 4] = [
			DamageInfo::set_amount,
			DamageInfo::set_max_damage,
			DamageInfo::set_base_damage,
			DamageInfo::set_damage_bonus,
		];
		for setter in setters {
			let mut damage = DamageInfo::new(10.0, DamageType::GENERIC);
			for value in [
				f32::NAN,
				f32::INFINITY,
				f32::NEG_INFINITY,
				-1.0,
				DamageInfo::MAX_DAMAGE + 1.0,
				1.0e30,
			] {
				assert!(
					std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| setter(
						&mut damage,
						value
					)))
					.is_err()
				);
			}
			setter(&mut damage, 0.0);
			setter(&mut damage, DamageInfo::MAX_DAMAGE);
		}
		let mut damage = DamageInfo::new(1.0, DamageType::GENERIC);
		damage.set_base_damage(f32::MAX);
		assert_eq!(damage.base_damage(), f32::MAX);
		for setter in [
			DamageInfo::set_amount,
			DamageInfo::set_max_damage,
			DamageInfo::set_damage_bonus,
		] {
			assert!(
				std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| setter(
					&mut damage,
					f32::MAX
				)))
				.is_err()
			);
		}
		assert!(
			std::panic::catch_unwind(std::panic::AssertUnwindSafe(
				|| damage.scale_amount(f32::MAX)
			))
			.is_err()
		);
		assert_eq!(damage.amount(), 1.0);
	}

	#[test]
	fn copies_change_owned_data_and_preserve_unknown_bits_and_handles() {
		let original = DamageInfo::new(24.0, DamageType::BULLET | DamageType(1 << 31));
		let mut copy = original.clone();
		copy.scale_amount(2.0);
		copy.set_weapon(EntityHandle::from_raw(17 | 3 << 16));
		assert_eq!(copy.amount(), 48.0);
		assert_eq!(original.amount(), 24.0);
		assert_eq!(copy.damage_type().0, (1 << 31) | 2);
		assert_eq!(original.weapon(), EntityHandle::INVALID);
		assert_eq!(copy.weapon().serial_number(), 3);
	}

	#[test]
	fn critical_policy_clamps_overlarge_recorded_bonus() {
		let mut damage = DamageInfo::new(10.0, DamageType::CRITICAL);
		damage.write_critical(CriticalHit::Full);
		damage.set_damage_bonus(50.0);
		assert!(damage.apply_critical_policy(CriticalPolicy::DISABLE_ALL));
		assert_eq!(damage.amount(), 0.0);
	}

	#[test]
	fn incoming_crit_changes_are_exclusive_and_do_not_scale_damage() {
		let mut damage = DamageInfo::new(10.0, DamageType::BLAST);
		for critical in [CriticalHit::Full, CriticalHit::Mini, CriticalHit::None] {
			damage.set_incoming_critical(critical);
			assert_eq!(damage.critical_hit(), Some(critical));
			assert_eq!(
				damage.damage_type().contains(DamageType::CRITICAL),
				critical == CriticalHit::Full
			);
			assert!(damage.damage_type().contains(DamageType::BLAST));
			assert_eq!(damage.amount(), 10.0);
		}
	}

	#[test]
	fn independent_policies_remove_bonus_only_once() {
		for (critical, policy, denied) in [
			(
				CriticalHit::Full,
				CriticalPolicy {
					full: false,
					mini: true,
				},
				true,
			),
			(
				CriticalHit::Mini,
				CriticalPolicy {
					full: false,
					mini: true,
				},
				false,
			),
			(
				CriticalHit::Full,
				CriticalPolicy {
					full: true,
					mini: false,
				},
				false,
			),
			(
				CriticalHit::Mini,
				CriticalPolicy {
					full: true,
					mini: false,
				},
				true,
			),
		] {
			let mut damage = DamageInfo::new(135.0, DamageType::BULLET | DamageType::CRITICAL);
			damage.write_critical(critical);
			damage.set_damage_bonus(35.0);
			assert_eq!(damage.apply_critical_policy(policy), denied);
			assert_eq!(damage.amount(), if denied { 100.0 } else { 135.0 });
			assert!(!damage.apply_critical_policy(policy));
			if denied {
				assert_eq!(damage.critical_hit(), Some(CriticalHit::None));
				assert!(!damage.damage_type().contains(DamageType::CRITICAL));
			}
		}
	}

	#[test]
	fn invalid_edits_leave_the_prior_record_intact() {
		let mut damage = DamageInfo::new(10.0, DamageType::GENERIC);
		for value in [f32::NAN, f32::INFINITY, -1.0, i32::MAX as f32] {
			assert!(
				std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| damage.set_amount(value)))
					.is_err()
			);
			assert_eq!(damage.amount(), 10.0);
		}
		assert!(
			std::panic::catch_unwind(std::panic::AssertUnwindSafe(
				|| damage.set_attacker(EntityHandle::from_raw(EntityHandle::SLOTS as u32))
			))
			.is_err()
		);
		assert_eq!(damage.attacker(), EntityHandle::INVALID);
	}
}