source_sdk_2013 0.1.0-alpha.8

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
//! Typed schema attribute definitions and the values they accept.

use crate::tf2::attributes::AttributeError;
use sdk_raw::tf2::attributes::INVALID_ATTRIB_DEF_INDEX;
use std::ffi::CStr;
use std::fmt::{self, Debug, Display, Formatter};
use std::marker::PhantomData;

/// An additive amount, such as health points: any finite float.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Amount(f32);

/// A [catalog](super::catalog) definition of any value type, as
/// [`catalog::ALL`](super::catalog::ALL) lists them, for attributes chosen
/// while the plugin runs, such as by name from a configuration file. Its
/// values are plain floats, which [`Self::stored`] checks as the definition's
/// value type and bounds would.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnyAttributeDef {
	/// A definition of an additive amount.
	Amount(AttributeDef<Amount>),

	/// A definition of an on or off switch.
	Flag(AttributeDef<Flag>),

	/// A definition of a multiplier.
	Multiplier(AttributeDef<Multiplier>),

	/// A definition of a duration.
	Seconds(AttributeDef<Seconds>),
}

impl AnyAttributeDef {
	/// The attribute class, as for [`AttributeDef::class`].
	pub const fn class(&self) -> &'static CStr {
		self.raw().class
	}

	/// How the schema describes the value, as for [`AttributeDef::format`].
	pub const fn format(&self) -> DescriptionFormat {
		self.raw().format
	}

	/// The definition index, as for [`AttributeDef::index`].
	pub const fn index(&self) -> AttributeIndex {
		self.raw().index
	}

	/// The largest stored value this crate writes.
	pub const fn max(&self) -> f32 {
		self.raw().max
	}

	/// The smallest stored value this crate writes.
	pub const fn min(&self) -> f32 {
		self.raw().min
	}

	/// The schema name, as for [`AttributeDef::name`].
	pub const fn name(&self) -> &'static CStr {
		self.raw().name
	}

	/// The definition without its value type.
	pub(super) const fn raw(&self) -> RawDef {
		match self {
			Self::Amount(def) => def.raw(),
			Self::Flag(def) => def.raw(),
			Self::Multiplier(def) => def.raw(),
			Self::Seconds(def) => def.raw(),
		}
	}

	/// `value` as the game stores it, once checked as the definition's value
	/// type: [`AttributeError::InvalidValue`] for a value the type has no
	/// equal of, such as a [`Flag`] other than 0 or 1 or a negative
	/// [`Multiplier`], and [`AttributeError::OutOfDomain`] outside the
	/// definition's bounds.
	pub fn stored(&self, value: f32) -> Result<f32, AttributeError> {
		fn typed<V: AttributeValue>(
			def: &AttributeDef<V>,
			value: f32,
		) -> Result<f32, AttributeError> {
			def.stored(V::from_stored(value).ok_or(AttributeError::InvalidValue)?)
		}

		match self {
			Self::Amount(def) => typed(def, value),
			Self::Flag(def) => typed(def, value),
			Self::Multiplier(def) => typed(def, value),
			Self::Seconds(def) => typed(def, value),
		}
	}

	/// What the definition's values are: `amount`, `flag`, `multiplier` or
	/// `seconds`.
	pub const fn value_kind(&self) -> &'static str {
		match self {
			Self::Amount(_) => "amount",
			Self::Flag(_) => "flag",
			Self::Multiplier(_) => "multiplier",
			Self::Seconds(_) => "seconds",
		}
	}
}

impl Amount {
	/// No change.
	pub const ZERO: Self = Self(0.0);

	/// A finite amount, or `None` for NaN and infinities. Negative zero
	/// becomes zero.
	pub const fn new(amount: f32) -> Option<Self> {
		if amount.is_finite() {
			Some(Self(amount + 0.0))
		} else {
			None
		}
	}

	/// The amount.
	pub const fn get(self) -> f32 {
		self.0
	}
}

impl AttributeValue for Amount {
	fn from_stored(stored: f32) -> Option<Self> {
		Self::new(stored)
	}

	fn to_stored(self) -> f32 {
		self.0
	}
}

impl sealed::Sealed for Amount {}

