Task 4 of 6
The finished field already is a distance field — you just have to ask it. Every cell knows where its nearest seed is, so the distance to that seed is one subtraction and one square root away, in a single extra pass with no memory of its own.
This is where carrying the position rather than the distance pays off twice over. Had the cells accumulated distances, every pass would have compounded whatever rounding the last one introduced. Carrying coordinates means the distance is computed once, at the end, from two exact integers — so the field is as accurate as the seed assignment is, and no more approximate than that.
distance — unpack each cell's seed and return
the Euclidean distance from the cell to it.grid of packed idsMath.floor(id / n) then id − sy * nMath.sqrt(…) — this pass is where the square root belongsNothing new: it is the two lines you already wrote inside the loop, applied once.
const sy = Math.floor(id / this.constants.n);
const sx = id - sy * this.constants.n;return Math.sqrt((sx - x) * (sx - x) + (sy - y) * (sy - y));
A seed cell measures 0 from itself, which is exactly right — those are the black pinpricks in the rendered field.
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.