Use cached hit box bounds in the spatial hash - #2900
Merged
Merged
Conversation
SpatialHash._get_cell_bounds() scanned the hit box's adjusted points itself. It now reads HitBox.get_adjusted_bounds(), which caches the bounds until the points change and shares them with collision checks. For sprites that haven't moved since their bounds were last needed, querying is ~40% faster and add + remove ~33% faster. Moving sprites are unchanged, since their points are recalculated either way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
SpatialHash._get_cell_bounds()(added in #2893) scanned a sprite's adjusted hit box points itself to find which grid cells it covers. It now readsHitBox.get_adjusted_bounds()(added in #2894) instead. That method caches the bounds until the points change, and collision checks already use it, so a sprite's bounds are now computed once and shared.The results are identical: same minimum and maximum, same
truncand cell hashing. The existingtest_cell_bounds_match_sprite_bounds(including rotated sprites) and the spatial hash tests all pass unchanged.Benchmarks
µs per call, best of 21 × 200,000 calls, 3 alternating before/after rounds (range shown):
get_sprites_near_sprite, sprite that hasn't movedadd+remove, sprite that hasn't movedget_sprites_near_sprite, sprite moving each callcheck_for_collisionA sprite that hasn't moved gets its bounds straight from the cache, so it's about 33–40% faster. A moving sprite has its points recalculated either way, so those cases are unchanged within noise.
benchmarks/spatial_hash/queries.pystill shows no bucket growth (102 buckets before and after querying a 20000×20000 area).Tests
spatial_hash.py.🤖 Generated with Claude Code