Skip to content

Commit 02ea4e1

Browse files
committed
Fixed the invalidation of the internal entity cache before all entity deletion listeners were called.
Fixed a KeyError being silenced in EntityDictionary.on_automatically_removed overrides. Slightly improved the retrieval speed of the cached entity instances.
1 parent debc63b commit 02ea4e1

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

addons/source-python/packages/source-python/entities/_base.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,10 @@ def __call__(cls, index, caching=True):
101101
"""
102102
# Let's first lookup for a cached instance
103103
if caching:
104-
obj = cls._cache.get(index, None)
105-
if obj is not None:
106-
return obj
104+
try:
105+
return cls._cache[index]
106+
except KeyError:
107+
pass
107108

108109
# Nothing in cache, let's create a new instance
109110
obj = super().__call__(index)
@@ -129,6 +130,17 @@ def cache(cls):
129130
"""
130131
return cls._cache
131132

133+
@staticmethod
134+
def _invalidate_cache(base_entity):
135+
"""Invalidates the cache for the given entity."""
136+
try:
137+
index = base_entity.index
138+
except ValueError:
139+
return
140+
141+
for cls in _entity_classes:
142+
cls.cache.pop(index, None)
143+
132144

133145
class Entity(BaseEntity, metaclass=_EntityCaching):
134146
"""Class used to interact directly with entities.
@@ -1225,10 +1237,6 @@ def _on_entity_deleted(base_entity):
12251237
except ValueError:
12261238
return
12271239

1228-
# Cleanup the cache
1229-
for cls in _entity_classes:
1230-
cls.cache.pop(index, None)
1231-
12321240
with suppress(KeyError):
12331241
# Loop through all delays...
12341242
for delay in _entity_delays[index]:

addons/source-python/packages/source-python/entities/dictionary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def _on_entity_deleted(self, base_entity):
8888
except ValueError:
8989
return
9090

91-
with suppress(KeyError):
91+
if index in self:
9292
# Call the deletion callback for the index...
9393
self.on_automatically_removed(index)
9494

src/core/sp_main.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,10 @@ void CSourcePython::OnEntitySpawned( CBaseEntity *pEntity )
631631
void CSourcePython::OnEntityDeleted( CBaseEntity *pEntity )
632632
{
633633
CALL_LISTENERS(OnEntityDeleted, ptr((CBaseEntityWrapper*) pEntity));
634+
635+
// Invalidate the internal entity cache once all callbacks have been called.
636+
static object oCacheInvalidator = import("entities").attr("_base").attr("_EntityCaching").attr("_invalidate_cache");
637+
oCacheInvalidator(ptr((CBaseEntityWrapper*) pEntity));
634638
}
635639

636640
void CSourcePython::OnDataLoaded( MDLCacheDataType_t type, MDLHandle_t handle )

0 commit comments

Comments
 (0)