Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Lenguaje de shading

Introducción

Godot utiliza un lenguaje de shading similar a GLSL ES 3.0. La mayoría de los tipos de datos y funciones están soportados y los pocos que no figuran serán agregados posteriormente.

Si ya estás familiarizado con GLSL, la Guía de migración de shaders de Godot es un recurso que te ayudará a hacer la transición desde GLSL regular al lenguaje de sombreado de Godot.

Tipos de datos

La mayoría de los tipos de datos de GLSL ES 3.0 están soportados:

Tipo

Descripción

void

Tipo de dato nulo, útil sólo para funciones que no retornan nada.

bool

Tipo de dato booleano, puede contener solamente true o false.

bvec2

Vector de dos componentes booleanas.

bvec3

Vector de tres componentes booleanas.

bvec4

Vector de cuatro componentes booleanas.

int

Escalar entero con signo.

ivec2

Vector de dos componentes de entero con signo.

ivec3

Vector de tres componentes de enteros con signo.

ivec4

Vector de cuatro componentes de enteros con signo.

uint

Escalar entero sin signo, no puede contener números negativos.

uvec2

Vector de dos componentes de enteros sin signo.

uvec3

Vector de tres componentes de enteros sin signo.

uvec4

Vector de cuatro componentes de enteros sin signo.

float

Escalar de punto flotante.

vec2

Vector de dos componentes de valores de punto flotante.

vec3

Vector de tres componentes de valores de punto flotante.

vec4

Vector de cuatro componentes de valores de punto flotante.

mat2

Matrix 2x2, ordenada por columna.

mat3

Matriz 3x3, ordenada por columnas (column-major order).

mat4

Matriz 4x4, ordenada por columnas (column-major order).

sampler2D

Tipo Sampler para vincular texturas 2D, las cuales son leídas como float.

isampler2D

Tipo Sampler para vincular texturas 2D, las cuales son leídas como enteros con signo.

usampler2D

Tipo Sampler para vincular texturas 2D, las cuales son leídas como enteros sin signo.

sampler2DArray

Tipo Sampler para vincular arrays de texturas 2D, las cuales son leídas como float.

isampler2DArray

Tipo Sampler para vincular arrays de texturas 2D, las cuales son leídas como enteros con signo.

usampler2DArray

Tipo Sampler para vincular arrays de texturas 2D, las cuales son leídas como enteros sin signo.

sampler3D

Tipo Sampler para vincular texturas 3D, las cuales son leídas como float.

isampler3D

Tipo Sampler para vincular texturas 3D, las cuales son leídas como enteros con signo.

usampler3D

Tipo Sampler para vincular texturas 3D, las cuales son leídas como enteros sin signo.

samplerCube

Sampler type for binding Cubemaps, which are read as float.

samplerCubeArray

Sampler type for binding Cubemap arrays, which are read as float.

Casting

Como en GLSL ES 3.0, el casting implícito entre escalares y vectores del mismo tamaño pero distinto tipo no está permitido. Casting de tipos de distinto tamaño tampoco está permitido. La conversión debe ser explícita mediante el uso de constructores.

Ejemplo:

float a = 2; // invalid
float a = 2.0; // valid
float a = float(2); // valid

Las constantes enteras son con signo, siempre se necesitará casting para convertirlas a enteros sin signo:

int a = 2; // valid
uint a = 2; // invalid
uint a = uint(2); // valid

Miembros

Escalares individuales miembros de tipos vectores se acceden mediante los miembros "x", "y", "z" y "w". Alternativamente, "r", "g", "b" y "a" también funciona y es equivalente. Usa la que se ajuste mejor al caso.

Para las matrices, utiliza la sintaxis de indexación m[columna][fila] para acceder a cada escalar o m[idx] para acceder a un vector por índice de fila. Por ejemplo, para acceder a la posición y de un objeto en una mat4, se utiliza m[3][1].

Construcción

La construcción de tipos vector deberá pasar siempre:

// The required amount of scalars
vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
// Complementary vectors and/or scalars
vec4 a = vec4(vec2(0.0, 1.0), vec2(2.0, 3.0));
vec4 a = vec4(vec3(0.0, 1.0, 2.0), 3.0);
// A single scalar for the whole vector
vec4 a = vec4(0.0);

La construcción de tipos matriz requiere pasar vectores de la misma dimensión de la matriz. Puedes también construir una matriz diagonal usando la sintaxis matx(float). De este modo, mat4(1.0) es una matriz identidad.

mat2 m2 = mat2(vec2(1.0, 0.0), vec2(0.0, 1.0));
mat3 m3 = mat3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
mat4 identity = mat4(1.0);

Matrices can also be built from a matrix of another dimension. There are two rules:

1. If a larger matrix is constructed from a smaller matrix, the additional rows and columns are set to the values they would have in an identity matrix. 2. If a smaller matrix is constructed from a larger matrix, the top, left submatrix of the larger matrix is used.

mat3 basis = mat3(MODEL_MATRIX);
mat4 m4 = mat4(basis);
mat2 m2 = mat2(m4);

Swizzling

Es posible obtener cualquier combinación de ellos en cualquier orden, siempre que el resultado sea igual a otro tipo vector (o escalar). Es más fácil mostrarlo que explicarlo:

vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
vec3 b = a.rgb; // Creates a vec3 with vec4 components.
vec3 b = a.ggg; // Also valid; creates a vec3 and fills it with a single vec4 component.
vec3 b = a.bgr; // "b" will be vec3(2.0, 1.0, 0.0).
vec3 b = a.xyz; // Also rgba, xyzw are equivalent.
vec3 b = a.stp; // And stpq (for texture coordinates).
float c = b.w; // Invalid, because "w" is not present in vec3 b.
vec3 c = b.xrt; // Invalid, mixing different styles is forbidden.
b.rrr = a.rgb; // Invalid, assignment with duplication.
b.bgr = a.rgb; // Valid assignment. "b"'s "blue" component will be "a"'s "red" and vice versa.

Precisión

Es posible agregar modificadores de precisión a los tipos de datos, se pueden usar para uniforms, variables, argumentos y varyings:

lowp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // low precision, usually 8 bits per component mapped to 0-1
mediump vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // medium precision, usually 16 bits or half float
highp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // high precision, uses full float or integer range (default)

El uso de baja precisión para algunas operaciones puede acelerar la matemática involucrada (al costo de, por supuesto, baja precisión). Esto es raramente necesitado en vertex shaders (donde precisión máxima es necesitada la mayor parte del tiempo), pero normalmente se necesita en los fragment.

Algunas arquitecturas (principalmente móviles) pueden beneficiarse significativamente de esto, pero existen desventajas como la sobrecarga adicional de conversión entre precisiones. Consulte la documentación de la arquitectura de destino para obtener más información. En muchos casos, los controladores móviles provocan un comportamiento incoherente o inesperado y es mejor evitar especificar la precisión a menos que sea necesario.

Arrays

Arrays are containers for multiple variables of a similar type.

Arrays locales

Los arrays locales se declaran en funciones. Pueden utilizar todos los tipos de datos permitidos, excepto los samplers. La declaración de los arrays sigue una sintaxis de tipo C: [const] + [precision] + typename + identifier + [array size].

void fragment() {
    float arr[3];
}

Pueden ser inicializados al principio como:

float float_arr[3] = float[3] (1.0, 0.5, 0.0); // first constructor

int int_arr[3] = int[] (2, 1, 0); // second constructor

vec2 vec2_arr[3] = { vec2(1.0, 1.0), vec2(0.5, 0.5), vec2(0.0, 0.0) }; // third constructor

bool bool_arr[] = { true, true, false }; // fourth constructor - size is defined automatically from the element count

Puedes declarar múltiples arrays (incluso con diferentes tamaños) en una expresión:

float a[3] = float[3] (1.0, 0.5, 0.0),
b[2] = { 1.0, 0.5 },
c[] = { 0.7 },
d = 0.0,
e[5];

Para acceder a un elemento del array, utiliza la sintaxis de indexación:

float arr[3];

arr[0] = 1.0; // setter

COLOR.r = arr[0]; // getter

Los arrays también tienen una función integrada .length() (que no debe confundirse con la función integrada length()). No acepta ningún parámetro y devolverá el tamaño del array.

float arr[] = { 0.0, 1.0, 0.5, -1.0 };
for (int i = 0; i < arr.length(); i++) {
    // ...
}

Nota

If you use an index either below 0 or greater than array size - the shader will crash and break rendering. To prevent this, use length(), if, or clamp() functions to ensure the index is between 0 and the array's length. Always carefully test and check your code. If you pass a constant expression or a number, the editor will check its bounds to prevent this crash.

Global arrays

You can declare arrays at global space like:

shader_type spatial;

const lowp vec3 v[1] = lowp vec3[1] ( vec3(0, 0, 1) );

void fragment() {
  ALBEDO = v[0];
}

Nota

Global arrays have to be declared as global constants, otherwise they can be declared the same as local arrays.

Constantes

Use la palabra clave const antes de la declaración de la variable para hacerla inmutable, lo que significa que no puede ser modificada. Todos los tipos básicos, excepto las samplers pueden ser declarados como constantes. Acceder y utilizar un valor constante es ligeramente más rápido que utilizar un uniforme. Las constantes deben ser inicializadas en su declaración.

const vec2 a = vec2(0.0, 1.0);
vec2 b;

a = b; // invalid
b = a; // valid

Las constantes no pueden ser modificadas y además no pueden tener indicios, pero varias de ellas (si tienen el mismo tipo) pueden ser declaradas en una sola expresión, por ejemplo

const vec2 V1 = vec2(1, 1), V2 = vec2(2, 2);

Al igual que las variables, los arrays también pueden ser declarados con const.

const float arr[] = { 1.0, 0.5, 0.0 };

arr[0] = 1.0; // invalid

COLOR.r = arr[0]; // valid

Las constantes pueden ser declaradas tanto globalmente (fuera de cualquier función) como localmente (dentro de una función). Las constantes globales son útiles cuando se quiere tener acceso a un valor en todo el shader que no necesita ser modificado. Al igual que los uniformes, las constantes globales se comparten entre todas las etapas del shader, pero no son accesibles fuera del shader.

shader_type spatial;

const float PI = 3.14159265358979323846;

Constants of the float type must be initialized using . notation after the decimal part or by using the scientific notation. The optional f post-suffix is also supported.

float a = 1.0;
float b = 1.0f; // same, using suffix for clarity
float c = 1e-1; // gives 0.1 by using the scientific notation

Constants of the uint (unsigned int) type must have a u suffix to differentiate them from signed integers. Alternatively, this can be done by using the uint(x) built-in conversion function.

uint a = 1u;
uint b = uint(1);

Structs

Structs are compound types which can be used for better abstraction of shader code. You can declare them at the global scope like:

struct PointLight {
    vec3 position;
    vec3 color;
    float intensity;
};

