# An O(N) implicit representation for the Koch Snowflake

This blog post was supposed to be about the [Menger Sponge](https://en.wikipedia.org/wiki/Menger_sponge).

I had come up with a clever strategy to use domain repetition – which is essentially free in implicit surfaces – to generate the fractal without an exponential blowup in element count. There were a bunch of cool pictures, and each one linked to an interactive demo in [Halfspace](https://www.mattkeeter.com/projects/halfspace).

Here's an example, so you know what you missed:

[![Picture of a sponge](https://www.mattkeeter.com/blog/2026-11-23-snowflake/sponge.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/sponge.html)

You can **click this image** (and indeed every image in this blog post) to load the model in Halfspace. I'd recommend doing so on a desktop; the Halfspace UI is un-suitable for phone screens and not optimized for touch interactions.

Anyways, the blog post was almost done, and I went to link to Inigo Quilez's [writeup on domain repetition](https://iquilezles.org/articles/sdfrepetition/). Down near the bottom of his writeup, he linked to another article titled ["menger fractal - 2011"](https://iquilezles.org/articles/menger/). As luck would have it, this was exactly the same trick that I was writing up, some 15 years earlier.

With the original post scooped, I took it upon myself to use the same tricks on a different fractal – one which I had _planned_ to leave as an exercise for the reader, because I didn't know how to do it!

* * *

That fractal is, of course, the seasonally-appropriate [Koch Snowflake](https://en.wikipedia.org/wiki/Koch_snowflake):

[![Picture of four snowflakes](https://www.mattkeeter.com/blog/2026-11-23-snowflake/snowstorm.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/snowstorm.html)

Let's spell out the rules of the game.

Our goal is to come up with a function which takes a position `(x, y)` and returns a signed value: negative for points inside the snowflake, and positive for points outside the snowflake.

The function should be **closed-form**: there should be no recursion, looping, or reliance on short-circuiting conditionals. The function can be built from a reasonable set of arithmetic operations: addition, subtraction, multiplication, modulo, minimum, maximum, etc.

We will assume that the function is being evaluated with common subexpression elimination, i.e. once you've computed a subexpression once, you can use it again for free elsewhere in the function.

(All of these conditions come from the design of the [Fidget implicit kernel](https://www.mattkeeter.com/projects/fidget))

Most importantly, the function should be **linear in complexity** with the number of levels in the snowflake. It's a CS 101 exercise to write a recursive fractal generator, where the function calls itself four times to produce the division into four line segments. Such an construction has `O(4^N)` complexity, which is (to use a technical term) Very Bad; our target is `O(N)`.

If this sounds like fun, I would strongly encourage you to try it yourself – it's a surprisingly interesting exercise! To get you started, here's a baseline implementation, which implements the Very Bad recursive strategy (click to edit it in Halfspace):

[![Picture of a snowflake built from many triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/bad_recursion.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/bad_recursion.html)

None of this is particularly well documented (the scripting language is [Rhai](https://rhai.rs/)!), but you should be able to poke around and figure out how things work; I have great faith in the intelligent and attractive readers of my blog.

* * *

### Hexagons are the bestagons

Not being sure where to start, I did notice one deficiency in the existing distance field: there are cracks between the triangles. The visualization shows inside/outside based on color: blue is inside, orange is outside, and the boundary ("isosurface") is shown in white. We are just sticking triangles together, so there are a bunch of zero-area cracks.

Butt joints are a common antipattern in modeling with distance fields: they have a distance value of zero, so it's ambiguous whether the crack should be treated as inside or outside the model. There are [strategies](https://www.mattkeeter.com/blog/2017-05-13-implicit-zeros/), but it's nicer to just not do that in the first place.

For our first fix, we'll instead note that we can replace pairs of little triangles with a single larger triangle:

[![Picture of a snowflake built with hexagonally-arranged triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/hexagons.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/hexagons.html)

Notice that each green and blue triangle has two ears poking out, and each one replaces two smaller triangles in the original model.

The core transform here is `hexify`, which scales and copies its input six times:

```rust
fn hexify(s) {
    union([
        s.remap(x * 3, -y * 3 + 2, z),
        s.remap(x * 3,  y * 3 + 2, z),
        s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),
        s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),
        s.remap(x * 3 - sqrt(3),  y * 3 - 1, z),
        s.remap(x * 3 + sqrt(3),  y * 3 - 1, z),
    ]) / 3
}
```

This eliminates the butt joints, although the distance field is far from perfect:

[![Picture of a snowflake distance field, with no zero-thickness cracks](https://www.mattkeeter.com/blog/2026-11-23-snowflake/nobutt.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/nobutt.html)

We've still got an obvious exponential complexity: each call to `hexify` multiples the element count by 6. What else can we do?

### Time for repetition

It's at this point that I made an interesting observation: if we include the center in the `hexify` transform, those triangles form a subset of an infinite tiling:

[![Picture of triangles repeating forever, which coincide with the level-two triangles in the snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/tiled.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/tiled.html)

The light blue level-2 triangles in our snowflake are a subset of an infinitely-repeating pattern of darker blue tiles. This is _great news_! Infinite repetitions are easy to construct using implicit surfaces using the modulo operator: in this case, we build the triangles from a repeating horizontal bar cutout:

```rust
let ycut = (((y + 0.5) % 1) - 0.5).abs() - 1/6.;
let cut = union(ycut, rotate(ycut, 120), rotate(ycut, 240));
```

[![Repeated cyan-magenta-yellow bars, with triangles in their negative space](https://www.mattkeeter.com/blog/2026-11-23-snowflake/cmyk.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/cmyk.html)

The triangles are in the negative space between bars.

Using modulo gives us an infinitely field of triangles in `O(1)` expression terms. We can then build our level-N triangles by simply scaling the triangle pattern:

[![More repeated triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/many.png)](https://www.mattkeeter.com/projects/halfspace/demo/#model=ZmxhaAEAAACxmDwA4CyMHR81-xTHCARLeFVW6qxqb_ZJTmR-4hqoDJ45JGfkc8KqTkR0tJLlu0mcZhrCRfCpw9IXSRa_X7v4P029FELWqJXU3sy-PU2IWvRFtVlIJELmGmI2pOkbNSUJXCFW3TbsIVwCcDH5AIIR-iDeZU1MGLyeC8MeojsgEyQA4m2A2Ambcp43nrwJDOhAQqBLjqBTMmFENvcChIiuBvREEzkR3BAH4J6RPoXQBL2HeS6U0RMF9Nc3nLDY5qotdSlz2CF_EYaeDv2QT-EosE_sZK0_pe4NHlPjRF8Kfetvns0XvFQb6lBaN4qdx6Uto7CZmEHQZsEcdjXmxUvCWZfOuHTWpZRLwC8Zq0_1cae_Dw15wfmg4U7YKXa8eAYQ2urFyXxiyq0-aBFdIHYCZWKRsW3aCrUrZUFYdX7RGYXQcX_e46RRNBX-mjaURN2tMR6kuHM6IiJbC0uuuHDAhSssOyoDo8jkGxfBzpMxaHvzwp1lWAQJQcAMiJ2YS6WMa3K3yePruMGWiQopPCreUGgJV_sh9GraooCv3BBHM2U0SkYFXRpSt9J2CazaOd5jHH_CIz6P07V1R_6vp0idvcfBg75P_6uMRJwgNrSlecVUNgOQxyMn1kU2Cmcztm6XS45mNBWMjWcCJPIe_AkFwd_a5IBWeRoptcqAEoxG0KQn9eiPx5yrrMfE7piu58YgN77QEG6LAkEznlu4GOEupC9yW55rVJWUzLKF2p7eQAXvdgPvE6k33RpNolRf_6YqY78qww2onFeRJy6UTJ6nC-k69iRQu2-BKHqARsrF6W9J_4WB2kf-s0IjOkCz0U6sZjN3nKVGVp9u9bitcGdiHM_qdLb1Dcq6Bnp7fJQUAWj2ZVP1kXMxYfNUgEkkVOBrz1DA9t52UX-NBW-Cp0LvoL5bFznSfsOhBDX2qgaFE2i-EQkCsZSWlp4R3uCQFl_EF2gkFyECmsV-CCBoq9yVoUMDIIujhO2oxfZBiaMc83dDOkZG_kECLHdxNM-56GQ9hODo3cIg)

Each level of the pattern is `O(1)`, so this meets our `O(N)` specification.

And voila! We have constructed our snowflake!

### Sweeping up the snowstorm

Unfortunately, we have also constructed a veritable Cantor duststorm of miscellaneous triangles, which is obvious in the black-and-white rendering:

[![A black-and-white image of the above, with many triangles outside the snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/dust.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/dust.html)

How can we preserve only the central snowflake?  
This is where things start to get _sneaky_.

Remember, each of these triangles is a **distance field**. We can dilate the distance field by subtracting an offset. Here's what that looks like on our original star, showing two offsets:

[![A six-pointed star with two offsets](https://www.mattkeeter.com/blog/2026-11-23-snowflake/dilated.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/dilated.html)

This suggests a strategy: at each level, construct a "safe zone" by offsetting the previous level, then clip the infinitely-repeating triangles against that zone. Here's an example showing the safe zone (in dark red) for the level-1 triangles:

[![A six-pointed star with an offset in darker red, mostly clipping the smaller green triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/clipped.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/clipped.html)

If you look carefully, you can see that this **almost works**: it exactly preserves the next-level green triangles in the snowflake. Unfortunately, the dilation also catches a fraction of next-level triangles elsewhere in the tiling.

Here's what it looks like after a few rounds of recursion:

[![Very nearly a correct snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/almost.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/almost.html)

It looks _interesting_, but not quite what we want!

The final fix relies on the distance field itself: we want the dilation of the field from triangle corners to be slower than from the sides. We can construct such a field by taking the intersection of the triangle with a high-gradient circle:

[![Triangles showing different fields](https://www.mattkeeter.com/blog/2026-11-23-snowflake/circle.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/circle.html)

The dilation of this shape doesn't hit the green triangles:

[![Triangle with dilation not hitting other triangles](https://www.mattkeeter.com/blog/2026-11-23-snowflake/good_dilation.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/good_dilation.html)

Using this as the basis for recursing, at last, our snowflake is correct!

[![A correct snowflake](https://www.mattkeeter.com/blog/2026-11-23-snowflake/final.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/final.html)

### Thinking with portals

This achieves our initial goal, but is still slightly unsatisfying: the underlying distance field is very wonky (technical term).

[![The distance field of the snowflake, which has widely varying gradients](https://www.mattkeeter.com/blog/2026-11-23-snowflake/wonky.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/wonky.html)

The inner field is correct, but the outer field has widely varying gradients (shown by the spacing between the lines).

After posting on social media, [Alexa Schor](https://alexaschor.com/) came up with an [elegant alternate design](https://bsky.app/profile/bsky.alexaschor.com/post/3n2i4u6nr4s2l) based on [Into the Portal: Directable Fractal Self-Similarity](https://alexaschor.com/into-the-portal/).

The core idea here (adapted from her design) is using **reflections**, which construct the union of a shape and its reflection without _fully copying the shape_. We can use reflections to revisit our earlier `hexify` function.

Remember, `hexify` is used to construct six copies of the model at different points in space:

```rust
fn hexify(s) {
    union([
        s.remap(x * 3, -y * 3 + 2, z),
        s.remap(x * 3,  y * 3 + 2, z),
        s.remap(x * 3 + sqrt(3), -y * 3 - 1, z),
        s.remap(x * 3 - sqrt(3), -y * 3 - 1, z),
        s.remap(x * 3 - sqrt(3),  y * 3 - 1, z),
        s.remap(x * 3 + sqrt(3),  y * 3 - 1, z),
    ]) / 3
}
```

We can instead write `hexify` in terms of a `fold` operation, which performs a combined reflection + union across a particular axis:

```
fn fold(x, y, angle) {
    let nx = -sin(angle);
    let ny =  cos(angle);
    let dist = x * nx + y * ny; // dot product
    let offset = max(dist, 0);
    [x - 2 * offset * nx, y - 2 * offset * ny]
}

fn hexify(shape) {
    let f0 = fold(x,         y,  120 * PI/180);
    let f1 = fold(f0[0], f0[1], -120 * PI/180);
    let f2 = fold(f1[0], f1[1],  120 * PI/180);
    shape.remap(x * 3, y * 3 - 2, z) // scale and transform
         .remap(f2[0], f2[1])        // six-fold reflection
         / 3                         // normalize distance field
}
```

The core thing to observe here is that we are only creating a single modified shape, instead of six transformed copies. Repeated applications of `hexify` are each `O(1)` in additional terms, thanks to common subexpression elimination.

With a little more tweaking, this produces the Best Possible Snowflake:

[![Picture of a snowflake with both black-and-white and distance field views.  The distance field is perfectly Euclidean](https://www.mattkeeter.com/blog/2026-11-23-snowflake/best.png)](https://www.mattkeeter.com/blog/2026-11-23-snowflake/models/best.html)

Please admire the fact that the field is an [Exact SDF](https://bsky.app/profile/mattkeeter.com/post/3loqglbjuak2n): it has the same gradient everywhere, and that gradient always points directly to the nearest point on the surface, both inside and outside the shape. What a lovely construction; thank you to Alexa for the suggestion!

* * *

That's all I've got for now; as always, feel free to [say hi](https://www.mattkeeter.com/about#contact) if you've got your own improvements on the design!