From 37fbf98932ff2c0676c4daf58b83636c27dfe3b9 Mon Sep 17 00:00:00 2001 From: Paul V Craven Date: Thu, 1 Oct 2026 13:56:12 -0500 Subject: [PATCH] Add early-exit and between-lists collision functions - has_collision_with_list() and has_collision_with_lists() return True at the first collision instead of building the whole hit list. About 18x faster than checking for an empty result when many sprites overlap. - check_for_collision_between_lists(list_a, list_b) returns every colliding (sprite_a, sprite_b) pair, such as bullets and enemies. Given the same list twice, each pair is returned once. Use the early-exit functions in the physics engines (initial overlap check, wiggle loop, ceiling loop, is_on_ladder, can_jump) and the A* pathfinding (_check_for_collision, AStarBarrierList.recalculate), everywhere only a yes/no answer was needed. Building an AStarBarrierList is about 7-9% faster. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + arcade/__init__.py | 6 + arcade/paths.py | 11 +- arcade/physics_engines.py | 24 ++-- arcade/sprite_list/__init__.py | 6 + arcade/sprite_list/collision.py | 148 +++++++++++++++++++++ tests/unit/sprite/test_sprite_collision.py | 143 ++++++++++++++++++++ 7 files changed, 318 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dd7675faa..ca443ae45c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,8 +27,11 @@ Arcade [PyPi Release History](https://pypi.org/project/arcade/#history) page. ### New Features - Added `HitBox.get_adjusted_bounds()`, which returns the cached `(left, right, bottom, top)` bounds of the adjusted hit box points. - Added `arcade.CollisionMethod`, an enum for the `method` argument of `check_for_collision_with_list` and `check_for_collision_with_lists`: `AUTO`, `SPATIAL`, `GPU`, and `SIMPLE`. It's an `IntEnum`, so the numbers `0` to `3` still work. +- Added `arcade.has_collision_with_list()` and `arcade.has_collision_with_lists()`, which return `True` as soon as they find a collision. They're faster than checking whether `check_for_collision_with_list()` returns an empty list, by about 18x when many sprites overlap. +- Added `arcade.check_for_collision_between_lists(list_a, list_b)`, which returns every colliding `(sprite_a, sprite_b)` pair between two lists, such as bullets and enemies. Passing the same list twice returns each pair once. ### Misc Changes +- The platformer and simple physics engines and `AStarBarrierList` now use `has_collision_with_list(s)` where they only need to know whether there's a collision. Building an `AStarBarrierList` is about 7-9% faster. - Sped up sprite collision checks. Sprites that pass the quick distance check are now compared by cached hit box bounds before the polygon test, and the polygon test skips horizontal and vertical edges, which the bounds check already covers. Checks that reach the polygon test are about 2-4x faster, e.g. 8.0 to 2.3 µs for two box hit boxes and 21.6 to 10.2 µs for two default octagon hit boxes. `are_polygons_intersecting` is also faster (7.3 to 1.6 µs for two rectangles). - Sped up collision checks further by caching each hit box's distinct edge directions. Parallel edges (such as opposite sides of the default octagon hit boxes, or matching edges on two sprites with the same angle) are only tested once, and the cache is kept when a sprite moves. Two unrotated octagon hit boxes go from 12.0 to 4.6 µs, and two rotated 30° from 20.8 to 6.9 µs. - `SpatialHash` now uses the hit box's cached bounds to find a sprite's grid cells, so they're shared with collision checks. Adding, removing, and querying for sprites that haven't moved is about 33-40% faster. diff --git a/arcade/__init__.py b/arcade/__init__.py index 9301430e2d..d6b3aeb6c5 100644 --- a/arcade/__init__.py +++ b/arcade/__init__.py @@ -187,6 +187,9 @@ def configure_logging(level: int | None = None): from .sprite_list import check_for_collision from .sprite_list import check_for_collision_with_list from .sprite_list import check_for_collision_with_lists +from .sprite_list import check_for_collision_between_lists +from .sprite_list import has_collision_with_list +from .sprite_list import has_collision_with_lists from .sprite_list import get_closest_sprite from .sprite_list import get_sprites_at_exact_point from .sprite_list import get_sprites_at_point @@ -330,6 +333,9 @@ def configure_logging(level: int | None = None): "check_for_collision", "check_for_collision_with_list", "check_for_collision_with_lists", + "check_for_collision_between_lists", + "has_collision_with_list", + "has_collision_with_lists", "close_window", "disable_timings", "draw_arc_filled", diff --git a/arcade/paths.py b/arcade/paths.py index a6cb3b249c..d13624afc7 100644 --- a/arcade/paths.py +++ b/arcade/paths.py @@ -8,7 +8,7 @@ BasicSprite, Sprite, SpriteSequence, - check_for_collision_with_list, + has_collision_with_list, get_sprites_at_point, ) from arcade.math import get_distance, lerp_2d @@ -33,9 +33,9 @@ def _spot_is_blocked( """ original_pos = moving_sprite.position moving_sprite.position = position - hit_list = check_for_collision_with_list(moving_sprite, blocking_sprites) + hit = has_collision_with_list(moving_sprite, blocking_sprites) moving_sprite.position = original_pos - return len(hit_list) > 0 + return hit def _heuristic(start: Point2, goal: Point2) -> float: @@ -319,10 +319,7 @@ def recalculate(self): # See if we'll have a collision if our sprite is at this location self.moving_sprite.position = pos - if ( - len(check_for_collision_with_list(self.moving_sprite, self.blocking_sprites)) - > 0 - ): + if has_collision_with_list(self.moving_sprite, self.blocking_sprites): self.barrier_list.add(cpos) # Restore original location diff --git a/arcade/physics_engines.py b/arcade/physics_engines.py index d68275d77e..d93f420ca4 100644 --- a/arcade/physics_engines.py +++ b/arcade/physics_engines.py @@ -12,6 +12,7 @@ SpriteType, check_for_collision, check_for_collision_with_lists, + has_collision_with_lists, ) from arcade.math import get_distance @@ -71,10 +72,7 @@ def _wiggle_until_free(colliding: Sprite, walls: Iterable[SpriteSequence[BasicSp for strided_index in range(0, 16, 2): x, y = try_list[strided_index:strided_index + 2] colliding.position = x, y - check_hit_list = check_for_collision_with_lists(colliding, walls) - # print(f"Vary {vary} ({trapped.center_x} {trapped.center_y}) " - # f"= {len(check_hit_list)}") - if len(check_hit_list) == 0: + if not has_collision_with_lists(colliding, walls): return wiggle_distance *= 2 @@ -104,7 +102,7 @@ def _move_sprite( collided with. """ # See if we are starting this turn with a sprite already colliding with us. - if len(check_for_collision_with_lists(moving_sprite, can_collide)) > 0: + if has_collision_with_lists(moving_sprite, can_collide): _wiggle_until_free(moving_sprite, can_collide) original_x, original_y = moving_sprite.position @@ -143,7 +141,7 @@ def _move_sprite( # If we hit a wall, move so the edges are at the same point if len(hit_list_x) > 0: if moving_sprite.change_y > 0: - while len(check_for_collision_with_lists(moving_sprite, can_collide)) > 0: + while has_collision_with_lists(moving_sprite, can_collide): moving_sprite.center_y -= 1 # print(f"Spot X ({self.player_sprite.center_x}, {self.player_sprite.center_y})" # f" {self.player_sprite.change_y}") @@ -645,9 +643,7 @@ def is_on_ladder(self) -> bool: :py:attr:`ladders`. """ if self.ladders: - hit_list = check_for_collision_with_lists(self.player_sprite, self.ladders) - if len(hit_list) > 0: - return True + return has_collision_with_lists(self.player_sprite, self.ladders) return False def can_jump(self, y_distance: float = 5) -> bool: @@ -686,18 +682,14 @@ def can_jump(self, y_distance: float = 5) -> bool: # Temporarily move the player down to collide floor-like sprites self.player_sprite.center_y -= y_distance - hit_list = check_for_collision_with_lists(self.player_sprite, self._all_obstacles) + on_ground = has_collision_with_lists(self.player_sprite, self._all_obstacles) self.player_sprite.center_y += y_distance # Reset the number jumps if the player touched a floor-like sprite - if len(hit_list) > 0: + if on_ground: self.jumps_since_ground = 0 - if ( - len(hit_list) > 0 - or self.allow_multi_jump - and self.jumps_since_ground < self.allowed_jumps - ): + if on_ground or self.allow_multi_jump and self.jumps_since_ground < self.allowed_jumps: return True else: return False diff --git a/arcade/sprite_list/__init__.py b/arcade/sprite_list/__init__.py index c2c1802c3a..a4a00b5fb7 100644 --- a/arcade/sprite_list/__init__.py +++ b/arcade/sprite_list/__init__.py @@ -7,6 +7,9 @@ check_for_collision, check_for_collision_with_list, check_for_collision_with_lists, + check_for_collision_between_lists, + has_collision_with_list, + has_collision_with_lists, get_sprites_at_point, get_sprites_at_exact_point, get_sprites_in_rect, @@ -23,6 +26,9 @@ "check_for_collision", "check_for_collision_with_list", "check_for_collision_with_lists", + "check_for_collision_between_lists", + "has_collision_with_list", + "has_collision_with_lists", "get_sprites_at_point", "get_sprites_at_exact_point", "get_sprites_in_rect", diff --git a/arcade/sprite_list/collision.py b/arcade/sprite_list/collision.py index 8d7b131ec7..c06807c925 100644 --- a/arcade/sprite_list/collision.py +++ b/arcade/sprite_list/collision.py @@ -1,5 +1,6 @@ from collections.abc import Iterable from enum import IntEnum +from typing import TypeVar from arcade.geometry import ( _are_polygons_overlapping_on_axes, @@ -14,6 +15,9 @@ from .sprite_list import SpriteSequence +# The sprite type of the second list in check_for_collision_between_lists +_SpriteType2 = TypeVar("_SpriteType2", bound=BasicSprite) + class CollisionMethod(IntEnum): """ @@ -259,6 +263,150 @@ def check_for_collision_with_list( # collision_list.append(sprite2) +def has_collision_with_list( + sprite: BasicSprite, + sprite_list: SpriteSequence[BasicSprite], + method: CollisionMethod | int = CollisionMethod.AUTO, +) -> bool: + """ + Check if a sprite collides with any sprite in a list. + + This is faster than checking whether :py:func:`check_for_collision_with_list` + returns an empty list, since it stops at the first collision it finds. + + Args: + sprite: + Sprite to check + sprite_list: + SpriteList to check against + method: + How to find the sprites to check. See :py:class:`CollisionMethod`. + Defaults to :py:attr:`CollisionMethod.AUTO`. + + Returns: + ``True`` if the sprite collides with at least one sprite in the list. + """ + if __debug__: + if not isinstance(sprite, BasicSprite): + raise TypeError( + f"Parameter 1 is not an instance of the Sprite class, " + f"it is an instance of {type(sprite)}." + ) + if not isinstance(sprite_list, SpriteSequence): + raise TypeError(f"Parameter 2 is a {type(sprite_list)} instead of expected SpriteList.") + + for sprite2 in _get_sprites_to_check(sprite, sprite_list, method): + if sprite is not sprite2 and _check_for_collision(sprite, sprite2): + return True + return False + + +def has_collision_with_lists( + sprite: BasicSprite, + sprite_lists: Iterable[SpriteSequence[BasicSprite]], + method: CollisionMethod | int = CollisionMethod.AUTO, +) -> bool: + """ + Check if a sprite collides with any sprite in any of several lists. + + This is faster than checking whether :py:func:`check_for_collision_with_lists` + returns an empty list, since it stops at the first collision it finds. + + Args: + sprite: + Sprite to check + sprite_lists: + SpriteLists to check against + method: + How to find the sprites to check. See :py:class:`CollisionMethod`. + Defaults to :py:attr:`CollisionMethod.AUTO`. + + Returns: + ``True`` if the sprite collides with at least one sprite in the lists. + """ + if __debug__: + if not isinstance(sprite, BasicSprite): + raise TypeError( + f"Parameter 1 is not an instance of the BasicSprite class, " + f"it is an instance of {type(sprite)}." + ) + + for sprite_list in sprite_lists: + for sprite2 in _get_sprites_to_check(sprite, sprite_list, method): + if sprite is not sprite2 and _check_for_collision(sprite, sprite2): + return True + return False + + +def check_for_collision_between_lists( + sprite_list_a: SpriteSequence[SpriteType], + sprite_list_b: SpriteSequence[_SpriteType2], + method: CollisionMethod | int = CollisionMethod.AUTO, +) -> list[tuple[SpriteType, _SpriteType2]]: + """ + Find every pair of colliding sprites between two lists. + + For example, to remove bullets and the enemies they hit:: + + for bullet, enemy in arcade.check_for_collision_between_lists(bullets, enemies): + bullet.remove_from_sprite_lists() + enemy.remove_from_sprite_lists() + + A sprite can be in more than one pair, such as a bullet hitting two + enemies at once. + + For each sprite in ``sprite_list_a``, ``method`` chooses how to find the + sprites in ``sprite_list_b`` to check, the same way as in + :py:func:`check_for_collision_with_list`. For the best speed, enable + spatial hashing on ``sprite_list_b``, and make it the list whose sprites + move less. + + If both arguments are the same list, each colliding pair is returned + once, and sprites are never paired with themselves. + + Args: + sprite_list_a: + The first list of sprites + sprite_list_b: + The second list of sprites + method: + How to find the sprites in ``sprite_list_b`` to check. See + :py:class:`CollisionMethod`. Defaults to :py:attr:`CollisionMethod.AUTO`. + + Returns: + A list of ``(sprite_a, sprite_b)`` tuples, or an empty list. + """ + if __debug__: + if not isinstance(sprite_list_a, SpriteSequence): + raise TypeError( + f"Parameter 1 is a {type(sprite_list_a)} instead of expected SpriteList." + ) + if not isinstance(sprite_list_b, SpriteSequence): + raise TypeError( + f"Parameter 2 is a {type(sprite_list_b)} instead of expected SpriteList." + ) + + pairs: list[tuple[SpriteType, _SpriteType2]] = [] + if not sprite_list_a or not sprite_list_b: + return pairs + + if sprite_list_a is sprite_list_b: + # Only report each pair once, by skipping sprites already checked + checked: set[BasicSprite] = set() + for sprite_a in sprite_list_a: + checked.add(sprite_a) + for sprite_b in _get_sprites_to_check(sprite_a, sprite_list_b, method): + if sprite_b not in checked and _check_for_collision(sprite_a, sprite_b): + pairs.append((sprite_a, sprite_b)) + return pairs + + for sprite_a in sprite_list_a: + for sprite_b in _get_sprites_to_check(sprite_a, sprite_list_b, method): + if sprite_a is not sprite_b and _check_for_collision(sprite_a, sprite_b): + pairs.append((sprite_a, sprite_b)) + return pairs + + def check_for_collision_with_lists( sprite: BasicSprite, sprite_lists: Iterable[SpriteSequence[SpriteType]], diff --git a/tests/unit/sprite/test_sprite_collision.py b/tests/unit/sprite/test_sprite_collision.py index 520acb5abc..de52f7bd16 100644 --- a/tests/unit/sprite/test_sprite_collision.py +++ b/tests/unit/sprite/test_sprite_collision.py @@ -356,6 +356,149 @@ def test_touching_edges(window): assert arcade.get_sprites_at_point((5, 0), sprite_list) == [a] +@pytest.mark.parametrize("method", list(arcade.CollisionMethod)) +@pytest.mark.parametrize("spatial", [False, True]) +def test_has_collision_with_list(window, method, spatial): + """has_collision_with_list matches whether check_for_collision_with_list finds anything""" + sprite = arcade.SpriteSolidColor(10, 10) + sprite_list = arcade.SpriteList(use_spatial_hash=spatial) + for x in (100, 200): + sprite_list.append(arcade.SpriteSolidColor(10, 10, center_x=x)) + # A sprite never collides with itself + sprite_list.append(sprite) + + assert arcade.has_collision_with_list(sprite, sprite_list, method=method) is False + assert arcade.check_for_collision_with_list(sprite, sprite_list, method=method) == [] + + sprite.center_x = 195 + assert arcade.has_collision_with_list(sprite, sprite_list, method=method) is True + assert arcade.check_for_collision_with_list(sprite, sprite_list, method=method) != [] + + # Touching edges don't count, the same as check_for_collision + sprite.center_x = 190 + assert arcade.has_collision_with_list(sprite, sprite_list, method=method) is False + + assert arcade.has_collision_with_list(sprite, arcade.SpriteList(), method=method) is False + + +def test_has_collision_with_list_stops_at_first_hit(window, monkeypatch): + """has_collision_with_list checks no more sprites than it needs to""" + from arcade.sprite_list import collision + + sprite = arcade.SpriteSolidColor(10, 10) + sprite_list = arcade.SpriteList() + for _ in range(10): + sprite_list.append(arcade.SpriteSolidColor(10, 10)) + + checked = [] + original = collision._check_for_collision + + def counting(sprite1, sprite2): + checked.append(sprite2) + return original(sprite1, sprite2) + + monkeypatch.setattr(collision, "_check_for_collision", counting) + assert arcade.has_collision_with_list(sprite, sprite_list) is True + assert checked == [sprite_list[0]] + + checked.clear() + assert arcade.has_collision_with_lists(sprite, [arcade.SpriteList(), sprite_list]) is True + assert checked == [sprite_list[0]] + + +def test_has_collision_with_lists(window): + sprite = arcade.SpriteSolidColor(10, 10) + near = arcade.SpriteSolidColor(10, 10, center_x=5) + far = arcade.SpriteList() + far.append(arcade.SpriteSolidColor(10, 10, center_x=100)) + hit = arcade.SpriteList(use_spatial_hash=True) + hit.append(near) + + assert arcade.has_collision_with_lists(sprite, []) is False + assert arcade.has_collision_with_lists(sprite, [far]) is False + assert arcade.has_collision_with_lists(sprite, [far, hit]) is True + assert arcade.has_collision_with_lists(sprite, (sl for sl in [far, hit])) is True + + with pytest.raises(TypeError): + arcade.has_collision_with_lists("moo", [far]) + + +def test_has_collision_with_list_type_errors(window): + sprite = arcade.SpriteSolidColor(10, 10) + with pytest.raises(TypeError): + arcade.has_collision_with_list("moo", arcade.SpriteList()) + with pytest.raises(TypeError): + arcade.has_collision_with_list(sprite, "moo") + + +@pytest.mark.parametrize("spatial", [False, True]) +def test_check_for_collision_between_lists(window, spatial): + bullets = arcade.SpriteList() + for x in (0, 100, 300): + bullets.append(arcade.SpriteSolidColor(4, 4, center_x=x)) + enemies = arcade.SpriteList(use_spatial_hash=spatial) + for x in (2, 98, 104, 500): + enemies.append(arcade.SpriteSolidColor(10, 10, center_x=x)) + + pairs = arcade.check_for_collision_between_lists(bullets, enemies) + expected = [ + (bullets[0], enemies[0]), + (bullets[1], enemies[1]), + (bullets[1], enemies[2]), # One bullet can hit two enemies + ] + # A spatial hash returns sprites in no particular order + assert len(pairs) == len(expected) + assert set(pairs) == set(expected) + + # Each pair matches check_for_collision + for a, b in pairs: + assert arcade.check_for_collision(a, b) + + # Swapping the lists swaps the pairs + swapped = arcade.check_for_collision_between_lists(enemies, bullets) + assert len(swapped) == len(expected) + assert set(swapped) == {(b, a) for a, b in expected} + + # Empty lists + assert arcade.check_for_collision_between_lists(bullets, arcade.SpriteList()) == [] + assert arcade.check_for_collision_between_lists(arcade.SpriteList(), enemies) == [] + + +@pytest.mark.parametrize("spatial", [False, True]) +def test_check_for_collision_between_lists_same_list(window, spatial): + """With the same list twice, each pair is returned once and never a sprite with itself""" + sprites = arcade.SpriteList(use_spatial_hash=spatial) + for x in (0, 5, 8, 100): + sprites.append(arcade.SpriteSolidColor(10, 10, center_x=x)) + a, b, c, far = sprites + + pairs = arcade.check_for_collision_between_lists(sprites, sprites) + assert len(pairs) == 3 + assert {frozenset(pair) for pair in pairs} == { + frozenset((a, b)), + frozenset((a, c)), + frozenset((b, c)), + } + + +def test_check_for_collision_between_lists_shared_sprite(window): + """A sprite in both lists isn't paired with itself""" + shared = arcade.SpriteSolidColor(10, 10) + other = arcade.SpriteSolidColor(10, 10, center_x=5) + list_a = arcade.SpriteList() + list_a.append(shared) + list_b = arcade.SpriteList() + list_b.extend([shared, other]) + assert arcade.check_for_collision_between_lists(list_a, list_b) == [(shared, other)] + + +def test_check_for_collision_between_lists_type_errors(window): + with pytest.raises(TypeError): + arcade.check_for_collision_between_lists("moo", arcade.SpriteList()) + with pytest.raises(TypeError): + arcade.check_for_collision_between_lists(arcade.SpriteList(), "moo") + + def test_check_for_collision_with_list(window): # TODO: Check that the right collision function is called internally a = arcade.SpriteSolidColor(50, 50, color=arcade.csscolor.RED)