/// A schema attribute vetted against the item schema TF2 ships: its name,
/// definition index, attribute class, description format, and the values
/// this crate writes to it.
///
/// Every definition in the [catalog](super::catalog) has TF2's legacy default
/// type, is stored as a float, and is read by gameplay hooks on the server.
/// The bounds are conservative policy rather than game limits: they keep
/// values away from the integer conversions and loops in game code that
/// extreme values overflow or stall.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AttributeDef<V: AttributeValue> {
	raw: RawDef,
	_value: PhantomData<fn() -> V>,
}

impl<V: AttributeValue> AttributeDef<V> {
	/// A definition the catalog vets. `min` and `max` bound the stored value,
	/// and must differ, so that [`ItemAttributes::set`] can confirm the
	/// running schema's index with another value.
	///
	/// [`ItemAttributes::set`]: super::ItemAttributes::set
	pub(super) const fn new(
		index: u16,
		name: &'static CStr,
		class: &'static CStr,
		format: DescriptionFormat,
		min: f32,
		max: f32,
	) -> Self {
		let Some(index) = AttributeIndex::new(index) else {
			panic!("catalog attributes need a valid definition index");
		};

		assert!(min.is_finite() && max.is_finite() && min < max);

		Self {
			raw: RawDef {
				name,
				index,
				class,
				format,
				min,
				max,
			},
			_value: PhantomData,
		}
	}

	/// The attribute class, the name of the gameplay hook that reads the
	/// attribute, such as `mult_dmg`.
	#[doc(alias("attribute_class"))]
	pub const fn class(&self) -> &'static CStr {
		self.raw.class
	}

	/// Whether the value lies within this definition's bounds.
	pub fn contains(&self, value: V) -> bool {
		self.raw.contains(value.to_stored())
	}

	/// How the schema describes the value, which decides how the game folds
	/// it with the same attribute class from other providers.
	#[doc(alias("description_format"))]
	pub const fn format(&self) -> DescriptionFormat {
		self.raw.format
	}

	/// The definition index the shipped schema gives the attribute. Writes
	/// check that the running schema maps [`Self::name`] to it.
	#[doc(alias("defindex"))]
	pub const fn index(&self) -> AttributeIndex {
		self.raw.index
	}

	/// The largest stored value this crate writes.
	pub const fn max(&self) -> f32 {
		self.raw.max
	}

	/// The smallest stored value this crate writes.
	pub const fn min(&self) -> f32 {
		self.raw.min
	}

	/// The schema name the game looks the attribute up by, such as
	/// `damage bonus`.
	pub const fn name(&self) -> &'static CStr {
		self.raw.name
	}

	/// The definition without its value type.
	pub(super) const fn raw(&self) -> RawDef {
		self.raw
	}

	/// The value as the game stores it, or [`AttributeError::OutOfDomain`]
	/// outside this definition's bounds.
	pub fn stored(&self, value: V) -> Result<f32, AttributeError> {
		let stored = value.to_stored();

		if self.raw.contains(stored) {
			Ok(stored)
		} else {
			Err(AttributeError::OutOfDomain)
		}
	}
}

/// An attribute definition index in TF2's item schema
/// (`attrib_definition_index_t`), never the invalid sentinel 65535.
#[doc(alias("attrib_definition_index_t"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AttributeIndex(u16);

impl AttributeIndex {
	/// Excludes [`INVALID_ATTRIB_DEF_INDEX`], 65535.
	pub const fn new(index: u16) -> Option<Self> {
		if index == INVALID_ATTRIB_DEF_INDEX {
			None
		} else {
			Some(Self(index))
		}
	}

	/// The raw definition index.
	pub const fn get(self) -> u16 {
		self.0
	}
}

impl Display for AttributeIndex {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		Display::fmt(&self.0, f)
	}
}

/// A value one of TF2's float-stored default-type attributes holds.
///
/// Sealed: the [catalog](super::catalog) pairs each definition with the value
/// type its gameplay hooks expect, and values reach the game only as the
/// float the schema stores.
pub trait AttributeValue: sealed::Sealed + Copy + Debug {
	/// Converts a stored float back, or returns `None` if it is not a valid
	/// value of this type.
	fn from_stored(stored: f32) -> Option<Self>;

	/// The value as the game stores it.
	fn to_stored(self) -> f32;
}

/// How the game folds values of one attribute class from several providers,
/// such as a player and each of their weapons.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Combine {
	/// Values are added together.
	Add,

	/// Values are combined with a bitwise or.
	BitOr,

	/// Values are multiplied together.
	Multiply,
}