After declaration, you can instantiate and initialize them like:

void fragment()
{
    PointLight light;
    light.position = vec3(0.0);
    light.color = vec3(1.0, 0.0, 0.0);
    light.intensity = 0.5;
}

Or use struct constructor for same purpose:

PointLight light = PointLight(vec3(0.0), vec3(1.0, 0.0, 0.0), 0.5);

Structs may contain other struct or array, you can also instance them as global constant:

shader_type spatial;

...

struct Scene {
    PointLight lights[2];
};

const Scene scene = Scene(PointLight[2](PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0)));

void fragment()
{
    ALBEDO = scene.lights[0].color;
}

You can also pass them to functions:

shader_type canvas_item;

...

Scene construct_scene(PointLight light1, PointLight light2) {
    return Scene({light1, light2});
}

void fragment()
{
    COLOR.rgb = construct_scene(PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 1.0), 1.0)).lights[0].color;
}

Operadores

El lenguaje de shading de Godot soporta el mismo conjunto de operadores de GLSL ES 3.0. Debajo está la lista de ellos en orden de precedencia:

Precedencia

Clase

Operador

1 (más alta)

agrupamiento entre paréntesis

()

2

unario

+, -, !, ~

3

multiplicativo

/, *, %

4

aditivo

+, -

5

Desplazamiento bit-wise

<<, >>

6

relacional

<, >, <=, >=

7

igualdad

==, !=

8

AND bit-wise

&

9

OR bit-wise excluyente

^

10

OR bit-wise inclusivo

|

11

AND lógico

&&

12 (la más baja)

OR lógico inclusivo

||

Control de Flujo

El lenguaje de shading de Godot soporta los tipos más comunes de control de flujo:

// `if` and `else`.
if (cond) {

} else {

}

// Ternary operator.
// This is an expression that behaves like `if`/`else` and returns the value.
// If `cond` evaluates to `true`, `result` will be `9`.
// Otherwise, `result` will be `5`.
int result = cond ? 9 : 5;

// `switch`.
switch (i) { // `i` should be a signed integer expression.
    case -1:
        break;
    case 0:
        return; // `break` or `return` to avoid running the next `case`.
    case 1: // Fallthrough (no `break` or `return`): will run the next `case`.
    case 2:
        break;
    //...
    default: // Only run if no `case` above matches. Optional.
        break;
}

// `for` loop. Best used when the number of elements to iterate on
// is known in advance.
for (int i = 0; i < 10; i++) {

}

// `while` loop. Best used when the number of elements to iterate on
// is not known in advance.
while (cond) {

}

// `do while`. Like `while`, but always runs at least once even if `cond`
// never evaluates to `true`.
do {

} while (cond);

Keep in mind that in modern GPUs, an infinite loop can exist and can freeze your application (including editor). Godot can't protect you from this, so be careful not to make this mistake!

Also, when comparing floating-point values against a number, make sure to compare them against a range instead of an exact number.

A comparison like if (value == 0.3) may not evaluate to true. Floating-point math is often approximate and can defy expectations. It can also behave differently depending on the hardware.

No hagas esto.

float value = 0.1 + 0.2;

// May not evaluate to `true`!
if (value == 0.3) {
    // ...
}

Instead, always perform a range comparison with an epsilon value. The larger the floating-point number (and the less precise the floating-point number), the larger the epsilon value should be.

const float EPSILON = 0.0001;
if (value >= 0.3 - EPSILON && value <= 0.3 + EPSILON) {
    // ...
}

See floating-point-gui.de for more information.

Descartando

Fragment and light functions can use the discard keyword. If used, the fragment is discarded and nothing is written.

Beware that discard has a performance cost when used, as it will prevent the depth prepass from being effective on any surfaces using the shader. Also, a discarded pixel still needs to be rendered in the vertex shader, which means a shader that uses discard on all of its pixels is still more expensive to render compared to not rendering any object in the first place.

Funciones

Es posible definir cualquier función en un shader de Godot. Estas llevan la siguiente sintaxis:

ret_type func_name(args) {
    return ret_type; // if returning a value
}

// a more specific example:

int sum2(int a, int b) {
    return a + b;
}

You can only use functions that have been defined above (higher in the editor) the function from which you are calling them. Redefining a function that has already been defined above (or is a built-in function name) will cause an error.

Los argumentos de las funciones pueden tener calificadores especiales:

  • in: Significa que el argumento es sólo para lectura (por defecto).

  • out: Significa que el argumento es sólo para escritura.

  • inout: Significa que el argumento es pasado por referencia.

  • const: Means the argument is a constant and cannot be changed, may be combined with in qualifier.

Ejemplo:

void sum2(int a, int b, inout int result) {
    result = a + b;
}

Nota

Unlike GLSL, Godot's shader language does not support function overloading. This means that a function cannot be defined several times with different argument types or numbers of arguments. As a workaround, use different names for functions that accept a different number of arguments or arguments of different types.

Varyings

Para enviar datos desde el procesador de vértices al procesador de fragmentos (o luz), se utilizan varyings. Se establecen para cada vértice primitivo en el procesador de vértices, y el valor se interpola para cada píxel en el procesador de fragmentos.

shader_type spatial;

varying vec3 some_color;

void vertex() {
    some_color = NORMAL; // Make the normal the color.
}

void fragment() {
    ALBEDO = some_color;
}

void light() {
    DIFFUSE_LIGHT = some_color * 100; // optionally
}

La variación también puede ser un array:

shader_type spatial;

