Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions arcade/texture_atlas/atlas_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
TYPE_CHECKING,
Sequence,
)
from weakref import WeakSet, WeakValueDictionary, finalize
from weakref import WeakSet, WeakValueDictionary, finalize, ref

import PIL.Image
from PIL import Image, ImageDraw
Expand Down Expand Up @@ -356,14 +356,25 @@ def _add_texture_ref(self, texture: Texture, create_finalizer=True) -> None:
self._image_ref_count.inc_ref(texture.image_data)

if create_finalizer:
ref = finalize(
atlas_ref = ref(self)

# NOTE: The finalizer needs to be completely decoupled from the atlas
# or it will self-reference and not die unless all the textures in it
# are removed. This lead to leaking orphaned atlases when you have
# pre-loaded shared textures in multiple atlases.
def finalizer_callback(atlas_name, hash):
atlas = atlas_ref()
if atlas is not None:
atlas._remove_texture_by_identifiers(atlas_name, hash)

finalizer_ref = finalize(
texture,
self._remove_texture_by_identifiers,
finalizer_callback,
texture.atlas_name,
texture.image_data.hash,
)
# Don't bother removing texture on program exit
ref.atexit = False
finalizer_ref.atexit = False
self._finalizers_created += 1

self._textures_added += 1
Expand Down
Loading