Custom Shaders

Writing a Custom Shader

With valora, you can shade each path with its own shader, and define custom uniforms. We'll start with this simple GLSL fragment shader:

#version 400

uniform vec3 color;
uniform float scale;
uniform float height;
uniform float width;

out vec4 frag;

void main() {
  vec2 pos = gl_FragCoord.xy / scale;

  vec3 white = vec3(1., 1., 1.);

  frag = vec4(mix(white, color, pos.x / width), 1.);
}

Save this to a file named pattern.frag.

Now, we'll use valora's shader API to define some uniforms and load the shader. A shader in valora is made of two parts:

  1. The shader program. This is the GLSL above, which exposes an interface to provide uniforms.

  2. The uniforms bound to the shader.

First let's define the uniforms type in Rust:

The derive macro UniformSet will generate mappings from the field types to something we can send to the GPU, should such a mapping exist for the type.

Now let's load the shader and draw with it:

If you run the painting with cargo run --release, and change the GLSL, you'll notice that the view pane will update live!

A path rendered with a custom shader.

Updating Uniforms

We can update our uniform values each frame. Once the uniforms are updated, we can rebind with the shader program to make a new shader.

Last updated

Was this helpful?