varying float var_arr[3];

void vertex() {
    var_arr[0] = 1.0;
    var_arr[1] = 0.0;
}

void fragment() {
    ALBEDO = vec3(var_arr[0], var_arr[1], var_arr[2]); // red color
}

También es posible enviar datos desde el procesador de fragmentos al procesador de luz utilizando la palabra clave varying. Para hacerlo, puedes asignar un valor a una variable varying en el procesador de fragmentos y luego utilizarla en la función de luz.

shader_type spatial;

varying vec3 some_light;

void fragment() {
    some_light = ALBEDO * 100.0; // Make a shining light.
}

void light() {
    DIFFUSE_LIGHT = some_light;
}

Ten en cuenta que las variables varying no se pueden asignar en funciones personalizadas o en la función del procesador de luz, como:

shader_type spatial;

varying float test;

void foo() {
    test = 0.0; // Error.
}

void vertex() {
    test = 0.0;
}

void light() {
    test = 0.0; // Error too.
}

Esta limitación se introdujo para evitar un uso incorrecto antes de la inicialización.

Calificadores de interpolación

Ciertos valores son interpolados durante el shading pipeline. Puedes modificar cómo se harán esas interpolaciones usando calificadores de interpolación.

shader_type spatial;

varying flat vec3 our_color;

void vertex() {
    our_color = COLOR.rgb;
}

void fragment() {
    ALBEDO = our_color;
}

Estos son los dos posibles calificadores de interpolación:

Calificador

Descripción

flat

El valor no es interpolado.

smooth

El valor es interpolado en una manera corregida por perspectiva. Es el modo por defecto.

Uniforms

Es posible pasar valores a shaders. Son globales para todo el shader y se llaman uniforms. Cuando un shader es asignado a un material, los uniforms aparecerán editables como parámetros. Los uniforms no pueden ser escritos desde dentro de un shader.

shader_type spatial;

uniform float some_value;

uniform vec3 colors[3];

Puedes poner los uniformes en el editor en el material. O puedes fijarlos a través de GDScript:

material.set_shader_parameter("some_value", some_value)

material.set_shader_parameter("colors", [Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1)])

Nota

The first argument to set_shader_parameter is the name of the uniform in the shader. It must match exactly to the name of the uniform in the shader or else it will not be recognized.

Cualquier tipo de GLSL, excepto void, puede ser un uniforme. Además, Godot proporciona sugerencias opcionales para el shader (pistas) para que el compilador comprenda para qué se utiliza el uniforme y cómo el editor debe permitir a los usuarios modificarlo.

shader_type spatial;

uniform vec4 color : source_color;
uniform float amount : hint_range(0, 1);
uniform vec4 other_color : source_color = vec4(1.0); // Default values go after the hint.
uniform sampler2D image : source_color;

It's important to understand that textures that are supplied as color require hints for proper sRGB -> linear conversion (i.e. source_color), as Godot's 3D engine renders in linear color space. If this is not done, the texture will appear washed out.

Nota

The 2D renderer also renders in linear color space if the Rendering > Viewport > HDR 2D project setting is enabled, so source_color must also be used in canvas_item shaders. If 2D HDR is disabled, source_color will keep working correctly in canvas_item shaders, so it's recommend to use it either way.

A continuación está la lista completa de hints:

Tipo

Hint

Descripción

vec3, vec4

source_color

Utilizado como color.

int, float

hint_range(min, max[, step])

Restringido a valores en un rango (con min/max/step).

sampler2D

source_color

Used as albedo color.

sampler2D

hint_normal

Utilizado como normalmap.

sampler2D

hint_default_white

As value or albedo color, default to opaque white.

sampler2D

hint_default_black

As value or albedo color, default to opaque black.

sampler2D

hint_default_transparent

As value or albedo color, default to transparent black.

sampler2D

hint_anisotropy

Como flowmap, hacia la derecha por defecto.

sampler2D

hint_roughness[_r, _g, _b, _a, _normal, _gray]

Used for roughness limiter on import (attempts reducing specular aliasing). _normal is a normal map that guides the roughness limiter, with roughness increasing in areas that have high-frequency detail.

sampler2D

filter[_nearest, _linear][_mipmap][_anisotropic]

Enabled specified texture filtering.

sampler2D

repeat[_enable, _disable]

Enabled texture repeating.

sampler2D

hint_screen_texture

Texture is the screen texture.

sampler2D

hint_depth_texture

Texture is the depth texture.

sampler2D

hint_normal_roughness_texture

Texture is the normal roughness texture (only supported in Forward+).

GDScript usa tipos de variables diferentes a los que usa el GLSL, así que al pasar las variables de GDScript a los shaders, Godot convierte el tipo automáticamente. A continuación se muestra una tabla de los tipos correspondientes:

Tipo GLSL

Tipo GDScript

Notas

bool

bool

bvec2

int

Bitwise packed int where bit 0 (LSB) corresponds to x.

For example, a bvec2 of (bx, by) could be created in the following way:

bvec2_input: int = (int(bx)) | (int(by) << 1)

bvec3

int

Bitwise packed int where bit 0 (LSB) corresponds to x.

bvec4

int

Bitwise packed int where bit 0 (LSB) corresponds to x.

int

int

ivec2

Vector2i

ivec3

Vector3i

ivec4

Vector4i

uint

int

uvec2

Vector2i

uvec3

Vector3i

uvec4

Vector4i

float

float

vec2

Vector2

vec3

Vector3, Color

When Color is used, it will be interpreted as (r, g, b).

