Manual

Manual

Shaders

A shader is a program the GPU runs to draw a surface. Your game can have shaders of its own, written in WESL beside its assets, and draw with them through materials. This page covers the shaders folder and its templates, how a shader is written, what the engine reads out of it, materials that run one, how they blend and cast shadows, shaders that move a mesh's corners, and how a build compiles your shaders ahead of time.

The shaders folder

A game's shaders are .wesl files in its shaders folder, beside assets and scripts. The Project panel shows it as one of its top folders. A shader is made only there: elsewhere the shader items of the Create menu are grayed, and say where a shader goes.

ItemWhat the new shader draws
Lit ShaderA surface lit by the scene's lights with Bevy's own lighting, shadowed and fogged as Bevy's surface is, with a color, a roughness, a metalness and a cutoff for cut-outs. Made as NewLitShader.wesl.
Unlit ShaderA surface drawn its color as it is, whatever the lights. Made as NewUnlitShader.wesl.
UI ShaderAn element of the game's interface, above its background and image and below its text. Made as NewUiShader.wesl.

Find them in the + button's menu, or as New Lit Shader, New Unlit Shader and New UI Shader in the right-click menu. Each draws as soon as it is made: a material running it is white, or textured where it is given a texture. Its comments say what the engine reads out of it.

Double-click a shader to open it in your code editor, the program your system opens .wesl files with. Picked, the Inspector shows its compiled variants (see Shaders compiled ahead for a build) and its text, with Open.

A UI Shader draws a UI element through the element's Material section, which takes a material file running a UI shader; see UI documents. The rest of this page is about shaders that draw meshes.

WESL

Shaders are written in WESL, as Bevy's own are: WGSL, the language of WebGPU, with imports and switches added. Plain WGSL is WESL too, and a .wgsl file in the shaders folder is read the same way.

  • Imports come first in a file, each ended by a semicolon: import bevy_pbr::render::forward_io::VertexOutput;. Several from one module are written in braces: import bevy_pbr::render::{pbr_functions, pbr_types};.
  • A switch keeps what follows it only where it is on: @if(VERTEX_UVS_A) before a statement, a declaration, a struct's field or an import, or before a block { ... }, with @else after it for where it is off. A switch Bevy turns on for one draw and off for another, such as VERTEX_UVS_A for a mesh with texture coordinates, makes each its own program.
  • A number Bevy gives is read from the constants module: constants::MATERIAL_BIND_GROUP.
import bevy_pbr::render::forward_io::VertexOutput;

@fragment
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
    var color = vec4<f32>(1.0);
    @if(VERTEX_COLORS)
    color = in.color;
    return color;
}

What a shader takes

A mesh's shader is a fragment shader whose entry point is called fragment, taking Bevy's VertexOutput, as Bevy's own shaders do. It can import Bevy's shader library: bevy_pbr::render::pbr_functions lights a surface as Bevy's are lit, as the Lit Shader does.

The engine reads what a material running it holds out of the shader itself, so nothing declares the values twice:

  • Its values are the struct at @group(constants::MATERIAL_BIND_GROUP) @binding(0) var<uniform>. Each is a 32-bit float, signed or unsigned integer, a vector of two to four of them, or a 4×4 matrix of floats, up to 256 bytes in all.
  • A value starts as the comment after it says, such as speed: f32, // = 2, or else at zero. A vector of three or four floats whose name has color in it is a color, which starts white and shows as a swatch in the Inspector.
  • Its textures are the texture_2d<f32> at bindings 1, 3, 5 and 7, each with its sampler at the binding after it. A texture is named by its variable's name, and a slot given no image samples white.
import bevy_pbr::render::{forward_io::VertexOutput, mesh_view_bindings::globals};

struct Params {
    color: vec4<f32>,   // = 0.25, 0.45, 0.9, 1
    speed: f32,         // = 2
}

@group(constants::MATERIAL_BIND_GROUP) @binding(0) var<uniform> params: Params;
@group(constants::MATERIAL_BIND_GROUP) @binding(1) var color_texture: texture_2d<f32>;
@group(constants::MATERIAL_BIND_GROUP) @binding(2) var color_sampler: sampler;

@fragment
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
    var color = params.color;
    @if(VERTEX_UVS_A)
    color *= textureSample(color_texture, color_sampler, in.uv);
    let pulse = 0.75 + 0.25 * sin(globals.time * params.speed);
    return vec4<f32>(color.rgb * pulse, color.a);
}

A material running this shader holds color, speed and color_texture. A file whose values the engine cannot read, such as a value of another type or more than 256 bytes of them, is refused, and the log says why.

Shaders that import other shaders

A shader imports another of your game's by its path in the shaders folder, after package::, so several shaders can share their lighting or their noise: import package::noise::fbm; takes fbm from noise.wesl, and import package::common::noise::fbm; from common/noise.wesl. A package's shaders import each other the same way, package:: naming the package's own shaders folder, and yours import a package's by its id with _ for each .: import acme_demo::noise::fbm; for Acme Demo's noise.wesl. The engine reads every file a shader imports along with it.

