randommetal

How to get a random number in Metal shader?


How would I go about getting a random number in a Metal shader?

I searched for "random" in The Metal Shading Language Specification, but found nothing.


Solution

  • So I was working on a Random Number Generator for another project and was wanting to package it into a neat framework for a while.

    Your question pushed me to do just that. If you don't mind the shameless plug, here is a very simple framework that will generate a random number for you in a metal shader based on (up to) three seeds that you give it. The code is based on the following research paper that describes how to create random numbers on parallel processors for Monte Carlo simulations. It also has a (theoretical) period of 2^121 so it should be good for most reasonable calculations that can be done on a GPU.

    All you have to call in your shader is an intializer, then you call rand(), like so:

    // Initialize a random number generator, seeds 2 and 3 are optional
    Loki rng = Loki(seed1, seed2, seed3);
    
    // get a random float [0,1)
    float random_float = rng.rand();
    

    I also included a sample project in the repo so you can see how it is used.