GRID BUCKETS · EXACT GEOMETRY · ORACLE TESTS
Build a spatial hashing collision lab
Use a uniform grid to propose circle pairs, reject false positives, and check every result against a brute-force oracle.
Install one working laboratory
Prerequisites: Squeak 6.1, Workspace Do It / Print It, classes, Arrays, Dictionaries, Sets and nested loops. No external packages, accounts or services are used. This is a native Squeak lesson; the app has not been packaged for the SqueakJS playground.
Use a copy of your learning image. Download the kit, unzip it, and open Squeak’s File List. Select spatial-hash.st and choose fileIn. Then select spatial-hash-tests.st and file it in as well. File-in chunks with exclamation marks belong in File List, not Workspace.
The full model and Morph are installed first. Work through eight experiments below to understand and edit the core methods. Each view download is only a Workspace launcher, not a standalone class definition or a cumulative checkpoint. Before opening the next view, close the old lab Morph using its halo delete control. Alternatively keep the app reference and evaluate app delete in the same Workspace. Saving the learning image is optional and separate.
Download the complete lab and tests
Complete native source · SUnit tests · Run instructions
LSHLab open01 · Represent each circle with stable data
A collision query asks which objects overlap now. Checking every pair works, but ten objects already produce 45 pairs. This lesson builds a broad phase that proposes a smaller set, followed by a narrow phase that decides which proposed pairs truly touch. It is a geometric query, not a physics solver: there are no velocities, forces, bounce responses or continuous-time guarantees.
Each circle is a three-element Array: stable integer ID, center Point, and integer radius. The sample contains ten circles. IDs are labels, not Array positions; moving a circle changes its center, not its identity. The model is separate from LSHLab, which paints the results. Repainting the Morph does not change the circle data.
File in the complete source, then inspect the method below in System Browser → LSHGrid → instance side → tutorial. Accept it with Alt-S/Cmd-S if you are following along by editing. Every method shown in this lesson is already present in the downloaded source. These are guided experiments on one working application, not cumulative checkpoint files. Start each experiment from a new lab or use Reset.
Read or accept this complete method
addId: id center: point radius: radius
circles size >= 60 ifTrue: [self error: 'Laboratory limit: 60 circles'].
(id isInteger and: [id > 0]) ifFalse: [self error: 'ID must be a positive integer'].
(circles anySatisfy: [:c | c first = id]) ifTrue: [self error: 'Duplicate ID'].
((point isPoint and: [point x isInteger and: [point y isInteger]]) and: [radius isInteger and: [radius between: 1 and: 60]]) ifFalse: [self error: 'Use integer coordinates and radius 1 to 60'].
((point x between: -200 and: 400) and: [point y between: -200 and: 300]) ifFalse: [self error: 'Center outside laboratory bounds'].
circles add: {id. point. radius}. self rebuildOpen this experiment
| app |
app := LSHLab open.
app stage: 1.
app
Check it independently
LSHGrid sample circles sizeExpected: 10
02 · Turn positions into cell coordinates
A uniform grid divides space into equal square cells. A cell coordinate is not a screen pixel: divide each model coordinate by cell width, then round downward. With a width of 50, positions 0 through 49 belong to cell 0. Position 50 starts cell 1. The Point used as the Dictionary key keeps x and y together.
Negative coordinates are the trap. Floor maps -1 / 50 to -1, while truncating toward zero would map it to 0 and distort the partition. The sample intentionally puts circles left of zero. They still get ordinary negative grid keys. The drawing merely translates and scales model positions to fit the panel; never use those display offsets in the spatial index.
The formula uses exact Integer/Fraction arithmetic before floor. That avoids needing a floating-point tolerance at cell boundaries in this integer-coordinate teaching model. Try the independent Print It expression below: its answer is -1@-1. A cell boundary is a partition convention, not a physical wall.
Read or accept this complete method
cellFor: point
^ (point x / cellSize) floor @ (point y / cellSize) floorOpen this experiment
| app |
app := LSHLab open.
app stage: 2.
app
Check it independently
LSHGrid new cellFor: -1@ -1Expected: -1@-1
03 · Insert a circle into every touched cell
Indexing only the center fails when a large circle crosses a cell edge. Instead, enclose the circle in an axis-aligned square, calculate its lowest and highest cell coordinates, and insert the ID into every cell in that inclusive rectangle. A radius-60 circle can occupy many width-10 cells; the model does not assume radius is smaller than a cell.
The enclosing box is deliberately conservative. A corner of the box may not lie inside the circle, so this step can create extra candidates. It must not lose a real contact. Including the highest endpoint also includes the adjacent cell when a box ends exactly on a boundary. That may add work, but preserves touching contacts under our inclusive narrow-phase rule.
rebuild starts with a new Dictionary and uses at:ifAbsentPut: to make each bucket only when needed. Repeated IDs across different buckets are expected. Green squares in the native view are occupied cells, not collision regions. The buckets accessor returns fresh collections so inspection does not accidentally mutate the internal index.
Read or accept this complete method
keysFor: circle
| center radius low high keys |
center := circle second. radius := circle third.
low := self cellFor: center - (radius @ radius).
high := self cellFor: center + (radius @ radius).
keys := OrderedCollection new.
low x to: high x do: [:x | low y to: high y do: [:y | keys add: x @ y]].
^ keysrebuild
buckets := Dictionary new.
circles do: [:circle |
(self keysFor: circle) do: [:key |
(buckets at: key ifAbsentPut: [OrderedCollection new]) add: circle first]]Open this experiment
| app |
app := LSHLab open.
app stage: 3.
app
Check it independently
(LSHGrid sample keysFor: (LSHGrid sample circleAt: 1)) sizeExpected: 2
04 · Build one Set of candidate pairs
For every occupied bucket, form all pairs of different positions in its ID list. A pair may occur in several buckets because both circles occupy several cells. Canonicalize it to {smaller ID. larger ID}, then put that Array in a Set. Array equality compares its elements, so the second occurrence becomes the same logical pair rather than a second test.
The loop starts j at i + 1. This avoids self-pairs and reversed pairs within a bucket. Sorting the two IDs is still necessary because insertion order need not match ID order. The test suite inserts ID 9 before ID 2 and checks that the only pair is #(2 9). Keep the pair Arrays unchanged after adding them to the Set: mutating a hashed key breaks lookup assumptions.
At the sample width of 50, the grid proposes three unique pairs rather than all 45. The thin gray lines display those candidates. That count is a fact about this scene, not a guaranteed reduction for arbitrary input. Dictionary hash collisions are handled by the collection’s equality logic; they are different from geometric collisions between circles.
Read or accept this complete method
candidatePairs
| pairs |
pairs := Set new.
buckets valuesDo: [:ids |
1 to: ids size do: [:i | i + 1 to: ids size do: [:j |
| a b | a := ids at: i. b := ids at: j.
pairs add: {a min: b. a max: b}]]].
^ pairsOpen this experiment
| app |
app := LSHLab open.
app stage: 4.
app
Check it independently
LSHGrid sample candidatePairs sizeExpected: 3
05 · Test the actual circles, not their boxes
A shared cell does not prove two circles overlap. For each candidate, subtract the centers to obtain a displacement. Compare squared distance with the square of the summed radii. This avoids square roots and keeps the chosen integer geometry exact. The <= comparison means tangency counts as contact; use < instead only if you intentionally want strict overlap and update the tests.
collisionPairs filters the candidate Set using overlaps:with:. In the initial scene, three candidates become two contacts: IDs 1–2 and IDs 3–4. Orange circles participate in at least one contact. A circle may belong to several pairs; counting orange circles is therefore not the same as counting collisions.
The equation applies to circles, not arbitrary sprites. An enclosing circle around a spaceship can be a useful approximation, but this lesson makes no pixel-perfect claim. The independent example below places two radius-10 circles 21 units apart: their boxes may share cells, yet the exact circle test correctly returns no contacts.
Read or accept this complete method
overlaps: a with: b
| delta radius |
delta := a second - b second. radius := a third + b third.
^ ((delta x * delta x) + (delta y * delta y)) <= (radius * radius)collisionPairs
^ self candidatePairs select: [:pair |
self overlaps: (self circleAt: pair first) with: (self circleAt: pair second)]Open this experiment
| app |
app := LSHLab open.
app stage: 5.
app
Check it independently
| g |
g := LSHGrid new.
g addId: 1 center: 0@0 radius: 10.
g addId: 2 center: 21@0 radius: 10.
g collisionPairs isEmptyExpected: true
06 · Compare with an exhaustive oracle
An optimization needs a correctness reference. bruteForcePairs ignores the grid and tests every unordered pair with the same geometric predicate. Its role is to verify candidate generation and deduplication, not to independently prove the circle equation. Separate tangency, separation and coincident-center tests cover that equation’s basic behavior.
The native panel reports Oracle: MATCH only when the final pair Sets are equal, not merely when they have equal counts. Two wrong pairs could have the same count as two correct ones. Compare identities. In SUnit, 18 test methods cover empty/single scenes, negative coordinates, boundary cells, invalid inputs, duplicates, capacity, movement and dense worst cases. One test generates 30 reproducible integer scenes and compares exact pair Sets.
Run the tests yourself after filing in spatial-hash-tests.st. The captured run passed all 18, with zero failures and errors. The generated scenes are deterministic coverage, not a mathematical proof or a statistical performance benchmark. Keep the oracle available while changing the grid code; remove neither assertions nor hard cases just to make the optimization look faster.
Read or accept this complete method
bruteForcePairs
| pairs |
pairs := Set new.
1 to: circles size do: [:i | i + 1 to: circles size do: [:j |
| a b | a := circles at: i. b := circles at: j.
(self overlaps: a with: b) ifTrue: [pairs add: {a first min: b first. a first max: b first}]]].
^ pairsallPairCount
^ (circles size * (circles size - 1)) // 2Open this experiment
| app |
app := LSHLab open.
app stage: 6.
app
Check it independently
LSHGridTest suite runExpected: 18 passes, 0 failures, 0 errors
07 · Move an object and rebuild the index
An index describes a particular state. Moving a circle without updating its bucket membership leaves stale candidates behind and may miss new contacts. moveId:to: validates the new Point, changes the matching circle, and rebuilds the complete grid. For 60 or fewer objects this straightforward approach is easy to reason about.
The Move circle 5 button advances a bounded scripted path toward circles 3 and 4, then wraps back to its start. In the stage-seven experiment four presses move ID 5 to 158@51. The measured state has five candidates and three contacts. The animated demonstration below is a sequence of actual native renders after these scripted button actions, not a recording of a person dragging objects.
For larger scenes you could remove and reinsert only the moved object, but then you must clean empty buckets and avoid retaining stale memberships. That is an extension, not an implemented feature. Rebuilding also does not prevent tunneling: a fast-moving circle can pass through another between sampled frames. Continuous collision detection needs swept geometry or carefully chosen substeps.
Read or accept this complete method
moveId: id to: point
| circle |
((point isPoint and: [point x isInteger and: [point y isInteger]]) and: [(point x between: -200 and: 400) and: [point y between: -200 and: 300]]) ifFalse: [self error: 'Use bounded integer coordinates'].
circle := self circleAt: id. circle at: 2 put: point. self rebuildOpen this experiment
| app |
app := LSHLab open.
app stage: 7.
app moveSample; moveSample; moveSample; moveSample.
app
Check it independently
| g |
g := LSHGrid sample.
g moveId: 5 to: 158@51.
g collisionPairs = g bruteForcePairsExpected: true
08 · Measure the cell-size tradeoff
Smaller cells can reduce unrelated neighbors but make large circles occupy many buckets. Larger cells lower bucket overhead while putting more unrelated circles together. Press Grid 25 / 50 / 100 to cycle the three widths; the first press from 50 chooses 100. In the shown initial scene width 100 produces four candidates and the same two true contacts.
Broad-phase cost depends on total bucket memberships plus the sum of within-bucket pair work, followed by Set deduplication and narrow-phase checks. It is not unconditionally linear. If all objects overlap or occupy one cell, candidate count is n(n−1)/2. The 15-coincident-circle test deliberately produces all 105 pairs. Our circleAt: lookup is a linear search, so this teaching implementation also adds lookup cost; use an ID-to-circle Dictionary before claiming an optimized production implementation.
The public setters accept cell widths 10–100, radii 1–60, positive unique IDs, integer centers in x=-200..400 and y=-200..300, and at most 60 circles. These bounds limit accidental work; they are not a physical world model. The fixed view is composed for the sample and may clip custom coordinates near the model limits. The model calculations remain independent of what is visible. Next, benchmark your own data without changing the exact contact set.
Read or accept this complete method
cellSize: size
(size isInteger and: [size between: 10 and: 100]) ifFalse: [self error: 'Use an integer cell size from 10 to 100'].
cellSize := size. self rebuildOpen this experiment
| app |
app := LSHLab open.
app stage: 8.
app changeGrid.
app
Check it independently
| g expected |
g := LSHGrid sample.
expected := g collisionPairs.
g cellSize: 100.
g collisionPairs = expectedExpected: true
Watch the index follow a moving circle