/// How the item schema describes an attribute's value (`description_format`),
/// which also decides how the game combines it (`ApplyAttribute` in
/// `attribute_manager.cpp`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DescriptionFormat {
	/// An amount added to the hooked value.
	#[doc(alias("value_is_additive"))]
	Additive,

	/// A fraction added to the hooked value, described as a percentage.
	#[doc(alias("value_is_additive_percentage"))]
	AdditivePercentage,

	/// A multiplier, described as a percentage of decrease.
	#[doc(alias("value_is_inverted_percentage"))]
	InvertedPercentage,

	/// Bits combined with a bitwise or.
	#[doc(alias("value_is_or"))]
	Or,

	/// A multiplier, described as a percentage of increase.
	#[doc(alias("value_is_percentage"))]
	Percentage,
}

impl DescriptionFormat {
	/// How the game combines values of this format.
	pub const fn combine(self) -> Combine {
		match self {
			Self::Additive | Self::AdditivePercentage => Combine::Add,
			Self::InvertedPercentage | Self::Percentage => Combine::Multiply,
			Self::Or => Combine::BitOr,
		}
	}

	/// The format's keyword in `items_game.txt`, such as `value_is_percentage`.
	pub const fn keyword(self) -> &'static str {
		match self {
			Self::Additive => "value_is_additive",
			Self::AdditivePercentage => "value_is_additive_percentage",
			Self::InvertedPercentage => "value_is_inverted_percentage",
			Self::Or => "value_is_or",
			Self::Percentage => "value_is_percentage",
		}
	}
}

/// An on or off switch, stored as 1 or 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Flag(pub bool);

impl AttributeValue for Flag {
	fn from_stored(stored: f32) -> Option<Self> {
		if stored == 1.0 {
			Some(Self(true))
		} else if stored == 0.0 {
			Some(Self(false))
		} else {
			None
		}
	}

	fn to_stored(self) -> f32 {
		if self.0 { 1.0 } else { 0.0 }
	}
}

impl sealed::Sealed for Flag {}

/// A factor the game multiplies the hooked value by: a finite, nonnegative
/// float.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Multiplier(f32);

impl Multiplier {
	/// No change.
	pub const ONE: Self = Self(1.0);

	/// A finite, nonnegative factor, or `None` otherwise. Negative zero
	/// becomes zero.
	pub const fn new(factor: f32) -> Option<Self> {
		if factor.is_finite() && factor >= 0.0 {
			Some(Self(factor + 0.0))
		} else {
			None
		}
	}

	/// The factor.
	pub const fn get(self) -> f32 {
		self.0
	}
}

impl AttributeValue for Multiplier {
	fn from_stored(stored: f32) -> Option<Self> {
		Self::new(stored)
	}

	fn to_stored(self) -> f32 {
		self.0
	}
}

impl sealed::Sealed for Multiplier {}

/// A definition without its value type: what an [`AttributeSet`] keeps for
/// each entry, and what the setters need.
///
/// [`AttributeSet`]: super::AttributeSet
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct RawDef {
	pub(super) name: &'static CStr,
	pub(super) index: AttributeIndex,
	pub(super) class: &'static CStr,
	pub(super) format: DescriptionFormat,
	pub(super) min: f32,
	pub(super) max: f32,
}

impl RawDef {
	/// Whether a stored value lies within the bounds. NaN never does.
	pub(super) fn contains(self, stored: f32) -> bool {
		stored >= self.min && stored <= self.max
	}
}

/// A duration in seconds: a finite, nonnegative float.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Seconds(f32);

impl Seconds {
	/// No time.
	pub const ZERO: Self = Self(0.0);

	/// A finite, nonnegative number of seconds, or `None` otherwise. Negative
	/// zero becomes zero.
	pub const fn new(seconds: f32) -> Option<Self> {
		if seconds.is_finite() && seconds >= 0.0 {
			Some(Self(seconds + 0.0))
		} else {
			None
		}
	}

	/// The number of seconds.
	pub const fn get(self) -> f32 {
		self.0
	}
}

impl AttributeValue for Seconds {
	fn from_stored(stored: f32) -> Option<Self> {
		Self::new(stored)
	}

	fn to_stored(self) -> f32 {
		self.0
	}
}

impl sealed::Sealed for Seconds {}

/// Keeps [`AttributeValue`] from being implemented outside this module.
mod sealed {
	pub trait Sealed {}
}