SketchImpact

← Back to Projects

Download the full project report (PDF)

SketchImpact is a 2D billiard game where players sketch their own freeform 32x32 sprites and watch them collide on a simulated table. Player-drawn shapes can be concave or disconnected, so the only fully accurate way to detect a collision is a pixel-perfect check between the two sprites' alpha masks - which is exact, but expensive to run on every candidate pair, every frame. The project's goal was to reduce how often that expensive check runs, without ever changing the simulation's outcome, by inserting a small learned filter between the cheap broad-phase check and the exact narrow-phase one.

SketchImpact sprite editor and billiard table

Built in Godot 4.7 with a PyTorch model exported to ONNX, as a two-week computer graphics course project with two teammates (Rene Sebastian, Shabaz Malik).

Implementation Details

Collision Pipeline

Every physics frame narrows the O(n²) set of possible sprite pairs down to the ones that actually need an exact check, in three stages: a quadtree broad phase collects candidate pairs from overlapping cells, an AABB check filters those down using each sprite's tight bounding box, and only the pairs that survive both reach the pixel-perfect narrow phase, which walks one sprite's opaque pixels and tests the corresponding sub-pixel offset against the other's mask. This baseline - with no skipping - is what the CNN filter later slots into, and what all later evaluation is measured against.

Dataset Generation

Training a classifier needs far more labelled (sprite_i, sprite_j, dx, dy, collided) tuples than a play session could produce, so the dataset is generated offline in Python, reimplementing the exact game rule as ground truth rather than approximating it. The sprite corpus combines 213 real sprites from an open dataset with 500 synthetic 32x32 masks (organic blobs, random convex polygons, primitives, thresholded noise). For each of 5,000 randomly chosen sprite pairs, offsets are restricted to the range where the two bounding boxes can overlap at all, then labelled at a target positive rate of 25%. The result is 2.46 million labelled samples stored in 6.6 MB by referencing each sprite's mask once rather than duplicating it per sample.

Model: A CoordConv CNN

A plain CNN has no inherent sense of position - its filters are shared and applied uniformly across the image, so it can see each sprite's local shape but not how the two sprites are placed relative to each other. Following Liu et al.'s CoordConv paper, the model's input adds four extra channels beyond the two alpha masks: the offset (dx, dy) broadcast as constants, and fixed x/y coordinate grids. This lets the network relate a pixel in one mask directly to the corresponding location in the other's frame, instead of having to infer offset arithmetic implicitly from data.

The full model is a three-block CNN with about 286K parameters:

class CollisionCNN(nn.Module):
    """
    CoordConv collision classifier.

    Input:  (B, 6, 32, 32)
              ch 0  alpha_i / 255
              ch 1  alpha_j / 255
              ch 2  dx / 32  (constant broadcast)
              ch 3  dy / 32  (constant broadcast)
              ch 4  x coordinate grid [0, 1]
              ch 5  y coordinate grid [0, 1]

    Output: (B,) raw logit - use BCEWithLogitsLoss, no sigmoid here.
    """

    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(6, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(inplace=True),

            nn.Conv2d(16, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2),                     # → (B, 32, 16, 16)

            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2),                     # → (B, 64, 8, 8)
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),                        # → (B, 4096)
            nn.Linear(64 * 8 * 8, 64),
            nn.ReLU(inplace=True),
            nn.Linear(64, 1),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.classifier(self.features(x)).squeeze(1)

Global average pooling was deliberately avoided in favour of flattening: a collision is a sparse, spatially local signal, and averaging the feature map across all positions would dilute a single corner-touch to near zero. Training used Adam (lr=1e-3, batch size 512) for 40 epochs on a free Colab instance (~2.5 hours), with random dihedral (D4) augmentation of both masks and the offset together - a collision's geometry is invariant under joint rotation/mirroring, which was verified empirically against the ground-truth rule over 2,000 trials before relying on it.

Training and validation loss curves

Integration into the Game

The model runs in a Python subprocess rather than through Godot's ONNX GDExtension, for ease of integration: the game speaks a small line-delimited JSON protocol over the subprocess's stdio pipe (register, clear, query, ping). After the AABB stage produces its candidate pairs each frame, the whole batch is sent to the model in one call; a pair flagged "maybe colliding" proceeds to the real pixel-perfect check, and a pair flagged "no" is skipped entirely. The decision threshold was not chosen for overall accuracy - it was read off the validation recall curve at the point closest to 99.9% recall, because a missed collision is a visible simulation bug while a missed skip only costs one extra pixel check.

The integration is designed to fail open: if the subprocess isn't available or stops responding, every pair is treated as "maybe", and the game degrades exactly to the pre-CNN baseline instead of silently dropping collisions. A runtime eval mode additionally runs the ground-truth check on every skipped pair anyway, tracking live false positives/negatives against the model's actual predictions during play.

Results

Offline, on a held-out validation split of 269,079 pairs, the operating threshold (chosen for 99.9% target recall) reached 99.91% actual recall at 33.25% precision, skipping 23.2% of checks:

Target recallThresholdActual recallPrecisionSkipped
99.9%-6.8800.99910.332523.2%
99.5%-4.7740.99520.441542.4%
99.0%-4.0710.99100.501249.5%
98.0%-3.3690.98250.577256.5%
95.0%-2.2460.95300.725866.5%
90.0%-1.2630.90700.850372.7%
Recall vs. fraction of pairs skipped

Low precision at the operating point is by design: the curve only breaks 50% precision once recall is allowed to drop to ~99%, confirming that near-perfect recall on this task means most flagged pairs turn out not to collide - an acceptable tradeoff since a false positive only costs one extra check, while a false negative is a visible bug.

Live, in a real play session (80 sprites, eval mode on), recall dropped to 98.86% at 27.0% precision, skipping 31.8% of checks - a real but modest gap from the offline number, caused by gameplay producing tightly packed, sprite-repeating pair distributions that differ from the uniform random sampling used to build the offline validation set:

In-game evaluation mode HUD

Outlook

The honest engineering conclusion is that a precomputed lookup table - built per sprite pair at spawn time via the same FFT cross-correlation already used to generate ground-truth labels, then reused via O(1) lookups every frame - would beat the CNN on every practical axis: exact instead of probabilistic, no training pipeline, no subprocess/IPC integration. The CNN's value here is demonstrating that collision geometry can be learned directly from raw masks, not a practical performance win over that alternative. Future work would prioritise closing the offline/live recall gap by training on pair distributions that better match actual gameplay (clustered positions, repeated sprites), and turning that lookup-table argument into an actual measurement to find the point (if any) at which sprite churn makes the CNN's fixed per-frame cost cheaper than amortising the table's one-time build.