The app does not run an autonomous timer. Each press performs one discrete movement and rebuild. Play demo here controls the recorded GIF, not a live Smalltalk interpreter. The local app’s Reset button restores the ten-circle sample, width 50 and view 1.
Keep correctness visible
The captured native run passed 18 SUnit tests with zero failures or errors. All displayed methods were recompiled in a fresh Squeak image and all eight launchers and Print It experiments were executed. The tests include 30 deterministic scenes, exact tangency, negative coordinates, large circles spanning many small cells, invalid inputs, stale-index prevention and a dense worst case.
This technique is useful for nearby-object queries and broad-phase collision detection. It is not automatically faster for every scene. Measure bucket memberships and candidate counts before optimizing, retain the brute-force oracle for small test cases, and document whether touching counts.
LSHGridTest suite runTwo extensions to try
- Add an ID-to-circle Dictionary and compare it with the current linear lookup. Keep every regression test passing.
- Instrument total bucket memberships and pair attempts before deduplication. Compare widths 10, 25, 50 and 100 on a clustered scene, not just a sparse one.
Connect the ideas
Review Dictionaries and Sets · Practice SUnit · Measure before optimizing · Compare a different spatial-grid problem
Primary implementation reference: inspect Dictionary, Set, Point and Integer in your installed Squeak System Browser. Official Squeak documentation provides the broader language and environment references.