Shaders
Custom shaders are Slang files under assets/. A mesh uses one
through Mesh.shader; a post effect is listed in the PostProcess component. Every shader
starts with import molten;, which brings in the data the engine passes and the lighting
helpers described below. This page is the complete contract: everything a shader can read
is listed here.
Saving a .slang file (or any file it #includes or imports) recompiles it while the game
runs. A shader with an error keeps the previous version on screen, logs
ERROR: molten: shaders/x.slang: import failed ..., and makes molten-game exit with
status 3 at the end of a scripted run.
Entry points
Every shader file has two entry points with these exact names:
[shader("vertex")] Varyings vertexMain(uint vertexID : SV_VertexID, uint instance : SV_InstanceID) { ... }
[shader("fragment")] float4 fragmentMain(Varyings input) : SV_Target { ... }
SV_InstanceID is optional (see Mesh.instances). The fragment shader can also take
bool frontFacing : SV_IsFrontFace (useful with doubleSided). A mesh shader may also export
prepassMain (see The prepass) and shadowMain (see
Cut-out materials), and a fog density shader has only a
computeMain (Fog density shaders). Entry points are found by name in
the source (comments do not count).
The same mesh shader runs in two passes:
| Pass | drawPush.frame->pass |
What happens |
|---|---|---|
| Main | PASS_MAIN (0) |
Normal drawing into the HDR scene |
| Shadow | PASS_SHADOW (1) |
Only vertexMain runs, once per sun shadow cascade (and per point / spot light shadow map with an Environment), with frame->view_proj set to that view's matrix. Write output.position = mul(drawPush.frame->view_proj, renderPosition) and vertex-animated meshes cast matching shadows. There is no fragment stage, so discarded pixels still cast shadows |
| Prepass | PASS_PREPASS (3) |
M17: opaque meshes, before Main, when TAA, AO, SSR or a post effect is on. Writes depth, normal, roughness and motion (The prepass) |
| Probe | PASS_PROBE (4) |
M17: like Main, drawn from a reflection probe (one face of six). No screen-space inputs |
Post effects run in pass PASS_POST (2).
Coordinates
All positions on the GPU are in render space: world position minus the render origin, a
point near the camera that moves by whole chunks when the camera travels far (large worlds,
M15). Lighting, distances and anything relative to the camera work the same in render space.
For patterns that must stay fixed to the world (noise on terrain, rain cells), use
worldPosition(renderPosition); its precision is that of a float near the absolute world
position, so prefer render-space math for anything far from the world origin.
Matrices are column-major and multiply column vectors: mul(matrix, float4(p, 1)). Clip
space is Vulkan's: depth 0 (near) to 1 (far), and screen uv (0, 0) is the top left.
Back faces are culled with counter-clockwise front faces unless doubleSided is set.
What a shader reads
drawPush (per draw)
| Field | Type | Meaning |
|---|---|---|
vertices |
Vertex* |
The mesh's vertices. Read them with loadVertex(vertexID), never drawPush.vertices[i].field (crashes Intel's Windows driver) |
frame |
FrameData* |
The pass data below |
model |
float4x4 |
Object to render space |
base_color |
float4 |
Mesh.color (linear RGBA) |
texture |
uint |
Texture indices: read them with baseTexture() (Mesh.texture, white if none) and normalTexture() (Mesh.normalMap, 0 if none) |
emission |
float |
Mesh.emission |
roughness, metallic |
float |
Mesh.roughness, Mesh.metallic |
params |
float4 |
Mesh.params: four free numbers for your shader |
draw |
uint |
M17: this draw's index into frame->draws (read it with drawData()); also the draw's SV_StartInstanceLocation, so SV_InstanceID stays 0-based |
maps |
uint |
M17: texture indices of Mesh.ormMap and Mesh.emissionMap (or the glTF's). Use materialRoughMetalOcclusion(uv) and materialEmission(uv). In a post effect: its history |
extra |
float2 |
M17, engine use. Mesh draws: .x is 0 opaque, 1 alpha, 2 additive. Post effects: .x 1 when historyTexture is valid |
Vertex has position (float3), normal (float3) and uv (float2), in model space.
drawPush.frame-> (per pass)
| Field | Type | Meaning |
|---|---|---|
view_proj |
float4x4 |
Render space to clip space (a shadow cascade's in the shadow pass) |
inv_view_proj, view, proj |
float4x4 |
The camera's inverse view-projection, view and projection |
camera_position |
float4 |
.xyz eye position (render space) |
camera_forward |
float4 |
.xyz view direction, .w near plane distance |
viewport |
float4 |
Target width, height, 1/width, 1/height in pixels |
light_direction |
float4 |
Sun: .xyz the direction the light travels, .w 1 if the scene has a sun |
light_color |
float4 |
Sun color times intensity |
ambient_color, ground_ambient |
float4 |
Ambient from above and from below (Light.ambient, Light.groundAmbient) |
time_seconds, delta_seconds |
float |
Simulation time and the time since the previous frame |
pass |
uint |
PASS_MAIN, PASS_SHADOW or PASS_POST |
render_origin |
float4 |
.xyz world position of render space's origin, .w the level's chunk size |
globals[16] |
float4 |
Values gameplay sets with shaderSetGlobal(index, vec4). Read with shaderGlobal(i) |
light_count, lights[64] |
Point and spot lights, nearest first (use localLights) |
|
scene_color, scene_depth |
uint |
Texture indices of the opaque scene's HDR color and the depth buffer, for transparent meshes and post effects (use sceneColor(uv) and sceneDepth(uv)) |
shadows, shadow_map, shadow_* |
Sun shadow data (use sunShadow) |
|
features |
uint |
M17: which of the inputs below are valid this frame, as FEATURE_* bits (hasFeature(FEATURE_FOG)) |
unjittered_view_proj, previous_view_proj |
float4x4 |
M17: this frame's projection without the TAA jitter, and last frame's (in this frame's render space) |
jitter |
float4 |
M17: .xy this frame's TAA offset in NDC, .zw last frame's |
draws |
DrawData* |
M17: per draw, previous_model (last frame's model matrix), motion, material factors (use drawData()) |
lighting |
LightingData* |
M17: shadow faces of point and spot lights, reflection probes, fog volumes |
normal_roughness, motion |
uint |
M17: prepass textures (use sceneNormalRoughness(uv), motionVector(uv)) |
ambient_occlusion, reflections |
uint |
M17: AO and screen-space reflection textures (the lighting helpers read them) |
sky_radiance, sky_sh[9], sky_params |
M17: the sky as image-based light (use skyRadiance(dir, roughness), skyIrradiance(normal)) |
|
fog_volume, fog_params, fog_color, fog_grid |
M17: volumetric fog (use fogAt(renderPos), applyFog(color, renderPos)) |
|
quality |
uint |
M17: 0 low, 1 medium, 2 high (the player's preset) |
Textures: textures[index] is the global texture array. Sample with linearSampler (linear,
repeat, mipmaps, anisotropic: for surfaces) or clampSampler (linear, clamp to edge: for
screen-space reads such as post effects, so the edges do not wrap). Wrap a computed index in
NonUniformResourceIndex(...).
Helpers from import molten
| Function | Result |
|---|---|
loadVertex(vertexID) |
The Vertex |
transformNormal(n) |
Model-space normal to render space (handles non-uniform scale) |
baseTexture(), normalTexture() |
Texture indices of Mesh.texture and Mesh.normalMap (0 = none) |
shaderGlobal(i) |
frame->globals[i] |
sceneTime() |
frame->time_seconds |
worldPosition(renderPos) |
World position (float) |
sunShadow(renderPos, normal) |
0 (shadowed) .. 1 (lit) for the sun |
perturbNormal(normal, renderPos, uv, mapSample) |
Applies a tangent-space normal map sample (OpenGL convention, +Y up); no vertex tangents needed |
surfaceLighting(surface) |
The default material's full lighting: sun with shadows, point and spot lights, sky/ground ambient with reflections, emission. Surface has position, normal, albedo, alpha, roughness, metallic, emission |
localLights(surface, viewDir), ambientLight(surface, viewDir) |
Parts of surfaceLighting |
surfaceLightingOccluded(surface, occlusion) |
M17: surfaceLighting with the material's ambient occlusion (an ORM map's R) |
materialRoughMetalOcclusion(uv) |
M17: roughness, metallic, occlusion from the ORM map times the draw's factors (or drawPush.roughness / metallic and 1 without a map) |
materialEmission(uv) |
M17: the emission map's color (0 without one) |
sunShadowSoft(renderPos, normal, pixel) |
M17: soft (PCSS) sun shadow, as wide as the sun's size; sunShadow without an Environment |
localShadow(light, renderPos, normal, pixel), localLightsShadowed(surface, viewDir, pixel) |
M17: point and spot light shadows |
skyIrradiance(normal), skyRadiance(dir, roughness) |
M17: light from the Environment's sky (diffuse, and prefiltered for a roughness) |
fogAt(renderPos), applyFog(color, renderPos) |
M17: volumetric fog between the eye and a point: rgb in-scatter, a transmittance. Transparent shaders apply it themselves |
drawData() |
M17: this draw's DrawData |
previousRenderPosition(modelPos) |
M17: where a model-space vertex was last frame (motion vectors) |
prepassOutput(normal, roughness, renderPos, previousRenderPos) |
M17: what prepassMain returns |
motionVector(uv), sceneNormalRoughness(uv) |
M17: prepass results at a screen uv |
historyTexture(uv), historyValid() |
M17, post effects: the effect's own output from last frame |
interleavedNoise(pixel) |
M17: per-pixel noise that changes every frame (TAA averages it away) |
lightmapUv(vertexID) |
M18: in vertexMain, this vertex's uv in the draw's baked lightmap atlas (pass it to the fragment stage) |
alphaCutoff(), alphaClip(alpha) |
M20: this draw's cut-out threshold (0 = none), and discard when alpha is below it |
hasGi(), giWeight(renderPos) |
M20: the frame has a ray-traced GI volume (cinematic tier); how much it lights a point (1 inside, fading to 0 one probe spacing outside) |
giIrradiance(renderPos, normal, toEye) |
M20: the volume's bounced light at a surface (irradiance / pi, like skyIrradiance). surfaceLighting already uses it |
surfaceLightingBaked(surface, occlusion, lightmapUv) |
M18: surfaceLightingOccluded that takes its diffuse ambient from the lightmap when the draw has one |
instancePosition(position, SV_InstanceID), instanceNormal(normal, SV_InstanceID), instanceTransform(SV_InstanceID) |
M19: in vertexMain, a model-space point or normal moved by the draw's per-instance transform (Mesh.instanceData, foliage); identity without one |
windSway(modelPosition, renderPosition) |
M19: how far the Environment's wind moves this vertex (add it to the render position); scaled by the draw's sway strength (foliage wind) and the vertex's height in the mesh; zero without wind |
applyDecals(inout surface, inout occlusion) |
M19: in fragmentMain of opaque materials, before lighting: the frame's decals change the surface's albedo, normal, roughness, metallic and occlusion |
drawTexture(i) |
M19: engine material texture slot i of the draw (the terrain's layers; 0 = none) |
hasProbeGrid(), probeGridIrradiance(renderPos, normal) |
M18: the level's baked light probes (used automatically for draws without a lightmap) |
fullscreenVertex(vertexID) |
Post effects: the vertex of a screen-covering triangle, with position and uv |
postInput(uv) |
Post effects: the HDR color so far |
sceneColor(uv) |
Opaque scene HDR color (before transparent meshes) |
sceneDepth(uv) |
Depth buffer value at uv (1 = nothing drawn there) |
renderPositionFromDepth(uv, depth) |
Render-space position of the surface at uv |
screenFromRender(renderPos) |
.xy screen uv and .z depth of a render-space point |
The default material (engine/shaders/basic_lit.slang in the engine) is this shader, which is
the best starting point for your own:
import molten;
struct Varyings
{
float4 position : SV_Position;
float3 renderPosition : POSITION0;
float3 normal : NORMAL;
float2 uv : TEXCOORD0;
};
[shader("vertex")]
Varyings vertexMain(uint vertexID : SV_VertexID)
{
Vertex vertex = loadVertex(vertexID);
float4 world = mul(drawPush.model, float4(vertex.position, 1.0));
Varyings output;
output.position = mul(drawPush.frame->view_proj, world);
output.renderPosition = world.xyz;
output.normal = transformNormal(vertex.normal);
output.uv = vertex.uv;
return output;
}
[shader("fragment")]
float4 fragmentMain(Varyings input, bool frontFacing : SV_IsFrontFace) : SV_Target
{
float3 normal = normalize(input.normal);
if (!frontFacing) normal = -normal;
uint normalMap = normalTexture();
if (normalMap != 0)
{
float3 mapped = textures[NonUniformResourceIndex(normalMap)].Sample(linearSampler, input.uv).rgb;
normal = perturbNormal(normal, input.renderPosition, input.uv, mapped);
}
float4 albedo = drawPush.base_color *
textures[NonUniformResourceIndex(baseTexture())].Sample(linearSampler, input.uv);
Surface surface;
surface.position = input.renderPosition;
surface.normal = normal;
surface.albedo = albedo.rgb;
surface.alpha = albedo.a;
surface.roughness = saturate(drawPush.roughness);
surface.metallic = saturate(drawPush.metallic);
surface.emission = albedo.rgb * max(0.0, drawPush.emission);
return float4(surfaceLighting(surface), albedo.a);
}
The prepass (M17)
With TAA, ambient occlusion, SSR or a post effect on, opaque meshes are drawn twice: first a
prepass that writes depth, the surface normal, roughness and motion, then the normal pass
(which tests against that depth without writing it). The prepass runs your vertexMain.
Without a prepassMain, the engine's prepass fragment computes a flat normal from depth and
the motion from the draw's model matrix change, which is right for any shader that does not
move its vertices. A shader that animates vertices (wind, waves) or has a normal map exports
its own, so motion vectors and SSR / AO match what it draws:
// Add to the Varyings: float3 previousPosition : POSITION1;
// In vertexMain:
// output.previousPosition = drawPush.frame->pass == PASS_PREPASS
// ? previousRenderPosition(animatedModelPosition) : world.xyz;
[shader("fragment")]
PrepassOutput prepassMain(Varyings input, bool frontFacing : SV_IsFrontFace)
{
return prepassOutput(normal, roughness, input.renderPosition, input.previousPosition);
}
previousRenderPosition uses last frame's model matrix; for vertex animation, evaluate your
animation with last frame's time (sceneTime() - drawPush.frame->delta_seconds) and pass that
model-space position.
Cut-out materials
A Mesh with alphaCutoff (or a glTF with alphaMode: "MASK") is a cut-out (M20): the default
material discards texels whose base color alpha is below the cutoff in fragmentMain,
prepassMain and shadowMain. A custom opaque shader supports cut-outs by calling
alphaClip(alpha) in its fragment entry points, and by exporting a shadowMain, which the
renderer runs in shadow passes for cut-out draws only (other draws' shadows have no fragment
stage). Read the full-resolution alpha there: a shadow map's coarse mips average a card's holes
away.
[shader("fragment")]
void shadowMain(Varyings input)
{
alphaClip(drawPush.base_color.a * textures[NonUniformResourceIndex(baseTexture())].SampleLevel(linearSampler, input.uv, 0).a);
}
Without a shadowMain a cut-out casts a solid shadow. At the cinematic tier, rays test the
same base color alpha against the cutoff.
Transparent and instanced meshes
Mesh.blend selects how a mesh's fragment color combines with what is behind it:
blend |
Result | Notes |
|---|---|---|
"opaque" (default) |
Replaces | Writes depth, casts shadows |
"alpha" |
color.rgb * color.a + behind * (1 - color.a) |
Glass, smoke, decals |
"additive" |
behind + color.rgb * color.a |
Rain streaks, sparks, light shafts, glows |
Transparent meshes draw after every opaque mesh, sorted far to near by their origin, test
depth (so walls hide them) but do not write it, and never cast shadows. They can read
sceneColor(uv) (for refraction) and sceneDepth(uv) (to fade where they meet a surface,
"soft particles"). Their pixels are in HDR, so values above 1 are fine and bloom picks them up.
Mesh.instances draws the mesh that many times (up to 1,048,576) in one draw call. The vertex
shader gets SV_InstanceID and decides where each copy goes; the default material puts them
all at the object's position. This is how to draw rain, snow, grass or debris cheaply. A
rain shader (one quad mesh, instances: 20000, blend: "additive", castShadows: false):
import molten;
struct Varyings
{
float4 position : SV_Position;
float2 uv : TEXCOORD0;
float fade : TEXCOORD1;
};
float hash(uint n) { n = (n << 13u) ^ n; n = n * (n * n * 15731u + 789221u) + 1376312589u; return float(n & 0x7fffffffu) / float(0x7fffffff); }
[shader("vertex")]
Varyings vertexMain(uint vertexID : SV_VertexID, uint instance : SV_InstanceID)
{
FrameData* f = drawPush.frame;
float area = drawPush.params.x; // width of the rain box around the camera (m)
float height = drawPush.params.y; // its height (m)
float speed = drawPush.params.z; // fall speed (m/s)
float intensity = shaderGlobal(0).y; // set from Cast
Vertex v = loadVertex(vertexID); // quad: x in -0.5..0.5, y in 0..1
// Each drop has a fixed cell around the camera; it falls and wraps around.
float3 eye = f.camera_position.xyz;
float2 cell = float2(hash(instance * 3u), hash(instance * 3u + 1u)) - 0.5;
float fall = frac(hash(instance * 3u + 2u) - f.time_seconds * speed / height);
float3 base = float3(eye.x + cell.x * area, eye.y - height * 0.5 + fall * height, eye.z + cell.y * area);
// Billboard around the fall direction, stretched along it.
float3 toEye = normalize(eye - base);
float3 side = normalize(cross(float3(0, 1, 0), toEye)) * 0.012;
float3 p = base + side * v.position.x + float3(0, -0.45, 0) * v.position.y;
Varyings output;
output.position = mul(f.view_proj, float4(p, 1.0));
output.uv = v.uv;
output.fade = instance < uint(intensity * 20000.0) ? 1.0 : 0.0; // fewer drops when it eases off
return output;
}
[shader("fragment")]
float4 fragmentMain(Varyings input) : SV_Target
{
float edge = 1.0 - abs(input.uv.x * 2.0 - 1.0);
return float4(drawPush.base_color.rgb, drawPush.base_color.a * edge * input.fade);
}
Post effects
The PostProcess component (put it on one object, for example a camera rig or a director)
controls how the HDR frame becomes the picture:
postProcess: {
exposure: 1.2, // multiplier before tone mapping
toneMapping: "aces", // "none" (clamp, the default) or "aces" (filmic)
bloom: 0.6, // 0 = off; glow around anything brighter than the threshold
bloomThreshold: 1.0,
antialiasing: "fxaa", // "none" or "fxaa"
effect1: "shaders/fog.slang", // up to effect4; run in order before bloom and tone mapping
},
Without a PostProcess object the frame uses exposure 1, clamping and no bloom or FXAA.
A post effect draws one full-screen triangle. It reads the HDR color so far with
postInput(uv), can read depth and the camera, and returns the new HDR color:
import molten;
[shader("vertex")]
FullscreenVertex vertexMain(uint vertexID : SV_VertexID) { return fullscreenVertex(vertexID); }
[shader("fragment")]
float4 fragmentMain(FullscreenVertex input) : SV_Target
{
float3 color = postInput(input.uv).rgb;
float depth = sceneDepth(input.uv);
float3 p = renderPositionFromDepth(input.uv, depth);
float distance = depth >= 1.0 ? 1e4 : length(p - drawPush.frame->camera_position.xyz);
float4 fog = shaderGlobal(1); // rgb color, a density, set from Cast
float amount = 1.0 - exp(-fog.a * distance);
return float4(lerp(color, fog.rgb, amount), 1.0);
}
History, motion and half resolution (M17)
Each post effect renders into its own pair of images, so it can read its own output from last
frame with historyTexture(uv) and blend it with this frame's result (clouds and fog marched
with few, noisy samples become smooth). Reproject with the motion of the surface:
historyTexture(uv - motionVector(uv)). Before there is a history (the first frame, a resize,
a camera cut or any shader reload) historyValid() is false and historyTexture returns the
input. effect1Scale: 0.5 runs an effect at half resolution; the engine upsamples it with the
depth so edges stay sharp. sceneNormalRoughness(uv) and motionVector(uv) work in every post
effect (the prepass runs whenever a post effect exists).
The order with M17 features on: shadows, prepass, AO / SSR, fog volume, opaque meshes, sky, fog, transparent meshes, post effects, TAA, auto exposure, bloom, tone mapping, UI.
Fog density shaders
A FogVolume's densityShader sets the fog's density inside its box, for clouds, smoke and
storms. It is a compute shader with [numthreads(4, 4, 4)] run over the froxel grid (the
view volume cut into cells, 160 x 90 x 64 at high quality, out to 128 m):
import molten;
[shader("compute")]
[numthreads(4, 4, 4)]
void computeMain(uint3 froxel : SV_DispatchThreadID)
{
if (!fogFroxelInside(froxel)) return; // outside the grid or this volume's box
float3 world = worldPosition(fogFroxelPosition(froxel));
float billow = saturate(sin(world.x * 0.3 + sceneTime()) * sin(world.z * 0.25) + 0.3);
addFogDensity(froxel, 0.4 * billow); // per meter, in the volume's color
}
addFogDensity fades at the box's faces. The engine lights the fog afterwards (sun with
shadows, sky, lamps with their shadows).
Feeding values from gameplay
import { shaderSetGlobal } from "molten";
shaderSetGlobal(1, vec4(0.55, 0.6, 0.65, 0.02)); // fog color and density for fog.slang
Globals belong to the engine: they keep their values across Cast reloads and start at zero
when the game starts. Mesh.params is the per-object alternative (set it in the .object
file or from a behavior: obj.mesh.params = vec4(...)). Devtools' Edit viewport draws with
globals at zero.
Lighting reference
- Sun: the first
Lightwithkind: "directional".color * intensityreaches a surface facing it;shadowsandshadowDistancecontrol its four shadow cascades (2048 x 2048 each). Other directional lights are ignored. - Point and spot lights:
kind: "point"/"spot",range(m, light fades smoothly to zero there),spotAngle(full outer cone in degrees). Brightness falls off with the square of the distance, so lamps need intensities around 5-50. Up to 64 nearest the camera light each frame. With an Environment,shadows: truemakes the nearest 16 cast shadows. - Material:
roughness0 (mirror) to 1 (matte),metallic0 or 1 for real materials (values between are for blends like dust on metal). Wet asphalt: dark color, roughness 0.1-0.3. Diffuse isalbedo * N.L * light(no 1/pi), so white under intensity 1 is white. - Ambient:
ambientlights surfaces facing up,groundAmbientsurfaces facing down; smooth surfaces reflect the same sky/ground colors. With an Environment (M17) the sky lights the scene instead (skyIrradiance,skyRadiance), reflection probes replace the sky inside their boxes, SSR adds what is on screen, and ambient occlusion darkens corners. - Physical sky: its radiance is scaled by pi to match the no-1/pi diffuse, so sun and sky keep
their real proportion. The sun's
color * intensityis the light above the atmosphere; the scene gets it tinted by the atmosphere (orange at sunset). - Ray-traced GI (M20, cinematic tier): inside a
giVolume,giIrradiancereplaces lightmaps, baked probes and the sky as the diffuse ambient; it holds the light that bounced off the scene (from the sun, lamps, emission and the sky), shadowed by the scene itself.
Limits
- Point and spot light shadows need an Environment. A custom shader's cut-out holes show in
shadows only if it exports
shadowMain. - Transparent meshes write no motion, so thin fast transparent effects (rain streaks) look fainter with TAA than with FXAA.
- Screen-space reflections only show what is on screen; reflection probes cover the rest inside their boxes. Bounced light comes from a bake (M18) or, at the cinematic tier, from a GI volume (M20); ray-traced reflections are M22.
- Pixel formats: the scene is RGBA16F (HDR); post effects read and write HDR.