vec4

Vector4, Color, Rect2, Plane, Quaternion

When Color is used, it will be interpreted as (r, g, b, a).

When Rect2 is used, it will be interpreted as (position.x, position.y, size.x, size.y).

When Plane is used it will be interpreted as (normal.x, normal.y, normal.z, d).

mat2

Transform2D

mat3

Basis

mat4 mat4

Projection, Transform3D

When a Transform3D is used, the w Vector is set to the identity.

sampler2D

Texture2D

isampler2D

Texture2D

usampler2D

Texture2D

sampler2DArray

Texture2DArray

isampler2DArray

Texture2DArray

usampler2DArray

Texture2DArray

sampler3D

Texture3D

isampler3D

Texture3D

usampler3D

Texture3D

samplerCube

Cubemap

samplerCubeArray

CubemapArray

Nota

Tengan cuidado al establecer los uniformes shader de GDScript, no se arrojará ningún error si el tipo no coincide. Su shader sólo mostrará un comportamiento indefinido.

A los uniforms se les pueden asignar valores por defecto:

shader_type spatial;

uniform vec4 some_vector = vec4(0.0);
uniform vec4 some_color : source_color = vec4(1.0);

Note that when adding a default value and a hint, the default value goes after the hint.

If you need to make multiple uniforms to be grouped in the specific category of an inspector, you can use a group_uniform keyword like:

group_uniforms MyGroup;
uniform sampler2D test;

You can close the group by using:

group_uniforms;

