Uniforms - Built-in functions - Shader Learning

Built-in functions

Uniforms

Task

Use the iResolution uniform to color only the left half of the screen in red.

Theory

Uniforms are like shared settings that your program sends from the CPU to the GPU. Every shader (the code that colors and draws things on screen) gets the same values, like screen size or time, and can read them, but can’t change them.


You can think of uniforms as global settings that help the shader know what to do. Instead of changing the shader code itself, you just change the input data (the uniforms), and the shader behaves differently. This makes it easy to reuse the same shader for different effects.


GLSL


In GLSL, you declare a uniform like this:

uniform vec2 iResolution; // screen width and height

• uniform tells the shader that this value comes from outside (from CPU).

• iResolution is the name of the variable. You can use it inside your shader to access the value.


HLSL


In HLSL, uniforms are grouped into a cbuffer (constant buffer):

cbuffer Uniforms : register(b0) {
    float2 iResolution; // screen width and height
}

• cbuffer is a block of read-only data sent from the CPU to the GPU.

• Uniforms is the name of the buffer. You can name it anything, but it should be descriptive.

• register(b0) binds this buffer to slot b0 in the GPU’s constant buffer register space. The b register space is reserved for constant buffers. If you declare multiple cbuffer-s, make sure their register bindings (b0, b1, etc.) don't overlap unless intentional.


When you declare a cbuffer, the variables inside it become globally accessible in your shader code. That means you don’t need to prefix them with the buffer name.

float width = iResolution.x;

You don’t need to write Uniforms.iResolution.x - just iResolution.x is enough. The shader automatically knows that iResolution comes from the Uniforms buffer.