and Hash Playground
I'm the sort of person who gets very excited when simple rules create complex behaviour. The other day, I needed a simple hash function that maps
TL;DR: The boolean predicate
For example, varying
For the rest of this post, we'll try to unpick the function. If you'd prefer to play with it yourself, check out the hash playground.
I was trying to make a game that obeyed a 2-bit colour palette. With a strict interpretation of the rules, this means no interpolation or antialiasing — the pixels onscreen should only be one of 4 colours. So I needed textures that could align perfectly to the screen. The not-at-all novel solution:
Hash the (x, y) screen-space pixel coordinate, and use it to choose a colour.
It turns out that this works fine, as long as the camera and viewports are fixed, and this very simple hash function is remarkably varied and interesting:
In Python, for example:
c_x, c_y, c_xy, c_xx, c_yy = 1, 1, 0, 1, 1
m, t, w, h = 64, 0.5, 128, 128
x = np.arange(w)[:, None]
y = np.arange(h)[None, :]
h = (c_x*x + c_y*y + c_xy*x*y + c_xx*x**2 + c_yy*y**2) % m < t*m
display(PIL.Image.fromarray(h))
Let's try to build up the maths to understand some of the structure behind these patterns. We'll call the expression between
What if our body is just
How about
I.e. the pattern seems to repeat after
Since the
To understand the pattern itself, it's like an extreme aliasing effect. Scanning left to right, first you follow a quadratic: black then blue. Then you skip over the
Going 2D,
Increasing the frequency,
Cross terms,
That's all I've got for understanding; I'm sure there's much more that could be said from the maths of modular arithmetic, which is mostly beyond me.
Here are some personal favourites after some idle tinkering. Note the similarity in the first two equations, which produce very different patterns.
It's particularly fun to sweep the threshold
I hope you enjoyed staring at the complexities of a simple function for a few minutes! If you haven't already, try the hash playground. Maybe you can generate a new texture for your game or print a case for a mobile phone (my next step).
See if you can spot some of these hash textures in the clip from my game-jam game below. And if you consider yourself part of the extremely limited target audience (who want to learn an assembly-like language just to play a short web game), perhaps check it out: C-crits.
Happy Hashing!