/
_base.py
1121 lines (888 loc) · 34.1 KB
/
_base.py
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ../entities/_base.py
"""Provides a base class to interact with a specific entity."""
# =============================================================================
# >> IMPORTS
# =============================================================================
# Python Imports
# Collections
from collections import defaultdict
# Contextlib
from contextlib import suppress
# WeakRef
from weakref import WeakSet
# Source.Python Imports
# Core
from core import GAME_NAME
from core import BoostPythonClass
# Entities
from entities.constants import INVALID_ENTITY_INDEX
# Engines
from engines.precache import Model
from engines.sound import Attenuation
from engines.sound import engine_sound
from engines.sound import Channel
from engines.sound import Pitch
from engines.sound import Sound
from engines.sound import SoundFlags
from engines.sound import StreamSound
from engines.sound import VOL_NORM
from engines.trace import engine_trace
from engines.trace import ContentMasks
from engines.trace import GameTrace
from engines.trace import Ray
from engines.trace import TraceFilterSimple
# Entities
from _entities._entity import BaseEntity
from entities import BaseEntityGenerator
from entities import TakeDamageInfo
from entities.classes import server_classes
from entities.constants import DamageTypes
from entities.constants import RenderMode
from entities.helpers import index_from_inthandle
from entities.helpers import index_from_pointer
from entities.helpers import wrap_entity_mem_func
# Filters
from filters.weapons import WeaponClassIter
# Listeners
from listeners import OnEntityDeleted
from listeners import on_entity_deleted_listener_manager
from listeners.tick import Delay
# Mathlib
from mathlib import NULL_VECTOR
# Memory
from memory import make_object
# Players
from players.constants import HitGroup
# Studio
from studio.cache import model_cache
from studio.constants import INVALID_ATTACHMENT_INDEX
# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get a list of projectiles for the game
_projectile_weapons = [weapon.name for weapon in WeaponClassIter('grenade')]
# Get a dictionary to store the delays
_entity_delays = defaultdict(set)
# Get a set to store the registered entity classes
_entity_classes = WeakSet()
# =============================================================================
# >> CLASSES
# =============================================================================
class _EntityCaching(BoostPythonClass):
"""Metaclass used to cache entity instances."""
def __init__(cls, classname, bases, attributes):
"""Initializes the class."""
# New instances of this class will be cached in that dictionary
cls._cache = {}
# Add the class to the registered classes
_entity_classes.add(cls)
def __call__(cls, index, caching=True):
"""Called when a new instance of this class is requested.
:param int index:
The index of the entity instance requested.
:param bool caching:
Whether to lookup the cache for an existing instance or not.
"""
# Let's first lookup for a cached instance
if caching:
obj = cls._cache.get(index, None)
if obj is not None:
return obj
# Nothing in cache, let's create a new instance
obj = super().__call__(index)
# Let's cache the new instance we just created
if caching:
cls._cache[index] = obj
# We are done, let's return the instance
return obj
@property
def cache(cls):
"""Returns the cached instances of this class.
:rtype: dict
"""
return cls._cache
class Entity(BaseEntity, metaclass=_EntityCaching):
"""Class used to interact directly with entities.
Beside the standard way of doing stuff via methods and properties this
class also provides dynamic attributes that depend on the entity that is
being accessed with this class. You can print all dynamic properties by
iterating over the following generators:
1. :attr:`properties`
2. :attr:`inputs`
3. :attr:`outputs`
4. :attr:`keyvalues`
:var cache:
A read-only attribute that returns a dictionary containing the cached
instances of this class.
.. note::
This is not an instance property, so it can only be
accessed through the class itself.
"""
def __init__(self, index, caching=True):
"""Initialize the Entity instance.
:param int index:
The entity index to wrap.
:param bool caching:
Whether to lookup the cache for an existing instance or not.
"""
# Initialize the object
super().__init__(index)
# Set the entity's base attributes
object.__setattr__(self, '_index', index)
def __hash__(self):
"""Return a hash value based on the entity index."""
# Required for sets, because we have implemented __eq__
return hash(self.index)
def __getattr__(self, attr):
"""Find if the attribute is valid and returns the appropriate value."""
# Loop through all of the entity's server classes
for server_class in self.server_classes:
# Does the current server class contain the given attribute?
if hasattr(server_class, attr):
# Return the attribute's value
return getattr(make_object(server_class, self.pointer), attr)
# If the attribute is not found, raise an error
raise AttributeError('Attribute "{0}" not found'.format(attr))
def __setattr__(self, attr, value):
"""Find if the attribute is value and sets its value."""
# Is the given attribute a property?
if (attr in super().__dir__() and isinstance(
getattr(self.__class__, attr, None), property)):
# Set the property's value
object.__setattr__(self, attr, value)
# No need to go further
return
# Loop through all of the entity's server classes
for server_class in self.server_classes:
# Does the current server class contain the given attribute?
if hasattr(server_class, attr):
# Set the attribute's value
setattr(server_class(self.pointer, wrap=True), attr, value)
# No need to go further
return
# If the attribute is not found, just set the attribute
super().__setattr__(attr, value)
def __dir__(self):
"""Return an alphabetized list of attributes for the instance."""
# Get the base attributes
attributes = set(super().__dir__())
# Loop through all server classes for the entity
for server_class in self.server_classes:
# Loop through all of the server class' attributes
for attr in dir(server_class):
# Add the attribute if it is not private
if not attr.startswith('_'):
attributes.add(attr)
# Return a sorted list of attributes
return sorted(attributes)
@classmethod
def create(cls, classname):
"""Create a new networked entity with the given classname.
:param str classname:
Classname of the entity to create.
:raise ValueError:
Raised if the given classname is not a networked entity.
"""
entity = BaseEntity.create(classname)
if entity.is_networked():
return cls(entity.index)
entity.remove()
raise ValueError('"{}" is not a networked entity.'.format(classname))
@classmethod
def find(cls, classname):
"""Try to find an entity with the given classname.
If not entity has been found, None will be returned.
:param str classname:
The classname of the entity.
:return:
Return the found entity.
:rtype: Entity
"""
entity = BaseEntity.find(classname)
if entity is not None and entity.is_networked():
return cls(entity.index)
return None
@classmethod
def find_or_create(cls, classname):
"""Try to find an entity with the given classname.
If no entity has been found, it will be created.
:param str classname:
The classname of the entity.
:return:
Return the found or created entity.
:rtype: Entity
"""
entity = cls.find(classname)
if entity is None:
entity = cls.create(classname)
return entity
@classmethod
def from_inthandle(cls, inthandle):
"""Create an entity instance from an inthandle.
:param int inthandle:
The inthandle.
:rtype: Entity
"""
return cls(index_from_inthandle(inthandle))
@classmethod
def _obj(cls, ptr):
"""Return an entity instance of the given pointer."""
return cls(index_from_pointer(ptr))
def is_networked(self):
"""Return True if the entity is networked.
:rtype: bool
"""
return True
@property
def index(self):
"""Return the entity's index.
:rtype: int
"""
return self._index
@property
def owner(self):
"""Return the entity's owner.
:return:
None if the entity has no owner.
:rtype: Entity
"""
try:
return Entity(index_from_inthandle(self.owner_handle))
except (ValueError, OverflowError):
return None
@property
def server_classes(self):
"""Yield all server classes for the entity."""
yield from server_classes.get_entity_server_classes(self)
@property
def properties(self):
"""Iterate over all descriptors available for the entity."""
for server_class in self.server_classes:
yield from server_class.properties
@property
def inputs(self):
"""Iterate over all inputs available for the entity."""
for server_class in self.server_classes:
yield from server_class.inputs
@property
def outputs(self):
"""Iterate over all outputs available for the entity."""
for server_class in self.server_classes:
yield from server_class.outputs
@property
def keyvalues(self):
"""Iterate over all entity keyvalues available for the entity.
.. note::
An entity might also have hardcoded keyvalues that can't be listed
with this property.
"""
for server_class in self.server_classes:
yield from server_class.keyvalues
def get_model(self):
"""Return the entity's model.
:return:
``None`` if the entity has no model.
:rtype: Model
"""
if not self.model_name:
return None
return Model(self.model_name)
def set_model(self, model):
"""Set the entity's model to the given model.
:param Model model:
The model to set.
"""
self.model_index = model.index
self.model_name = model.path
model = property(
get_model, set_model,
doc="""Property to get/set the entity's model.
.. seealso:: :meth:`get_model` and :meth:`set_model`""")
def get_parent(self):
"""Return the entity's parent.
:rtype: Entity
"""
# Get the parent handle...
parent_inthandle = self.parent_inthandle
# Does the entity have no parent?
if parent_inthandle == -1:
return None
# Return the parent of the entity...
return Entity(index_from_inthandle(parent_inthandle))
def _set_parent(self, parent):
"""Set the parent of the entity.
:param Entity parent:
The parent of the entity. If None, actual parent will be cleared.
"""
# Clear the actual parent if None was given...
if parent is None:
self.clear_parent()
# Set the parent of the entity...
self.set_parent(parent)
parent = property(
get_parent, _set_parent,
doc="""Property to get/set the parent of the entity.
.. seealso:: :meth:`get_parent` and :meth:`set_parent`""")
def get_property_bool(self, name):
"""Return the boolean property.
:param str name:
Name of the property to retrieve.
:rtype: bool
"""
return self._get_property(name, 'bool')
def get_property_color(self, name):
"""Return the Color property.
:param str name:
Name of the property to retrieve.
:rtype: Color
"""
return self._get_property(name, 'Color')
def get_property_edict(self, name):
"""Return the Edict property.
:param str name:
Name of the property to retrieve.
:rtype: Edict
"""
return self._get_property(name, 'Edict')
def get_property_float(self, name):
"""Return the float property.
:param str name:
Name of the property to retrieve.
:rtype: float
"""
return self._get_property(name, 'float')
def get_property_int(self, name):
"""Return the integer property.
:param str name:
Name of the property to retrieve.
:rtype: int
"""
return self._get_property(name, 'int')
def get_property_interval(self, name):
"""Return the Interval property.
:param str name:
Name of the property to retrieve.
:rtype: Interval
"""
return self._get_property(name, 'Interval')
def get_property_pointer(self, name):
"""Return the pointer property.
:param str name:
Name of the property to retrieve.
:rtype: Pointer
"""
return self._get_property(name, 'pointer')
def get_property_quaternion(self, name):
"""Return the Quaternion property.
:param str name:
Name of the property to retrieve.
:rtype: Quaternion
"""
return self._get_property(name, 'Quaternion')
def get_property_short(self, name):
"""Return the short property.
:param str name:
Name of the property to retrieve.
:rtype: int
"""
return self._get_property(name, 'short')
def get_property_ushort(self, name):
"""Return the ushort property.
:param str name:
Name of the property to retrieve.
:rtype: int
"""
return self._get_property(name, 'ushort')
def get_property_string(self, name):
"""Return the string property.
:param str name:
Name of the property to retrieve.
:rtype: str
"""
return self._get_property(name, 'string_array')
def get_property_string_pointer(self, name):
"""Return the string property.
:param str name:
Name of the property to retrieve.
:rtype: str
"""
return self._get_property(name, 'string_pointer')
def get_property_char(self, name):
"""Return the char property.
:param str name:
Name of the property to retrieve.
:rtype: str
"""
return self._get_property(name, 'char')
def get_property_uchar(self, name):
"""Return the uchar property.
:param str name:
Name of the property to retrieve.
:rtype: int
"""
return self._get_property(name, 'uchar')
def get_property_uint(self, name):
"""Return the uint property.
:param str name:
Name of the property to retrieve.
:rtype: int
"""
return self._get_property(name, 'uint')
def get_property_vector(self, name):
"""Return the Vector property.
:param str name:
Name of the property to retrieve.
:rtype: Vector
"""
return self._get_property(name, 'Vector')
def _get_property(self, name, prop_type):
"""Verify the type and return the property."""
# Loop through all entity server classes
for server_class in self.server_classes:
# Is the name a member of the current server class?
if name not in server_class.properties:
continue
# Is the type the correct type?
if prop_type != server_class.properties[name].prop_type:
raise TypeError('Property "{0}" is of type {1} not {2}'.format(
name, server_class.properties[name].prop_type, prop_type))
# Return the property for the entity
return getattr(
make_object(server_class._properties, self.pointer), name)
# Raise an error if the property name was not found
raise ValueError(
'Property "{0}" not found for entity type "{1}"'.format(
name, self.classname))
def set_property_bool(self, name, value):
"""Set the boolean property.
:param str name:
Name of the property to set.
:param bool value:
The value to set.
"""
self._set_property(name, 'bool', value)
def set_property_color(self, name, value):
"""Set the Color property.
:param str name:
Name of the property to set.
:param Color value:
The value to set.
"""
self._set_property(name, 'Color', value)
def set_property_edict(self, name, value):
"""Set the Edict property.
:param str name:
Name of the property to set.
:param Edict value:
The value to set.
"""
self._set_property(name, 'Edict', value)
def set_property_float(self, name, value):
"""Set the float property.
:param str name:
Name of the property to set.
:param float value:
The value to set.
"""
self._set_property(name, 'float', value)
def set_property_int(self, name, value):
"""Set the integer property.
:param str name:
Name of the property to set.
:param int value:
The value to set.
"""
self._set_property(name, 'int', value)
def set_property_interval(self, name, value):
"""Set the Interval property.
:param str name:
Name of the property to set.
:param Interval value:
The value to set.
"""
self._set_property(name, 'Interval', value)
def set_property_pointer(self, name, value):
"""Set the pointer property.
:param str name:
Name of the property to set.
:param Pointer value:
The value to set.
"""
self._set_property(name, 'pointer', value)
def set_property_quaternion(self, name, value):
"""Set the Quaternion property.
:param str name:
Name of the property to set.
:param Quaternion value:
The value to set.
"""
self._set_property(name, 'Quaternion', value)
def set_property_short(self, name, value):
"""Set the short property.
:param str name:
Name of the property to set.
:param int value:
The value to set.
"""
self._set_property(name, 'short', value)
def set_property_ushort(self, name, value):
"""Set the ushort property.
:param str name:
Name of the property to set.
:param int value:
The value to set.
"""
self._set_property(name, 'ushort', value)
def set_property_string(self, name, value):
"""Set the string property.
:param str name:
Name of the property to set.
:param str value:
The value to set.
"""
self._set_property(name, 'string_array', value)
def set_property_string_pointer(self, name, value):
"""Set the string property.
:param str name:
Name of the property to set.
:param str value:
The value to set.
"""
self._set_property(name, 'string_pointer', value)
def set_property_char(self, name, value):
"""Set the char property.
:param str name:
Name of the property to set.
:param str value:
The value to set.
"""
self._set_property(name, 'char', value)
def set_property_uchar(self, name, value):
"""Set the uchar property.
:param str name:
Name of the property to set.
:param int value:
The value to set.
"""
self._set_property(name, 'uchar', value)
def set_property_uint(self, name, value):
"""Set the uint property.
:param str name:
Name of the property to set.
:param int value:
The value to set.
"""
self._set_property(name, 'uint', value)
def set_property_vector(self, name, value):
"""Set the Vector property.
:param str name:
Name of the property to set.
:param Vector value:
The value to set.
"""
self._set_property(name, 'Vector', value)
def _set_property(self, name, prop_type, value):
"""Verify the type and set the property."""
# Loop through all entity server classes
for server_class in self.server_classes:
# Is the name a member of the current server class?
if name not in server_class.properties:
continue
# Is the type the correct type?
if prop_type != server_class.properties[name].prop_type:
raise TypeError('Property "{0}" is of type {1} not {2}'.format(
name, server_class.properties[name].prop_type, prop_type))
# Set the property for the entity
setattr(make_object(
server_class._properties, self.pointer), name, value)
# Is the property networked?
if server_class.properties[name].networked:
# Notify the change of state
self.edict.state_changed()
# No need to go further
return
# Raise an error if the property name was not found
raise ValueError(
'Property "{0}" not found for entity type "{1}"'.format(
name, self.classname))
def delay(
self, delay, callback, args=(), kwargs=None,
cancel_on_level_end=False):
"""Execute a callback after the given delay.
:param float delay:
The delay in seconds.
:param callback:
A callable object that should be called after the delay expired.
:param tuple args:
Arguments that should be passed to the callback.
:param dict kwargs:
Keyword arguments that should be passed to the callback.
:param bool cancel_on_level_end:
Whether or not to cancel the delay at the end of the map.
:raise ValueError:
If the given callback is not callable.
:return:
The delay instance.
:rtype: Delay
"""
# TODO: Ideally, we want to subclass Delay and cleanup on cancel() too
# in case the caller manually cancel the returned Delay.
def _callback(*args, **kwargs):
"""Called when the delay is executed."""
# Remove the delay from the global dictionary...
_entity_delays[self.index].remove(delay)
# Was this the last pending delay for the entity?
if not _entity_delays[self.index]:
# Remove the entity from the dictionary...
del _entity_delays[self.index]
# Call the callback...
callback(*args, **kwargs)
# Get the delay instance...
delay = Delay(delay, _callback, args, kwargs, cancel_on_level_end)
# Add the delay to the dictionary...
_entity_delays[self.index].add(delay)
# Return the delay instance...
return delay
def get_input(self, name):
"""Return the input function matching the given name.
:parma str name:
Name of the input function.
:rtype: InputFunction
:raise ValueError:
Raised if the input function wasn't found.
"""
# Loop through each server class for the entity
for server_class in self.server_classes:
# Does the current server class contain the input?
if name in server_class.inputs:
# Return the InputFunction instance for the given input name
return getattr(
make_object(server_class._inputs, self.pointer), name)
# If no server class contains the input, raise an error
raise ValueError(
'Unknown input "{0}" for entity type "{1}".'.format(
name, self.classname))
def call_input(self, name, *args, **kwargs):
"""Call the input function matching the given name.
:param str name:
Name of the input function.
:param args:
Optional arguments that should be passed to the input function.
:param kwargs:
Optional keyword arguments that should be passed to the input
function.
:raise ValueError:
Raised if the input function wasn't found.
"""
self.get_input(name)(*args, **kwargs)
def emit_sound(
self, sample, recipients=(), volume=VOL_NORM,
attenuation=Attenuation.NONE, channel=Channel.AUTO,
flags=SoundFlags.NO_FLAGS, pitch=Pitch.NORMAL, origin=NULL_VECTOR,
direction=NULL_VECTOR, origins=(), update_positions=True,
sound_time=0.0, speaker_entity=INVALID_ENTITY_INDEX,
download=False, stream=False):
"""Emit a sound from this entity.
:param str sample:
Sound file relative to the ``sounds`` directory.
:param RecipientFilter recipients:
Recipients to emit the sound to.
:param int index:
Index of the entity to emit the sound from.
:param float volume:
Volume of the sound.
:param Attenuation attenuation:
How far the sound should reaches.
:param int channel:
Channel to emit the sound with.
:param SoundFlags flags:
Flags of the sound.
:param Pitch pitch:
Pitch of the sound.
:param Vector origin:
Origin of the sound.
:param Vector direction:
Direction of the sound.
:param tuple origins:
Origins of the sound.
:param bool update_positions:
Whether or not the positions should be updated.
:param float sound_time:
Time to play the sound for.
:param int speaker_entity:
Index of the speaker entity.
:param bool download:
Whether or not the sample should be added to the downloadables.
:param bool stream:
Whether or not the sound should be streamed.
"""
# Get the correct Sound class...
if not stream:
sound_class = Sound
else:
sound_class = StreamSound
# Get the sound...
sound = sound_class(sample, self.index, volume, attenuation, channel,
flags, pitch, origin, direction, origins, update_positions,
sound_time, speaker_entity, download)
# Make sure we have a tuple as recipients...
if not isinstance(recipients, tuple):
recipients = (recipients,)
# Emit the sound to the given recipients...
sound.play(*recipients)
def is_in_solid(
self, mask=ContentMasks.ALL, generator=BaseEntityGenerator):
"""Return whether or not the entity is in solid.
:param ContentMasks mask:
Contents the ray can possibly collide with.
:param generator:
A callable that returns an iterable which contains
:class:`BaseEntity` instances that are ignored by the ray.
:rtype: bool
"""
# Get a Ray object of the entity physic box
ray = Ray(self.origin, self.origin, self.mins, self.maxs)
# Get a new GameTrace instance
trace = GameTrace()
# Do the trace
engine_trace.trace_ray(ray, mask, TraceFilterSimple(
generator()), trace)
# Return whether or not the trace did hit
return trace.did_hit()
def take_damage(
self, damage, damage_type=DamageTypes.GENERIC, attacker_index=None,
weapon_index=None, hitgroup=HitGroup.GENERIC, skip_hooks=False,
**kwargs):
"""Deal damage to the entity.
:param int damage:
Amount of damage to deal.
:param DamageTypes damage_type:
Type of the dealed damage.
:param int attacker_index:
If not None, the index will be used as the attacker.
:param int weapon_index:
If not None, the index will be used as the weapon. This method
also tries to retrieve the attacker from the weapon, if
``attacker_index`` wasn't set.
:param HitGroup hitgroup:
The hitgroup where the damage should be applied.
:param bool skip_hooks:
If True, the damage will be dealed directly by skipping any
registered hooks.
"""
# Import Entity classes
# Doing this in the global scope causes cross import errors
from weapons.entity import Weapon
# Is the game supported?
if not hasattr(self, 'on_take_damage'):
# Raise an error if not supported
raise NotImplementedError(
'"take_damage" is not implemented for {0}'.format(GAME_NAME))
# Store values for later use
attacker = None
weapon = None
# Was an attacker given?
if attacker_index is not None:
# Try to get the Entity instance of the attacker
with suppress(ValueError):
attacker = Entity(attacker_index)
# Was a weapon given?
if weapon_index is not None:
# Try to get the Weapon instance of the weapon
with suppress(ValueError):
weapon = Weapon(weapon_index)
# Is there a weapon but no attacker?
if attacker is None and weapon is not None:
# Try to get the attacker based off of the weapon's owner
with suppress(ValueError, OverflowError):
attacker_index = index_from_inthandle(weapon.owner_handle)
attacker = Entity(attacker_index)