Stateful Randomness in Shaders
I often find myself needing good random numbers in shaders, but this gets messy when you want to generate a bunch of different ones for each pixel. To get around this, I’m using a genuinely awful hack in DaeForth.
:m rand-given-seed (| seed |) [ seed seed 1141 * sin ] [ 12.9898 78.233 ] dot sin 43758.5453 * fract ; @float global =pixel-seed real-position /rand-given-seed \+ =pixel-seed :m seed .7 rand-given-seed ; :m gen-seed seed =>cur-seed cur-seed rand-given-seed =>next-seed [ next-seed ] &seed def-macro cur-seed ; :m next-random gen-seed pixel-seed * store rand-given-seed ;
Each time you call
next-random it generates a new, high-quality random number for the given pixel. Importantly, it does so with low overhead at runtime!
For instance, this generates two random colors and then mixes them randomly (for a total of 7...
Continue reading →