Random 1D - Noise - Shader Learning

Noise

Random 1D

Task

In a shader program, implement the random function that generates a pseudo-random value in the range of [-1, 1] for a given input using a sine wave. Use the value 12.34 as the multiplier for the sine argument and 1234.5678 as the multiplier for the sine output.

Theory

Using the sin and fract functions to generate pseudo-random values in shaders is based on their mathematical properties, which allow for creating sufficiently chaotic and unpredictable results.


The sin Function


The sin function has several important properties that make it useful for generating pseudo-random numbers:


Sensitivity to Input Changes: The sin function is highly sensitive to changes in its input. Even small variations in the input can lead to significant changes in the output. This sensitivity is crucial for generating chaotic and unpredictable values. For example, if you slightly change the input value, the output of the sine function can vary dramatically, which helps in creating a more random-like distribution of values.


Periodicity: The sin function is periodic, meaning it repeats at regular intervals. This property can be used to create repeating but complex patterns.


The fract Function


The fract function helps limit the values returned by the sin function to the range from 0.0 to 1.0, which is convenient for use in shaders. Keep in mind that the result of fract is always positive:

if (x >= 0.0)
  return x - floor(x)
else
  return x - ceil(x)

Although fract limits the values, it does not destroy the randomness created by previous operations. This is because the fractional part of a number retains the chaotic and unpredictable nature embedded in the original value.


Multipliers


The large multiplier (e.g., 1234.5678) used after the sin function further amplifies the sensitivity to input changes. This large number ensures that even small differences in the input coordinates result in significantly different outputs after applying the sin function. This amplification is crucial for achieving a high degree of randomness.


Example


Let’s consider an example function that uses sin and fract to generate pseudo-random numbers:

float random(float x) {
    return fract(sin(x * 12.34) * 1234.5678);
}

Input Data: The value x, which can be pixel coordinates or any other values.

Multipliers: The constants 12.34 and 1234.5678 are chosen empirically to create more chaotic results.

The sin Function: Applied to the result of the multiplication to create a chaotic value.

The fract Function: Limits the result to the range from 0.0 to 1.0.