Shaders from before Bevy 0.20

A shader written for the composer Bevy used before 0.20 is refused, and the log says so. Each of its directives has a WESL form:

BeforeIn WESL
#import bevy_pbr::forward_io::VertexOutputimport bevy_pbr::render::forward_io::VertexOutput;, at the top of the file
#import bevy_ui::ui_vertex_output::UiVertexOutputimport bevy_ui_render::ui_vertex_output::UiVertexOutput;
#define_import_path my_game::noiseNothing: a file is imported by its path, package::noise
#ifdef NAME … #else … #endif@if(NAME) { … } @else { … }, or @if(NAME) before one statement
#{MATERIAL_BIND_GROUP}constants::MATERIAL_BIND_GROUP

Most of Bevy's library moved under render, as bevy_pbr::render::pbr_functions did. A UI shader's corners are given as two radii each now, in.border_radius_x and in.border_radius_y, as a corner can be an ellipse.

Materials that run a shader

In the editor

Make a material file (Material in the Project panel's Create menu) and pick your shader in its Shader list in the Inspector. Under Double Sided and Transparency, the Inspector shows a row for each value the shader takes, by the name the shader gives it, and a slot for each texture: drop an image on it, or pick one with its button. Each edit is saved to the material file as you make it. Give the material to entities as you give any material file; see Meshes and materials.

In the file, the material names its shader by its path and identity, and its values and textures by the shader's names for them:

{
  "abyssMaterial": 2,
  "ids": {
    "color_texture": "6d33cf113bfc4cd183855291b38be3c0",
    "shader": "b612f1ee9f5e49a0b04e2e28e9f37485"
  },
  "shader": "shaders/pulse.wesl",
  "textures": {
    "color_texture": "textures/stone.png"
  },
  "values": {
    "color": [1, 0.55, 0.15, 1],
    "speed": 4
  }
}

From code

Each of your game's shaders has a key under Shaders, named after its file, whether it is addressable or not: pulse.wesl is Shaders.Pulse. A package's shaders have keys under its own namespace, such as Acme.Demo.Shaders.Noise. A shader is read at once, so what it takes is known on the next line.

ShaderId pulse = context.Assets.LoadShader(Shaders.Pulse);MaterialId hot = context.Assets.CreateMaterial(pulse);context.Assets.SetColor(hot, "color", new Vector4(1f, 0.5f, 0.1f, 1f));context.Assets.SetFloat(hot, "speed", 4f);context.Commands.SetMaterial(entity, hot);   // the system declares AndSetMaterialcontext.Assets.Release(hot);                 // the entity keeps it

A material running a shader is an ordinary material: it is given to entities with SetMaterial or SetMesh, copied with CopyMaterial and let go of with Release. Its values are set by name:

MethodSets
SetFloat(material, name, value)A f32
SetInt(material, name, value)An i32 or a u32
SetVector(material, name, value)A vector of floats, from a Vector4: as many of its numbers as the value holds
SetColor(material, name, color)A color, linear, with alpha where it has one
SetMatrix(material, name, value)A mat4x4<f32>, from a Matrix4x4 as .NET writes it; the engine turns it into WGSL's columns
SetTexture(material, name, image)A texture, by its variable's name; null empties it

GetFloat and GetVector read a value back. A name the shader does not take, or a value of the wrong kind, is refused, naming it. context.Assets.LayoutOf(shader) lists what a shader takes.

What changes every frame

Setting a value changes the material, and Bevy then prepares every entity drawn with it again. Setting values every frame on a material that thousands of entities share costs time every frame. What changes every frame for everyone is better read in the shader from Bevy: the time as globals.time and the camera as view, both from bevy_pbr::render::mesh_view_bindings.

Change a shader while the editor is open

Save a shader with the editor open and everything drawn with it is drawn with what the file says now. Every material running it keeps each value whose name, kind and size are the same, and a new value starts as the file says. A file whose values cannot be read is refused and draws as it did, and a mistake the renderer finds compiling it is written to the Logs panel.

How a material blends, and from which sides

A material running your shader is drawn opaque, from the front, until it is told otherwise, as Bevy's own surface is.

  • Transparency in the Inspector, "alpha_mode" among the file's values, or context.Assets.SetAlphaMode(material, AlphaKind.Blend) from code: Opaque, Mask, Blend, Premultiplied, AlphaToCoverage, Add or Multiply. See Transparency for what each does. With Mask, the shader leaves pixels out with discard.
  • Double Sided in the Inspector, "double_sided": true in the file, or context.Assets.SetDoubleSided(material, true): back faces are drawn too, in the shadows as well. A back face keeps the normal of its front, so a lit shader turns it round, as the Lit Shader does with pbr_functions::prepare_world_normal(in.world_normal, true, is_front).

AlphaModeOf and IsDoubleSided read them back. A UI element's material is blended whatever it says.

Shadows of a cut-out

A material set to Mask casts the shadow of what it keeps, as long as its shader also draws its depth and its shadows. Bevy draws those passes with your shader with the PREPASS_PIPELINE switch on, wherever the shader's text names it, and the shader leaves out there what it leaves out in its own pass. The Lit Shader shows how: its color is worked out in a function both passes call, its main fragment, marked @if(!PREPASS_PIPELINE), discards under @if(MAY_DISCARD), and a fragment marked @if(PREPASS_PIPELINE && PREPASS_FRAGMENT) discards the same pixels. A shader that never names PREPASS_PIPELINE, and every blended material, casts the shadow of all of its mesh.

Move the mesh's corners

A shader can place the mesh's corners itself, for water's waves or grass bending in the wind. A @vertex fn vertex, taking Bevy's Vertex and returning a VertexOutput, runs in place of Bevy's mesh shader in the main pass. Bevy may pack a mesh's corners small, so the shader unpacks them first with decompress_vertex, as Bevy's own mesh shader does. Its depth and shadows move too only where the shader also answers PREPASS_PIPELINE, writing the prepass's VertexOutput there; otherwise they are drawn where the mesh is.

import bevy_pbr::render::{
    forward_io::{Vertex, VertexOutput, decompress_vertex},
    mesh_functions,
    mesh_view_bindings::globals,
    view_transformations::position_world_to_clip,
};

@vertex
fn vertex(packed: Vertex) -> VertexOutput {
    let vertex = decompress_vertex(packed, packed.instance_index);
    var out: VertexOutput;
    let world_from_local = mesh_functions::get_world_from_local(vertex.instance_index);
    out.world_position = mesh_functions::mesh_position_local_to_world(world_from_local, vec4(vertex.position, 1.0));
    out.world_position.y += 0.05 * sin(2.0 * globals.time + out.world_position.x);
    out.position = position_world_to_clip(out.world_position.xyz);
    out.world_normal = mesh_functions::mesh_normal_local_to_world(vertex.normal, vertex.instance_index);
    @if(VERTEX_UVS_A)
    out.uv = vertex.uv;
    @if(VERTEX_OUTPUT_INSTANCE_INDEX)
    out.instance_index = vertex.instance_index;
    return out;
}

The fragment shader beside it is your own, as before. A UI element's shader keeps Bevy's vertex stage.

Shaders compiled ahead for a build

A built game compiles none of your shaders as it plays. Bevy composes a shader for each set of switches a draw asks for, from the mesh's attributes, the camera, the lights and the pass, and each set is a program of its own: a variant. The editor writes down every variant of your shaders it draws, in the Scene panel or as the game plays, and compiles each to SPIR-V in the background, exactly as the renderer would compose it. The status bar says how far along it is, such as Compiling shaders 2 of 6 · glow.wesl.

The compiled variants keep no name from your source, only the entry points'. A variant is compiled again only when what it is made from changes: its file, a file of yours it imports, Bevy's shader library, or the GPU's switches. A desktop build packs each shader's variants as SPIR-V and no WGSL; a web build packs them for WebGPU and WebGL2, each as WGSL with no names but its entry points. See Build and run your game.

The shader's Inspector

Pick a shader in the Project panel. Its Compiled section says how many variants were collected and compiled, how big their SPIR-V is and how big packed, what every variant shares folded into one line (Shared by all), and a row for each variant with only its own switches, which are what make it another program, and its size. Clear forgets the variants and deletes what they compiled to; each is collected again as it is drawn. A mistake is shown there and in the log with its file, and with its line and column where it is found as the shader is composed; one found only after, such as a name nothing declares, says what is wrong. The variants compiled before it are kept. Under it, Text shows the shader's text.

Use Compiled Shaders

Edit ▸ Use Compiled Shaders, ticked while it is on, draws your game's shaders as a built game does: from their compiled variants only. A variant that nobody compiled draws magenta, and the log says how it differs from the nearest one that was, such as with VERTEX_COLORS, without MULTISAMPLED. Being drawn, it is collected and compiled, and drawn from as soon as it lands. Saving a shader while it is on compiles its variants again.

Before you build

A build packs the variants compiled so far, and a variant nobody drew is not among them: a built game draws it magenta. The variants are kept in the project's cache folder, which is left out of version control, so they are collected on each computer as it draws the game. Before you build, play through your game in the editor, ideally with Use Compiled Shaders on, so every camera, light and mesh your shaders meet has been drawn at least once.

In the Scripting API

  • ShaderId and ShaderAddress: a shader read from the shaders folder, and the key it is read by.
  • ShaderFiles: what makes a file a shader.
  • AssetAccess: LoadShader, CreateMaterial, and the setters a material's values are set by.
  • ShaderLayout and ShaderValue: what a shader takes, as the engine reads it.
  • AlphaKind: how a material is drawn over what is behind it.
  • MaterialId: a material, running Bevy's own surface or one of your shaders.