The syntax also supports subgroups (it's not mandatory to declare the base group before this):

group_uniforms MyGroup.MySubgroup;

Global uniforms

Sometimes, you want to modify a parameter in many different shaders at once. With a regular uniform, this takes a lot of work as all these shaders need to be tracked and the uniform needs to be set for each of them. Global uniforms allow you to create and update uniforms that will be available in all shaders, in every shader type (canvas_item, spatial, particles, sky and fog).

Global uniforms are especially useful for environmental effects that affect many objects in a scene, like having foliage bend when the player is nearby, or having objects move with the wind.

To create a global uniform, open the Project Settings then go to the Shader Globals tab. Specify a name for the uniform (case-sensitive) and a type, then click Add in the top-right corner of the dialog. You can then edit the value assigned to the uniform by clicking the value in the list of uniforms:

Adding a global uniform in the Shader Globals tab of the Project Settings

Adding a global uniform in the Shader Globals tab of the Project Settings

After creating a global uniform, you can use it in a shader as follows:

shader_type canvas_item;

global uniform vec4 my_color;

void fragment() {
    COLOR = my_color.rgb;
}

Note that the global uniform must exist in the Project Settings at the time the shader is saved, or compilation will fail. While you can assign a default value using global uniform vec4 my_color = ... in the shader code, it will be ignored as the global uniform must always be defined in the Project Settings anyway.

To change the value of a global uniform at run-time, use the RenderingServer.global_shader_parameter_set method in a script:

RenderingServer.global_shader_parameter_set("my_color", Color(0.3, 0.6, 1.0))

Assigning global uniform values can be done as many times as desired without impacting performance, as setting data doesn't require synchronization between the CPU and GPU.

You can also add or remove global uniforms at run-time:

RenderingServer.global_shader_parameter_add("my_color", RenderingServer.GLOBAL_VAR_TYPE_COLOR, Color(0.3, 0.6, 1.0))
RenderingServer.global_shader_parameter_remove("my_color")

Adding or removing global uniforms at run-time has a performance cost, although it's not as pronounced compared to getting global uniform values from a script (see the warning below).

Advertencia

While you can query the value of a global uniform at run-time in a script using RenderingServer.global_shader_parameter_get("uniform_name"), this has a large performance penalty as the rendering thread needs to synchronize with the calling thread.

Therefore, it's not recommended to read global shader uniform values continuously in a script. If you need to read values in a script after setting them, consider creating an autoload where you store the values you need to query at the same time you're setting them as global uniforms.

Per-instance uniforms

Nota

Per-instance uniforms are only available in spatial (3D) shaders.

Sometimes, you want to modify a parameter on each node using the material. As an example, in a forest full of trees, when you want each tree to have a slightly different color that is editable by hand. Without per-instance uniforms, this requires creating a unique material for each tree (each with a slightly different hue). This makes material management more complex, and also has a performance overhead due to the scene requiring more unique material instances. Vertex colors could also be used here, but they'd require creating unique copies of the mesh for each different color, which also has a performance overhead.

Per-instance uniforms are set on each GeometryInstance3D, rather than on each Material instance. Take this into account when working with meshes that have multiple materials assigned to them, or MultiMesh setups.

shader_type spatial;

// Provide a hint to edit as a color. Optionally, a default value can be provided.
// If no default value is provided, the type's default is used (e.g. opaque black for colors).
instance uniform vec4 my_color : source_color = vec4(1.0, 0.5, 0.0, 1.0);

void fragment() {
    ALBEDO = my_color.rgb;
}

After saving the shader, you can change the per-instance uniform's value using the inspector:

Setting a per-instance uniform's value in the GeometryInstance3D section of the inspector

Setting a per-instance uniform's value in the GeometryInstance3D section of the inspector

Per-instance uniform values can also be set at run-time using set_instance_shader_parameter method on a node that inherits from GeometryInstance3D:

$MeshInstance3D.set_instance_shader_parameter("my_color", Color(0.3, 0.6, 1.0))

When using per-instance uniforms, there are some restrictions you should be aware of:

  • Per-instance uniforms do not support textures, only regular scalar and vector types. As a workaround, you can pass a texture array as a regular uniform, then pass the index of the texture to be drawn using a per-instance uniform.

  • There is a practical maximum limit of 16 instance uniforms per shader.

  • If your mesh uses multiple materials, the parameters for the first mesh material found will "win" over the subsequent ones, unless they have the same name, index and type. In this case, all parameters are affected correctly.

  • If you run into the above situation, you can avoid clashes by manually specifying the index (0-15) of the instance uniform by using the instance_index hint:

instance uniform vec4 my_color : source_color, instance_index(5);

Variables incorporadas

A large number of built-in variables are available, like UV, COLOR and VERTEX. What variables are available depends on the type of shader (spatial, canvas_item or particle) and the function used (vertex, fragment or light). For a list of the built-in variables that are available, please see the corresponding pages:

Funciones integradas

Se soporta un gran número de funciones propias de GLSL ES 3.0. Cuando se utiliza la nomenclatura vec_type (float), vec_int_type, vec_uint_type, vec_bool_type, puede ser escalar o vector.

Función

Description / Return value

vec_type radians (vec_type grados)

Convierte de grados a radianes.

vec_type degrees (vec_type radianes)

Convierte de radianes a grados.

vec_type sin (vec_type x)

Seno.

vec_type cos (vec_type x)

Coseno.

vec_type tan (vec_type x)

Tangente.

vec_type asin (vec_type x)

Arcoseno.

vec_type acos (vec_type x)

Arcocoseno.

vec_type atan (vec_type y_over_x)

Arcotangente.

vec_type atan (vec_type y, vec_type x)

Arcotangente.

vec_type sinh (vec_type x)

Seno hiperbólico.

vec_type cosh (vec_type x)

Coseno hiperbólico.

vec_type tanh (vec_type x)

Tangente hiperbólica.

vec_type asinh (vec_type x)

Seno hiperbólico inverso.

vec_type acosh (vec_type x)

Coseno hiperbólico inverso.

vec_type atanh (vec_type x)

Tangente hiperbólica inversa.

vec_type pow (vec_type x, vec_type y)

Potencia (sin definir si x < 0 o si x = 0 y y <= 0).

vec_type exp (vec_type x)

Exponencial base e.

vec_type exp2 (vec_type x)

Exponencial base 2.

vec_type log (vec_type x)

Logaritmo natural.

vec_type log2 (vec_type x)

Logartimo base 2.

vec_type sqrt (vec_type x)

Raíz cuadrada.

vec_type inversesqrt (vec_type x)

Raíz cuadrada inversa.

vec_type abs (vec_type x)

ivec_type abs (ivec_type x)

Absolute value (returns positive value if negative).

vec_type sign (vec_type x)

ivec_type sign (ivec_type x)

Sign (returns 1.0 if positive, -1.0 if negative, 0.0 if zero).

vec_type floor (vec_type x)

Redondeo a entero hacia abajo.

vec_type round (vec_type x)

Redondeo hacia el entero más cercano.

vec_type roundEven (vec_type x)

Redondeo hacia el entero par más cercano.

vec_type trunc (vec_type x)

Truncamiento.

vec_type ceil (vec_type x)

Redondeo a entero hacia arriba.

vec_type fract (vec_type x)

Fractional (returns x - floor(x)).

vec_type mod (vec_type x, vec_type y)

vec_type mod (vec_type x, float y)

Módulo (resto de la división).

vec_type modf (vec_type x, out vec_type i)

Parte fraccionaria de x, con i como parte entera.

vec_type min (vec_type a, vec_type b)

Valor más bajo entre a y b.

vec_type max (vec_type a, vec_type b)

Highest value between a and b.

vec_type clamp (vec_type x, vec_type min, vec_type max)

Clamp x between min and max (inclusive).

float mix (float a, float b, float c)

vec_type mix (vec_type a, vec_type b, float c)

vec_type mix (vec_type a, vec_type b, bvec_type c)

Linear interpolate between a and b by c.

vec_type fma (vec_type a, vec_type b, vec_type c)

Performs a fused multiply-add operation: (a * b + c) (faster than doing it manually).

vec_type step (vec_type a, vec_type b)

b[i] < a[i] ? 0.0 : 1.0.

vec_type step (float a, vec_type b)

b[i] < a ? 0.0 : 1.0.

vec_type smoothstep (vec_type a, vec_type b, vec_type c)

vec_type smoothstep (float a, float b, vec_type c)

Hermite interpolate between a and b by c.

bvec_type isnan (vec_type x)

Devuelve true si el escalar o componente de un vector es NaN (no es un número).

bvec_type isinf (vec_type x)

Devuelve true si el escalar o componente de un vector es INF.

ivec_type floatBitsToInt (vec_type x)

Copia por bits Float->Int, sin conversión.

uvec_type floatBitsToUint (vec_type x)

Copia por bits Float->UInt, sin conversión.

vec_type intBitsToFloat (ivec_type x)

Copia por bit Int->Float, sin conversión.

vec_type uintBitsToFloat (uvec_type x)

Copia por bit UInt->Float, sin conversión.

float length (vec_type x)

Longitud del vector.

float distance (vec_type a, vec_type b)

Distancia entre vectores, lo mismo que length(a - b).

float dot (vec_type a, vec_type b)

Producto punto.

vec3 cross (vec3 a, vec3 b)

Producto vectorial/cruz/cruzado.

vec_type normalize (vec_type x)

Normalizado a la longitud de unidad.

vec3 reflect (vec3 I, vec3 N)

Reflejo.

vec3 refract (vec3 I, vec3 N, float eta)

Refracción.

vec_type faceforward (vec_type N, vec_type I, vec_type Nref)

Si dot(Nref, I) < 0, retorna N, sino retorna -N.

mat_type matrixCompMult (mat_type x, mat_type y)

Multiplicación de componentes de matrices.

mat_type outerProduct (vec_type column, vec_type row)

Producto exterior.

mat_type transpose (mat_type m)

Matriz transpuesta.

float determinant (mat_type m)

Matriz determinante.

mat_type inverse (mat_type m)

Matriz inversa.

bvec_type lessThan (vec_type x, vec_type y)

Comparación booleana de vectores en vectores < int/uint/float.

bvec_type greaterThan (vec_type x, vec_type y)

Comparación booleana vectorial > entre vectores int/uint/float.

bvec_type lessThanEqual (vec_type x, vec_type y)

Comparación booleana vectorial <= entre vectores int/uint/float.

bvec_type greaterThanEqual (vec_type x, vec_type y)

Comparación booleana vectorial >= entre vectores int/uint/float.

bvec_type equal (vec_type x, vec_type y)

Comparación booleana vectorial == entre vectores int/uint/float.

bvec_type notEqual (vec_type x, vec_type y)

Comparación booleana vectorial != entre vectores int/uint/float.

bool any (bvec_type x)

true if any component is true, false otherwise.

bool all (bvec_type x)

true if all components are true, false otherwise.

bvec_type not (bvec_type x)

Invierte un vector booleano.

ivec2 textureSize (gsampler2D s, int lod)

ivec3 textureSize (gsampler2DArray s, int lod)

ivec3 textureSize (gsampler3D s, int lod)

ivec2 textureSize (samplerCube s, int lod)

ivec2 textureSize (samplerCubeArray s, int lod)

Obtiene el tamaño de una textura.

The LOD defines which mipmap level is used. An LOD value of 0 will use the full resolution texture.

vec2 textureQueryLod (gsampler2D s, vec2 p)

vec3 textureQueryLod (gsampler2DArray s, vec2 p)

vec2 textureQueryLod (gsampler3D s, vec3 p)

vec2 textureQueryLod (samplerCube s, vec3 p)

Compute the level-of-detail that would be used to sample from a texture. The x component of the resulted value is the mipmap array that would be accessed. The y component is computed level-of-detail relative to the base level (regardless of the mipmap levels of the texture).

int textureQueryLevels (gsampler2D s)

int textureQueryLevels (gsampler2DArray s)

int textureQueryLevels (gsampler3D s)

int textureQueryLevels (samplerCube s)

Obtiene número de niveles de mipmap accesibles de una textura.

If the texture is unassigned to a sampler, 1 is returned (Godot always internally assigns a texture even to an empty sampler).

gvec4_type texture (gsampler2D s, vec2 p [, float bias])

gvec4_type texture (gsampler2DArray s, vec3 p [, float bias])

gvec4_type texture (gsampler3D s, vec3 p [, float bias])

vec4 texture (samplerCube s, vec3 p [, float bias])

vec4 texture (samplerCubeArray s, vec4 p [, float bias])

Realiza una lectura de textura.

gvec4_type textureProj (gsampler2D s, vec3 p [, float bias])

gvec4_type textureProj (gsampler2D s, vec4 p [, float bias])

gvec4_type textureProj (gsampler3D s, vec4 p [, float bias])

Realiza una lectura de textura con proyección.

gvec4_type textureLod (gsampler2D s, vec2 p, float lod)

gvec4_type textureLod (gsampler2DArray s, vec3 p, float lod)

gvec4_type textureLod (gsampler3D s, vec3 p, float lod)

vec4 textureLod (samplerCube s, vec3 p, float lod)

vec4 textureLod (samplerCubeArray s, vec4 p, float lod)

Realiza una lectura de textura en un mipmap personalizado.

The LOD defines which mipmap level is used. An LOD value of 0.0 will use the full resolution texture. If the texture lacks mipmaps, all LOD values will act like 0.0.

gvec4_type textureProjLod (gsampler2D s, vec3 p, float lod)

gvec4_type textureProjLod (gsampler2D s, vec4 p, float lod)

gvec4_type textureProjLod (gsampler3D s, vec4 p, float lod)

Realiza una lectura de textura con proyección/LOD.

The LOD defines which mipmap level is used. An LOD value of 0.0 will use the full resolution texture. If the texture lacks mipmaps, all LOD values will act like 0.0.

gvec4_type textureGrad (gsampler2D s, vec2 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureGrad (gsampler2DArray s, vec3 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureGrad (gsampler3D s, vec3 p, vec2 dPdx, vec2 dPdy)

vec4 textureGrad (samplerCube s, vec3 p, vec3 dPdx, vec3 dPdy)

vec4 textureGrad (samplerCubeArray s, vec3 p, vec3 dPdx, vec3 dPdy)

Realiza una lectura de textura con gradientes explícitos.

gvec4_type textureProjGrad (gsampler2D s, vec3 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureProjGrad (gsampler2D s, vec4 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureProjGrad (gsampler3D s, vec4 p, vec3 dPdx, vec3 dPdy)

Performs a texture read with projection/LOD and with explicit gradients.

gvec4_type texelFetch (gsampler2D s, ivec2 p, int lod)

gvec4_type texelFetch (gsampler2DArray s, ivec3 p, int lod)

gvec4_type texelFetch (gsampler3D s, ivec3 p, int lod)

Obtiene un solo texel usando coordenadas enteras.

The LOD defines which mipmap level is used. An LOD value of 0 will use the full resolution texture.

gvec4_type textureGather (gsampler2D s, vec2 p [, int comps])

gvec4_type textureGather (gsampler2DArray s, vec3 p [, int comps])

vec4 textureGather (samplerCube s, vec3 p [, int comps])

Gathers four texels from a texture. Use comps within range of 0..3 to define which component (x, y, z, w) is returned. If comps is not provided: 0 (or x-component) is used.

vec_type dFdx (vec_type p)

Derivative in x using local differencing. Internally, can use either dFdxCoarse or dFdxFine, but the decision for which to use is made by the GPU driver.

vec_type dFdxCoarse (vec_type p)

Calculates derivative with respect to x window coordinate using local differencing based on the value of p for the current fragment neighbour(s), and will possibly, but not necessarily, include the value for the current fragment. This function is not available on gl_compatibility profile.

vec_type dFdxFine (vec_type p)

Calculates derivative with respect to x window coordinate using local differencing based on the value of p for the current fragment and its immediate neighbour(s). This function is not available on gl_compatibility profile.

vec_type dFdy (vec_type p)

Derivative in y using local differencing. Internally, can use either dFdyCoarse or dFdyFine, but the decision for which to use is made by the GPU driver.

vec_type dFdyCoarse (vec_type p)

Calculates derivative with respect to y window coordinate using local differencing based on the value of p for the current fragment neighbour(s), and will possibly, but not necessarily, include the value for the current fragment. This function is not available on gl_compatibility profile.

vec_type dFdyFine (vec_type p)

Calculates derivative with respect to y window coordinate using local differencing based on the value of p for the current fragment and its immediate neighbour(s). This function is not available on gl_compatibility profile.

vec_type fwidth (vec_type p)

Sum of absolute derivative in x and y. This is the equivalent of using abs(dFdx(p)) + abs(dFdy(p)).

vec_type fwidthCoarse (vec_type p)

Sum of absolute derivative in x and y. This is the equivalent of using abs(dFdxCoarse(p)) + abs(dFdyCoarse(p)). This function is not available on gl_compatibility profile.

vec_type fwidthFine (vec_type p)

Sum of absolute derivative in x and y. This is the equivalent of using abs(dFdxFine(p)) + abs(dFdyFine(p)). This function is not available on gl_compatibility profile.

uint packHalf2x16 (vec2 v)

vec2 unpackHalf2x16 (uint v)

Convert two 32-bit floating-point numbers into 16-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packUnorm2x16 (vec2 v)

vec2 unpackUnorm2x16 (uint v)

Convert two 32-bit floating-point numbers (clamped within 0..1 range) into 16-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packSnorm2x16 (vec2 v)

vec2 unpackSnorm2x16 (uint v)

Convert two 32-bit floating-point numbers (clamped within -1..1 range) into 16-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packUnorm4x8 (vec4 v)

vec4 unpackUnorm4x8 (uint v)

Convert four 32-bit floating-point numbers (clamped within 0..1 range) into 8-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packSnorm4x8 (vec4 v)

vec4 unpackSnorm4x8 (uint v)

Convert four 32-bit floating-point numbers (clamped within -1..1 range) into 8-bit and pack them into a 32-bit unsigned integer and vice-versa.

ivec_type bitfieldExtract (ivec_type value, int offset, int bits)

uvec_type bitfieldExtract (uvec_type value, int offset, int bits)

Extracts a range of bits from an integer.

ivec_type bitfieldInsert (ivec_type base, ivec_type insert, int offset, int bits)

uvec_type bitfieldInsert (uvec_type base, uvec_type insert, int offset, int bits)

Insert a range of bits into an integer.

ivec_type bitfieldReverse (ivec_type value)

uvec_type bitfieldReverse (uvec_type value)

Reverse the order of bits in an integer.

ivec_type bitCount (ivec_type value)

uvec_type bitCount (uvec_type value)

Counts the number of 1 bits in an integer.

ivec_type findLSB (ivec_type value)

uvec_type findLSB (uvec_type value)

Find the index of the least significant bit set to 1 in an integer.

ivec_type findMSB (ivec_type value)

uvec_type findMSB (uvec_type value)

Find the index of the most significant bit set to 1 in an integer.

void imulExtended (ivec_type x, ivec_type y, out ivec_type msb, out ivec_type lsb)

void umulExtended (uvec_type x, uvec_type y, out uvec_type msb, out uvec_type lsb)

Multiplies two 32-bit numbers and produce a 64-bit result. x - the first number. y - the second number. msb - will contain the most significant bits. lsb - will contain the least significant bits.

uvec_type uaddCarry (uvec_type x, uvec_type y, out uvec_type carry)

Adds two unsigned integers and generates carry.

uvec_type usubBorrow (uvec_type x, uvec_type y, out uvec_type borrow)

Subtracts two unsigned integers and generates borrow.

vec_type ldexp (vec_type x, out ivec_type exp)

Assemble a floating-point number from a value and exponent.

If this product is too large to be represented in the floating-point type the result is undefined.

vec_type frexp (vec_type x, out ivec_type exp)

Splits a floating-point number(x) into significand (in the range of [0.5, 1.0]) and an integral exponent.

For x equals zero the significand and exponent are both zero. For x of infinity or NaN, the results are undefined.