A shader compiler you embed in your app. oksl compiles a small, safe shading language at runtime, through one front end, from SkSL (the language of Skia's runtime effects), GLSL ES 3 as Shadertoy writes it, or plain GLSL ES 3.0 / 3.1 vertex, fragment and compute shaders, into:
- SPIR-V for Vulkan,
- MSL for Metal,
- DXBC (Shader Model 5.1) for Direct3D 12,
- a CPU program that renders or dispatches the same shader with no GPU at all.
It's plain Odin with no external toolchain. Runtime shaders usually mean
shipping glslang, shaderc, SPIRV-Cross, DXC or Slang; with oksl the compiler
is part of your binary, so nobody installs anything. The library depends on
core: only; the tools also use vendor:sdl3 and vendor:stb.
- SDL_GPU apps that want shaders compiled at runtime on every platform, instead of shipping pre-built blobs made offline with SDL_shadercross.
- Games and engines: hot-reloaded shaders while developing, modding and player-made effects. The language has no pointers or memory access beyond its inputs, which is why Skia uses SkSL for runtime effects (see Limitations about loops before running untrusted code).
- Creative coding and VJ tools: a Shadertoy-style playground in your own app.
- UI frameworks: custom effects (ripples, blurs, gradients, glows) as small shaders, the way Flutter uses Skia's runtime effects.
- Headless rendering and tests: the CPU interpreter renders the same
effect on machines without a GPU (servers, CI) and gives a reference for
golden-image tests.
tools/gpu_paritychecks GPU against CPU. - Learning: a small, readable compiler from source to real GPU code.
Relatives: Skia's SkSL runtime effects, naga (wgpu's shader translator), SDL_shadercross. oksl's niche is Odin-native, tiny, runtime, with a CPU fallback. It started as the shader engine of onimite (video from Lua scripts), where it compiles fframes' SkSL shaders unchanged; demo/ is an onimite video about it.
m, errors, ok := oksl.compile(source) // SkSL
// m, errors, ok := oksl.compile_shadertoy(glsl) // Shadertoy GLSL (Options.profile = .Shadertoy)
// m, errors, ok := oksl.compile_glsl(frag) // GLSL ES 3.0 fragment shader (Options.profile = .Glsl)
// m, errors, ok := oksl.compile_glsl(comp, {stage = .Compute}) // GLSL ES 3.1 compute shader
defer oksl.destroy(m)
if !ok {
// Errors are values ({pos, code, operands}); text is made here.
fmt.eprint(oksl.format_errors(errors)) // "12:7: undeclared identifier \"foo\""
return
}
// GPU: SDL_CreateGPUShader with m.spirv (entry oksl.SPIRV_ENTRY), m.msl
// (entry oksl.MSL_ENTRY) or m.dxbc (format .DXBC, entry oksl.DXBC_ENTRY;
// compiled with dxbc = true), num_samplers = m.num_samplers, num_uniform_buffers =
// m.num_uniform_buffers, num_storage_buffers = len(m.storage_buffers);
// Vertex shader: oksl.compile(oksl.LAYER_VERTEX_GLSL, {profile = .Glsl, stage = .Vertex}), once.
// CPU:
block := make([]u8, m.block_size)
oksl.write_builtins(block, {resolution = {f32(w), f32(h), 1}, time = t, channel_resolution = {{tw, th, 1}, {}, {}, {}}})
// or one input at a time: oksl.write_input(block, .Channel_Time, {clip_seconds}, 0)
oksl.set_uniform(m, block, "uSpeed", {0.5})
scratch: oksl.Scratch // working memory, one per thread
defer oksl.scratch_destroy(&scratch)
oksl.run(&m.program, block, w, h, pixels, w * 4, &scratch, {sampler = my_sampler})A Shadertoy multipass program (Common, Buffer A-D, Image) compiles into a pass table and an edge array:
desc := oksl.Program_Desc{common = common_src}
desc.sources[.Buffer_A] = trail_src
desc.sources[.Image] = image_src
desc.channels[.Buffer_A][0] = {.Buffer, u8(oksl.Pass_Kind.Buffer_A)} // itself: the previous frame
desc.channels[.Image][0] = {.Buffer, u8(oksl.Pass_Kind.Buffer_A)} // this frame's
desc.channels[.Image][1] = {.External, 7} // the host's input 7
g, errors, ok := oksl.compile_program(desc) // errors: "Buffer A:3:9: ..."
defer oksl.destroy_program(g)
for pass, i in g.passes { // buffers (A..D), then Image
for e in g.edges[pass.edges.start:][:pass.edges.count] {
// e.channel reads: e.source = .Buffer (pass e.id, this frame),
// .Previous (pass e.id, last frame) or .External (input e.id)
}
// run pass.module like any module, into a float target for buffers
}SkSL as Skia's runtime effects accept it (with ES3-style extensions where they cost nothing):
- Entry point:
half4 main(float2 coord)(float4/vec4andvec2spellings too).coordis the position in layer units (pixel centres, origin top-left; the host'siResolutionscales uv to it). The result is premultiplied RGBA. - Types:
bool int uint float half(halfisfloat: everything is 32-bit), vectorsfloat2..4,half2..4,int2..4,uint2..4,bool2..4, matricesfloat2x2..float4x4/halfNxM(column-major, N columns of M rows), the GLSL spellingsvec3,ivec2,mat3,mat2x4..., structs, and constant-size arrays (dynamic indexing allowed, no arrays of arrays). - Uniforms: scalars, vectors, matrices and arrays of them;
layout(...)qualifiers (layout(color)) are accepted and ignored. A uniform declared with the name and type of an input row (float3 iResolution,float iTime,int iFrame, ...: the table below) binds to that slot; declared with another type it is an ordinary uniform the host fills by name. - Children:
uniform shader name;(up to four, channels in declaration order).name.eval(p)samples the child atpin the child's own pixels: it lowers to an explicit-lod sample atp / childSize(the size comes from the block), bilinear and clamped by the host's sampler, like Skia's image shaders. - Expressions and statements: the usual operators, swizzles (
xyzw,rgba,stpq) for reading and writing, constructors with flattening,?:,,,.length(),if/else,for,while,do-while,switch(int or uint, constant labels, fallthrough),break,continue,return,const,in/out/inoutparameters, overloads, prototypes and calls before definitions. Implicitint -> uint -> floatconversions are accepted. Recursion is an error. - Built-ins: SkSL's intrinsics (the GLSL ES 3 math, geometric, matrix,
vector-relational and bit-cast functions,
saturate),sk_FragCoord(float4(coord, 0, 1): the layer is its own device), and the extensionsdFdx,dFdy,fwidth. - Diagnosed: SkSL has no preprocessor (
#versionlines are skipped, any other directive is an error), nodiscard, nosampler2D/texture()(useuniform shaderand.eval), nocolorFilter/blenderchildren, no shader parameters, andmainImageis not an entry point (compile Shadertoy code throughcompile_shadertoy). Errors areline:column: message; several are collected per compile.
compile_shadertoy (or Options.profile = .Shadertoy) takes Shadertoy code,
GLSL ES 3, through the same parser, checker and backends as SkSL:
- Entry point:
void mainImage(out vec4 fragColor, in vec2 fragCoord). The checker synthesizes thevec4 main(vec2 coord)the backends call, as IR (not text):fragCoordhas the bottom-left origin,gl_FragCoordis the same point, and the colour comes out clamped with alpha 1.mainitself is reserved. - Inputs: every Shadertoy input is declared before the source, from
the input table:
iResolution,iTime,iTimeDelta,iFrame,iFrameRate,iMouse,iDate,iSampleRate,iChannelTime[4],iChannelResolution[4],iChannel0..3. Redeclaring one with its own type (uniform vec3 iResolution;, common in code from other hosts) is allowed. A shader uses (and the host binds) only the ones it reads. - Sampling:
texture(iChannelN, uv)takes 0..1 uv with the origin at the bottom left, like Shadertoy;textureLod,texelFetch(integer texels from the bottom left of their level; see texelFetch below) andtextureSizework too.texturesamples at the level its uv derivatives pick (plus its bias), the others at an explicit level, as SkSL's.evaldoes; on the CPU the host sampler sees the level (see the CPU interpreter). Auniform sampler2D name;takes a channel the source doesn't name asiChannelN, and samplers can be function parameters (textureSize, which isiChannelResolution[N].xyat every lod, needs the channel itself). - Preprocessor: token level: object-like and function-like
#define(with##),#undef,#if/#ifdef/#ifndef/#elif/#else/#endifwithdefined()and integer expressions,#line,#error;#version,#extensionand#pragmaare skipped.GL_ES,__VERSION__(300) and Shadertoy'sHW_PERFORMANCE(1) are defined. Tokens keep their source positions (a macro's tokens take the position of its use), so errors point at the user's line and column. - Language: the SkSL list above with the GLSL spellings only (
vec3,ivec2,mat2x3; nofloat3,half,saturate,sk_FragCoord), plusdiscard,precisionstatements andhighp/mediump/lowp(accepted and ignored).uniform shaderand.evalare SkSL's and diagnosed.
compile_glsl (or Options.profile = .Glsl) takes a GLSL ES 3.0
fragment shader, or a vertex shader with Options.stage = .Vertex: the
Shadertoy language and preprocessor above, without Shadertoy's
conventions. compile_pipeline compiles a vertex and a fragment shader
together and links them:
p, errors, ok := oksl.compile_pipeline({vertex = vs, fragment = fs, vertex_prelude = vp, fragment_prelude = fp})
defer oksl.destroy_pipeline(p)
// p.vertex and p.fragment are Modules; errors read "Fragment:12:7: ...".
offset, type, found := oksl.uniform_offset(p.vertex, "modelViewMatrix")- Entry point:
void main(). - Vertex shaders:
inattributes (layout(location = N)or the next free location),outvaryings andgl_Position, written as it is (no depth or y remapping: give it SDL_GPU's clip space, depth 0..1, y up). Interpolated integer outputs needflat.Module.stage_inputsare the attributes the shader reads. - Linking: a pipeline matches varyings by name, as GLSL ES 3.00 does (which allows no locations on them): each fragment input takes the location of the vertex output of its name. One the vertex shader does not write, or writes with another type or interpolation, is an error.
- Preludes:
Options.prelude(per stage in a pipeline) is source preprocessed and checked ahead of the shader's own: a host's built-in declarations, and#defines that apply to the shader, including ones that rename keywords and built-ins (#define varying out,#define gl_FragColor pc_fragColor), as three.js's ShaderMaterial prefixes do. Errors in it are the prelude's (Vertex prelude:3:1: ...). - Stage variables:
inandoutglobals, withlayout(location = N)(other layout qualifiers are ignored). Inputs without one take the next free location in declaration order; one output may omit it, several may not. Inputs are float, int or uint scalars or vectors, integer onesflat(smoothandcentroidare accepted); outputs are float, int or uint scalars or vectors, at locations 0..7.Module.stage_inputs/stage_outputsreflect them (name, type, location, flat). - gl_FragCoord: the fragment's window position, origin top-left
(Vulkan's and Metal's), pixel centres at .5. gl_FrontFacing: whether
the triangle faces the camera. gl_VertexID (vertex shaders): the
vertex's index in the draw, its first vertex included (Vulkan's
VertexIndex, Metal's
vertex_id); on the CPU,Run_Options.first_vertexplus the vertex's index inrun_vertex. gl_SampleMask[0] (fragment shaders): the samples of the fragment's coverage it keeps (SPIR-V's SampleMask, Metal'ssample_mask;run_fragment'ssample_masks).dFdx,dFdyandfwidthare fine derivatives, per row and column of the quad, as the interpreter computes them (SPIR-V'sOpDPdxFineand friends: a driver may take plainOpDPdxcoarse). - Uniforms and samplers: nothing is declared up front. The uniform
block holds only the uniforms the shader uses, std140 from offset 0, in
declaration order (none: no block);
uniform_offsetandset_uniformfind them by name, and unused or undeclared names are not found. Up to 16uniform sampler2Ds andsampler2DArrays take channels in declaration order (Module.channel_arraysmarks the arrays).textureuv starts at the top left, as in Vulkan (no flip).textureSizequeries the image (on the CPU, the size the host gives; an array's z is its layers) andtexelFetchreads the image's texel (below), so both take sampler parameters too. Asampler2DArraytakesvec3(uv, layer)intexture,textureLodandtextureGrad(the layer rounded to nearest even and clamped, as GPUs take it; RADV does, not GLSL ES'sfloor(r + 0.5)) andivec3(x, y, layer)intexelFetch(GLSL profiles).textureGrad(s, uv, dPdx, dPdy)samples at the level those derivatives pick, in any stage. - texelFetch reads exactly one texel: texel
p(asampler2DArray's layerp.z) of levellod, whatever sampler is bound with the texture (its filter, wrap,max_lod, lod bias and anisotropy play no part), and(0, 0, 0, 0)wherep, the layer orlodis outside the image's, negative ones included (anintlod and auintone alike, so0x80000000uand up are out), on every GPU backend and on the CPU. SPIR-V reads it withOpImageFetchbehind a bounds check (Vulkan leaves a fetch out of range undefined, androbustImageAccessallows(0, 0, 0, 1)):uint(lod) < OpImageQueryLevels,uvec2(p) < uvec2(size at that lod)and a layer below the layers, the lod and coordinates it queries and fetches moved to 0 where they are out of range, the result selected from the in-range mask. MSL callsread()behind the same check, the level checked before its size is queried. DXBC is oneld, which D3D12 makes 0 out of range in the format's components but 1 in an alpha the format lacks (vkd3d'sR8andR16read(0, 0, 0, 1)), so its w is masked by the texel being insideresinfo_uint's size at that lod (and layers) and its levels. In the Shadertoy profilep.ycounts from the bottom row of its level (h - 1 - p.ywithhthat level's height, as the image reports it). A shader that wants the edge texel instead clamps the coordinate itself:texelFetch(s, clamp(p, ivec2(0), size - 1), lod)withsizethe level's (textureSize(s, lod); in Shadertoy, whosetextureSizeis level 0's,max(size >> lod, 1)). The image's levels are the GPU texture'snum_levels: on the CPU a channel read through the sampler callback has the full mip chain of itschannel_sizesunlessRun_Options.channel_levelssays fewer, so setchannel_levelsto your GPU texture'snum_levelsfor the CPU to match it (a texture made withnum_levels = 1reads 0 on the GPU at every lod above 0, where the full chain calls the sampler).tools/gpu_parityandtools/d3d12_parity'sbound_fetchcheck it on every format, with SDL's default sampler (whosemax_lod0 pinned a sampled texelFetch to level 0),max_lod1000 wrapping and clamped, and a 16x anisotropic sampler with a lod bias of 3: the texel inside,(0, 0, 0, 0)bit for bit outside;d3d12_parity'sbound_fetch_layersthe same through arrays of every format, layers out of range included (whereR8andR16would read alpha 1); and both tools'testdata/st_texel_fetch_levels.glslthe Shadertoy flip at every level of a non-square 48 x 20 image with 4 of its 6 levels, which the CPU gets aschannel_levels4. - Storage buffers: in vertex and fragment shaders, read-only, GLSL ES
3.1's block with one runtime-sized array:
layout(std430) readonly buffer Rows { Row rows[]; } rowBuf;read asrowBuf.rows[i](orrows[i]without an instance name), at any int or uint index, in any function and either stage (row_majorandcolumn_majorlayout qualifiers are accepted as no-ops; compute shaders also allow read-write andwriteonlystorage buffers, bound in SDL_GPU's compute order below). Elements are float, int and uint scalars and vectors and structs of them, laid out std430 (layout(std430)is optional; other packings, writes in graphics stages, sized arrays, bools and matrices are diagnosed).Module.storage_buffersgives each block's name, element type and stride (vec3[]steps by 16 bytes, while a struct'svec3field takes 12) in SDL_GPU binding order—which in graphics stages equals declaration order since every buffer isreadonly. Word addresses are 32-bit (they wrap) on every backend; a read past the buffer gives 0 on the CPU and is undefined on the GPU (Metal reads past it). - Taps:
Options.taps(in a pipeline, the vertex stage's) runs what a vertex shader'smaindoes towardgl_Positionagain for other environments, such as a motion blur's shutter opening, once per tap and beforemainitself. Tap N copies the statements the position depends on (inmain, the functions it reaches and the globals' initializers): each uniform reads at its offset plus (N + 1) ×Module.block_stride, the attributes the tap lists read their twins ({"position", "o3dOpenPosition"}),gl_Positiongoes to the tap'sposition, and the shader's own outputs and globals are private to the copy. Twins and positions are ordinaryinandout vec4declarations, usually the prelude's, so locations, reflection and linking treat them like any other; a twin the copy never reads is no input, and a position takes a location like any output, so a prelude declares it only for a pipeline with taps. The block holds1 + tapsenvironments ofblock_stridebytes, each laid out asModule.uniforms(set_uniform(m, block[n * m.block_stride:], ...)fills environment n).run_vertexruns the taps too, their positions ordinary varyings; each tap costs another run of the arithmetic the position depends on. - Diagnosed:
varying/attribute(unless a prelude defines them), duplicate or out-of-range locations, integer interpolated variables withoutflat, initializers on stage variables, writes to inputs, gl_FragCoord and gl_FrontFacing, fragment-only features (discard, derivatives, gl_FragCoord, gl_SampleMask) in vertex shaders, gl_VertexID in fragment shaders,sampler2DArrayin the Shadertoy profile (whose channels are 2D), more than 16 samplers, taps outside a vertex shader, a tap position, attribute or twin not declared as one, a position the shader uses itself, and two taps writing one position.
compile_glsl(src, {stage = .Compute}) (or Options{profile = .Glsl, stage = .Compute}, .comp in the tools; rejected by the SkSL and
Shadertoy profiles) compiles a GLSL ES 3.1 compute shader:
-
Workgroup size:
layout(local_size_x = X, local_size_y = Y, local_size_z = Z) in;is required (omitted axes default to 1, positive integer literals up to 1024 per axis andX * Y * Z <= 1024in total; duplicate declarations must specify the same set of axes with the same values) and is reflected inModule.threadcount. Vulkan's guaranteed minimums (maxComputeWorkGroupSize = {128, 128, 64},maxComputeWorkGroupInvocations = 128) are lower, so8x8,16x8and64x1stay portable across drivers. -
Built-ins:
gl_GlobalInvocationID,gl_LocalInvocationID,gl_WorkGroupID,gl_NumWorkGroups(uvec3),gl_LocalInvocationIndex(uint), and the compile-time constantgl_WorkGroupSize(const uvec3, usable in constant expressions and array sizes). WithOptions.num_work_groups_uniform,gl_NumWorkGroupsis auvec3in the uniform block on the GPU, atModule.num_work_groups_offset(for Direct3D 12, which has no group count; see DXBC below), and still the dispatch'sgroupson the CPU. -
Storage buffers and binding order:
std430storage buffers may bereadonly, read-write (unqualified) orwriteonly(readonlyandwriteonlytogether is diagnosed; reads fromwriteonlyand writes toreadonly, including compound assignment,++/--andout/inoutarguments, are diagnosed). Because SDL_GPU binds read-only storage buffers before read-write /writeonlyones,Module.storage_buffersandRun_Options.buffersuse that same order—read-only blocks in declaration order, then read-write andwriteonlyblocks in declaration order—and eachStorage_Buffer_Infocarriesreadonlyandwriteonly:buffer A { uint out_words[]; }; readonly buffer B { float weights[]; }; // Binding / reflection / Run_Options.buffers order: [B, A].
Writes are 32-bit word-addressed across SPIR-V, MSL and the CPU VM (masked per lane; out-of-bounds writes are dropped on the CPU and undefined on the GPU). Graphics stages still allow only
readonlybuffers, so their binding order equals declaration order. -
Storage images: up to 16 (
IMAGE_COUNT) 2D storage images (image2D,uimage2D,iimage2D), each with a requiredlayout(<format>)fromrgba8,rgba16f,rgba32f,r32f(image2D),r32ui(uimage2D) orr32i(iimage2D), qualifiedreadonlyorwriteonly; unqualified read-write is allowed on the single-channel formatsr32f,r32uiandr32i(GLSL ES 3.1 / Vulkan baseline withoutshaderStorageImageReadWithoutFormat). Built-ins areimageLoad(img, ivec2),imageStore(img, ivec2, val)andimageSize(img). User functions may takeinimage parameters withoutlayout(...)qualifiers: the format is inferred from call-site arguments and conflicting call-site formats are diagnosed (a read-write image may be passed to areadonlyorwriteonlyparameter). Portable GLSL ES 3.1 shaders pass images towriteonlyparameters (glslangrequiresGL_EXT_shader_image_load_formattedonreadonlyand read-write image parameters, which oksl accepts as an extension).Module.storage_imagesandRun_Options.imagesfollow SDL_GPU's order: read-only images first, then read-write /writeonly, each in declaration order. When creating SDL_GPU textures, useCOMPUTE_STORAGE_READforreadonly,COMPUTE_STORAGE_WRITEforwriteonly, andCOMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE(notREAD | WRITE) for read-writer32*images. -
Sampling:
sampler2Dandsampler2DArraywork withtextureLod,texelFetch,textureGradandtextureSize. Implicit-leveltexture,textureProjand derivatives (dFdx,dFdy,fwidth) need fragment quads and are diagnosed in compute, along with stagein/outvariables,discardand vertex/fragment built-ins. -
Workgroup
sharedmemory: globalsharedvariables of scalar (bool,int,uint,float), vector, matrix, array and struct types, with no initializers and up to 16,384 bytes in total (MAX_COMPUTE_SHARED_MEMORY_SIZE's GLSL ES 3.10 minimum). Non-globalshareddeclarations, extra qualifiers andsharedin other stages are diagnosed. On GPUs,sharedmemory starts with undefined, stale contents at each workgroup, so shaders must initialize every element before reading or atomically updating it;run_computezeroessharedmemory on the CPU only, for deterministic CPU runs. -
Barriers:
barrier(),memoryBarrierShared()andgroupMemoryBarrier()in compute shaders, plusmemoryBarrier(),memoryBarrierBuffer()andmemoryBarrierImage()across GLSL stages. Per GLSL ES 3.10 §8.14,barrier()is permitted inside dynamically uniform control flow (including reduction loops, helper calls and after uniform earlyreturns). Although §8.14 specifies execution ordering alone forbarrier(), oksl guarantees thatbarrier()also orderssharedmemory on every backend (SPIR-VWorkgroupMemory | AcquireRelease0x108matchingglslang, MSLmem_threadgroup, and sequential chunks on the CPU), sobarrier()makes priorsharedwrites visible across the workgroup without a separatememoryBarrierShared(). -
Atomics:
atomicAdd,atomicMin,atomicMax,atomicAnd,atomicOr,atomicXor,atomicExchangeandatomicCompSwapon scalarintanduintinsharedvariables and read-writebufferblocks (including array elements, struct fields and vector components). Locals, uniforms,readonly/writeonlybuffers and floats are rejected;atomic_uintcounters (atomicCounter*,memoryBarrierAtomicCounter) are rejected because Vulkan disallows SPIR-V'sAtomicStoragecapability, andimageAtomic*is rejected as outside GLSL ES 3.10 core.
A Pass_Graph is passes (modules, in running order) and edges saying
what each pass's channels read. Nothing in it depends on the dialect:
make_program builds one from compiled modules of any profile, and
compile_program builds Shadertoy's (below) on top of it.
blur, _, _ := oksl.compile(blur_sksl) // any profile
smooth, _, _ := oksl.compile_glsl(smooth_frag)
g, errors, ok := oksl.make_program({
{module = blur, name = "blur", channels = {0 = {.External, 7}}},
{module = smooth, name = "smooth", channels = {0 = {.Buffer, 0}, 1 = {.Previous, 1}}},
})
defer oksl.destroy_program(g) // frees the modules too, also on failure
for p in g.passes {
block := make([]u8, p.module.block_size)
oksl.write_builtins(p.module, block, builtins) // the inputs only where the module has them
// ... render p.module into its target, binding channels from g.edges[p.edges]
}- A channel reads the host's input (
.External, its id), this frame's output of an earlier pass (.Buffer, pass index) or the previous frame of any pass, itself included (.Previous; transparent black on the first frame).g.outputis the result's pass (the last by default); at mostPASS_MAX(8) passes. - Inputs appear per dialect: SkSL
uniform shaderchildren, ShadertoyiChannel0..3, GLSLuniform sampler2Ds, channels in declaration order. A GLSL pass on the layer quad readsin vec2 uvat location 0. - A Shadertoy module compiled with
Options.unclampedreturns mainImage's colour as it is, for a pass rendering into a float target.
compile_program takes a Program_Desc: an optional Common source, up
to four buffer passes (Buffer A-D, "" for absent ones), the Image pass
(required) and, per pass, what each channel reads (Channel_Ref: a
buffer by its Pass_Kind, read as this frame's output when it runs
earlier and as the previous frame otherwise (or explicitly .Previous),
one of the host's inputs by id, or nothing).
- Common is one shared unit, preprocessed and parsed once: its macros (a mark of the macro table) and its declarations (copies of its flat syntax arrays) start every pass, as Shadertoy prepends it. A pass's own macros stay in that pass. Errors in Common are reported once.
- Passes are modules, in
Pass_Graph.passes: the buffers in A..D order, then the Image pass, which runs last. Buffer passes return mainImage's colour unclamped with its alpha (render them into float targets); the Image pass is clamped and opaque likecompile_shadertoy. - Edges are one flat array, for the channels each pass samples, sorted
by pass then channel (
Pass.edgesis a pass's range):Bufferreads this frame's output of an earlier pass,Previousthe previous frame's output of itself or a later pass (Shadertoy's feedback; the host binds transparent black on the first frame),Externalthe host's inputid. - Errors carry their source in
Pos.src(Source: Common, Buffer A..D, Image;SOURCE_NAMESspells them) andformat_errorswritesBuffer A:12:7: .... A channel bound to a buffer the program lacks is an error at the channel's first use in the pass.
The inputs come first, at fixed offsets, whether or not they are used:
| offset | uniform |
|---|---|
| 0 | iResolution vec3 |
| 12 | iTime |
| 16 | iTimeDelta |
| 20 | iFrame (int) |
| 24 | iFrameRate |
| 28 | iSampleRate |
| 32 | iMouse vec4 |
| 48 | iDate vec4 |
| 64 | iChannelResolution: channel sizes in pixels, vec3[4] (stride 16; .eval divides by xy, textureSize gives xy) |
| 128 | iChannelTime float[4] (stride 16) |
| 192 | user uniforms, std140, in declaration order |
The rows are one table, INPUTS (indexed by Input: name, type, offset;
the channel rows give the sampler binding). Module.uniforms reflects each
user uniform (offset, size, count, stride) and Module.block_size gives
the total size (with vertex taps, block_stride is one environment's).
Bools are stored as 4-byte uints. write_builtins, write_input (one
row, by index) and set_uniform fill a block.
inputs_used and channels_used/num_samplers say what the shader
reads, and channel_names[n] names what channel n binds (a uniform shader, iChannelN or a uniform sampler2D). SkSL and Shadertoy have
four channels (the rows above); GLSL shaders have 16 (SAMPLER_COUNT).
- SPIR-V 1.0: fragment entry
main; stage inputs and outputs at their locations (the layer profiles:vec2 uvat location 0, 0..1 across the layer, origin top-left, and thevec4colour at location 0); gl_FragCoord as theFragCoordbuilt-in; integer inputsFlat; channel n as a combined image sampler at set 2, binding n (an arrayed image for asampler2DArray); storage buffer i at set 2, bindingnum_samplers + i(aBufferBlockofuintwords, read-only); the uniform block at set 3, binding 0.OriginUpperLeft. - MSL: fragment entry
oksl_main, returningOksl_Out(output N as[[color(N)]]); input N read as[[user(locnN)]](SPIRV-Cross's names, so SDL_shadercross vertex shaders match), gl_FragCoord as[[position]]; channel n at[[texture(n)]]/[[sampler(n)]](texture2d_arrayfor asampler2DArray); the block at[[buffer(0)]], storage buffer i at[[buffer(num_uniform_buffers + i)]]asconst device uint*. Its struct is padded to the same std140 offsets. - Vertex shaders: SPIR-V entry
main(Vertex), attributes at their locations,gl_Positionas thePositionbuilt-in, varyings at their locations,gl_VertexIDasVertexIndex; samplers then storage buffers at set 0, the uniform block at set 1, binding 0. MSL:vertex Oksl_Out oksl_mainwith attributes as[[attribute(N)]]of a[[stage_in]]struct,gl_VertexIDas a[[vertex_id]]parameter, varyings as[[user(locnN)]]and the position as[[position]]; the block at[[buffer(0)]], storage buffers after it. One vertex uniform block (Module.num_uniform_buffers1, or 0 when there is none). - Compute shaders:
Module.threadcountand the six SDL_GPU counts (num_samplers,num_readonly_storage_textures,num_readonly_storage_buffers,num_readwrite_storage_textures,num_readwrite_storage_buffers,num_uniform_buffers) populateSDL_GPUComputePipelineCreateInfodirectly. SPIR-V (GLCompute,LocalSize,NonWritableonreadonly,NonReadableonwriteonly): set 0 binds combined samplers (0..num_samplers - 1), read-only storage images, then read-only storage buffers; set 1 binds read-write /writeonlystorage images, then read-write /writeonlystorage buffers; set 2, binding 0 binds the uniform block. MSL (kernel void oksl_main): flat[[texture(n)]](0..num_samplers - 1sampled textures paired with[[sampler(n)]], then read-only storage images asaccess::read, then read-write /writeonlystorage images asaccess::read_write/access::write), the uniform block at[[buffer(0)]]when present, then read-only storage buffers (const device uint*) followed by read-write /writeonlystorage buffers (device uint*) starting at[[buffer(num_uniform_buffers)]]. - DXBC (
Module.dxbc, SDL_GPU'sDXBCformat: a container with ISGN, OSGN and an SM5.1 SHEX chunk, signed with the DXBC checksum, and SFI0 when a compute shader uses UAV registers pastu7; entrymain, profilesvs_5_1,ps_5_1andcs_5_1; emitted only withOptions.dxbc): SDL_GPU's D3D12 registers. Vertex shaders: channel n att[n]ands[n]in space 0, storage buffer i att[num_samplers + i](aByteAddressBuffer), the uniform block atb0in space 1. Fragment shaders: the same in space 2, the block in space 3. A stage variable at location N isTEXCOORDN in register N (SDL_GPU's vertex semantics), so a vertex shader's outputs and a fragment shader's inputs agree by register whichever a stage reads;SV_Positiontakes register 16 (after the 16 locations), as do a vertex shader'sSV_VertexIDinput, andSV_IsFrontFace17; colour target N isSV_TargetN andgl_SampleMask[0]SV_Coverage(oMask).gl_FragCoord.wis1 / SV_Position.w(D3D gives the clip w). D3D'sSV_VertexIDleaves out the draw's first vertex (StartVertexLocation, andBaseVertexLocationof an indexed draw), so on D3D12gl_VertexIDis 0 at the draw's first vertex, where Vulkan and Metal (andRun_Options.first_vertexon the CPU) count SDL'sfirst_vertexin (a host that batches draws passes its base in a uniform instead). Every function is inlined (vkd3d takes no DXBC subroutines); every loop has one shape (a first-pass flag runs a for's step and a do-while's test at the top, socontinueis a bare continue);discardends the invocation (retafter it, as SPIR-V'sOpKill); integer division and remainder follow the CPU's rules (x / 0andx % 0are 0); run-time indexes are clamped as on the CPU, and a storage buffer read loads only the words it reads, at element * stride + offset in 32-bit words (0 past the buffer's end, as on the CPU). The emitter's tables live in the temporary allocator; the container is the only allocation on the module's. - DXBC compute shaders (
cs_5_1,dcl_thread_groupfromlocal_size): SDL_GPU's D3D12 compute registers (SDL_gpu_d3d12.c's compute root signature): channel n att[n]ands[n]in space 0, read-only storage images att[num_samplers + i]and read-only storage buffers after them, in space 0; read-write andwriteonlystorage images atu[i], read-write andwriteonlystorage buffers after them, in space 1; the uniform block atb0in space 2.gl_GlobalInvocationID,gl_WorkGroupID,gl_LocalInvocationIDandgl_LocalInvocationIndexareSV_DispatchThreadID,SV_GroupID,SV_GroupThreadIDandSV_GroupIndex. Direct3D has nogl_NumWorkGroups, and SDL_GPU passes no group count, so reading it is the errorDxbc_Num_Work_Groupsunless the shader is compiled withOptions.num_work_groups_uniform: then in every GPU backend (SPIR-V, MSL and DXBC, so one block layout serves them all)gl_NumWorkGroupsis auvec3the checker adds to the block after the shader's own uniforms, under an internal name no shader can declare (so a uniform of the shader's never meets it; it is not inModule.uniforms, which lists the shader's own); the host writes the dispatch's group count there as three u32s, atModule.num_work_groups_offset(-1 when the shader does not read it), while the CPU (run_compute) keeps reading itsgroups, which it knows. Alocal_size_zover Direct3D's 64 isDxbc_Local_Size_Z, more than 64 UAV registers (writable images and buffers)Dxbc_Too_Many_Uavsand more than 128 SRV registers (samplers, read-only images and buffers)Dxbc_Too_Many_Srvs, each with the count and the limit. Storage buffers are raw views (read-only ones SRVs, the others UAVs) with the CPU's rules: word element * stride + offset in 32 bits, reads past the end 0, a write past it dropped word by word (a vector or struct straddling the end keeps its words inside), atomics past it dropped and returning 0 (D3D leaves their value undefined, so it is masked by the buffer's size). Read-only images are typed SRVs read withld, read-write andwriteonlyones typed UAVs (ld_uav_typedonly on the read-writer32f,r32uiandr32ithat GLSL ES 3.10 allows, which every D3D12 device loads, so no feature flag is needed); out of bounds a load gives 0 in every component (a single channel format's w too, as on the CPU; D3D would give 1) and a store writes nothing. Shared variables are packed into oneg0as the CPU lays them out, their run-time indexes clamped as on the CPU. Barriers map tosyncas the SPIR-V backend's scopes and semantics say:barrier()issync_g_t,memoryBarrier()sync_uglobal_g,memoryBarrierShared()sync_g,memoryBarrierBuffer()andmemoryBarrierImage()sync_uglobal,groupMemoryBarrier()sync_ugroup_g; a device-scope fence orders only UAVs declared globally coherent, so the raw UAVs are_glcwhen the shader callsmemoryBarrier()ormemoryBarrierBuffer(), the typed ones when it callsmemoryBarrier()ormemoryBarrierImage()(and only then, keeping the other shaders' caches). Every atomic is the immediate form (imm_atomic_*,imm_atomic_cmp_exchforatomicCompSwap), its operands evaluated left to right after its target.rgba16fstores round toward zero on D3D (its rule for float conversions) where the CPU rounds to nearest: they can differ by one half-float ulp. - Layer vertex shader (
LAYER_VERTEX_GLSL, the source oftestdata/layer.vert, which a host compiles once like any vertex shader:compile(LAYER_VERTEX_GLSL, {profile = .Glsl, stage = .Vertex})): position (vec2, target pixels, y down) at location 0, uv (vec2) at location 1, and its uniform block holding the target size (size,vec4, xy used). Positions map to NDC like ovg's SDL_GPU backend. It writes uv at location 0 (in MSL as[[user(locn0)]]). A GLSL fragment shader readinglayout(location = 0) in vec2can run on it too.
The generated fragment code derives coord from uv * iResolution.xy, so
set iResolution to the layer's size in the units coord should run in
(pixels, or the box's own units as fframes does).
compile also builds Module.program. Run it with
run(&m.program, block, width, height, out, stride, &scratch, opts) for
RGBA8, or run_f32 for float RGBA, from the output at location 0;
run_targets writes every output, one float target per location. A
Scratch (registers and masks) grows to the largest program it has run,
so runs that reuse one allocate nothing. Run_Options takes a
sampler callback (proc(user, channel, uv, lod, layer) -> [4]f32; .eval
passes lod 0; layer is a sampler2DArray's, rounded to nearest even
and saturated to an int (NaN as 0), for the host to clamp to its layers,
or texelFetch's p.z), the channels' sizes in texels (and layers; in
every profile, Shadertoy's too) and the levels texelFetch finds there
(channel_levels, below), optional bound images (channel_images,
below), the
storage buffers' words (buffers, one []u32 per buffer in
Module.storage_buffers order; a read past one gives 0 and a write past
one is dropped), the compute storage images (images, one Storage_Image
per image in Module.storage_images order), an optional sub-rectangle
(x, y, w, h in layer pixels; when region_targets is set on run_f32 or
run_targets, each non-nil target is tightly packed to that region and pixel
(px, py) is written to target[(py - y) * w + (px - x)], validated via
ensure for w > 0 && h > 0, the region inside 0..width × 0..height,
and len >= w * h on every non-nil target, while the shader still sees
full-layer gl_FragCoord, uv, varyings and derivatives; run rejects
region_targets) and
the stage inputs by location
(Varying: per component a + dx * x + dy * y at pixel centres, what one
triangle's rasterization gives). An input without one is zero, except
location 0, which gets the layer's uv as the layer vertex shader writes it.
For hosts that rasterize themselves (a software 3D renderer keeping its own clipping, coverage and depth), two calls run a pipeline's stages:
scratch: oksl.Scratch // one per thread; a Program is only read
defer oksl.scratch_destroy(&scratch)
// Vertices: attribute n from (pointer, byte stride, format: 1 to 4 f32, i32
// or u32, Ubyte4_Norm or Ushort4, as SDL_GPU's formats); out come clip
// positions and each vertex's varyings, `varying_floats` per vertex at the
// offsets Stage_Var_Info.offset gives (flat ones flagged; integers as their
// bits, so a fragment's flat integer input is its provoking vertex's bits).
oksl.run_vertex(&p.vertex.program, vblock, attrs, count, positions, varyings, &scratch)
// Fragments: the host's 2x2 quads (top-left pixel, facing, helper lanes,
// optionally each lane's depth for gl_FragCoord.z) with their interpolated
// varyings, one float of the record at a time across every lane; out come
// every output per lane (targets[n] for location n, nil to skip), the
// lanes shaded and, when given, each lane's kept samples (gl_SampleMask[0],
// all ones when unwritten: AND it with coverage).
oksl.run_fragment(&p.fragment.program, fblock, {count = n, origin = origins, front_facing = facing, helpers = helpers, varyings = soa, depth = z}, targets, shaded, &scratch, {}, sample_masks)run_fragment shades LANES / 4 (16) quads at a time, each quad's
derivatives from its own lanes as in the layer runner, so its results
match the layer runner's bit for bit (a test checks).
Compute shaders run through run_compute:
img := oksl.Storage_Image{data = rgba_bytes, width = w, height = h, stride = w * 4, format = .Rgba8}
// Run all workgroups, or split [first_group ..< first_group + group_count) across a worker pool:
oksl.run_compute(&m.program, block, {groups_x, groups_y, 1}, &scratch, {images = {img}, buffers = {out_words}}, first_group, group_count)run_compute executes one workgroup at a time (group_count = -1 runs to
the end of groups.x * groups.y * groups.z). The JIT (x86-64 with AVX2,
and arm64) runs a workgroup in batches of 8 consecutive gl_LocalInvocationIndex
values, each batch through the whole program before the next; the
interpreter runs it in ceil(local_size / 64) 64-lane chunks, each
instruction across a chunk. A workgroup whose size isn't a multiple of the
batch (8 in the JIT, 64 in the interpreter) leaves lanes idle in its last
one, and lane layout inside a workgroup does not depend on how the
workgroup range is split across caller threads (give each thread its own
Scratch). run_compute validates Run_Options up front and panics on
missing buffers or images, mismatched Image_Format, negative dimensions or
strides, strides smaller than width * texel_bytes, or undersized data.
On Storage_Image (stride == 0 means width * texel_bytes), rgba8 writes round(clamp(x, 0, 1) * 255), rgba16f
rounds to nearest even (Vulkan allows drivers to round toward zero),
integer formats are exact, single-channel r32* loads fill .gba = (0, 0, 1) in bounds, out-of-bounds imageLoad returns (0, 0, 0, 0), and
out-of-bounds imageStore and buffer writes are dropped. run_compute zeroes
shared memory at the start of each workgroup on the CPU only, for determinism
(GPUs start with stale data, so portable shaders must initialize shared
memory before reading it).
The JIT takes a workgroup of at most 8 invocations whatever its program
contains: it fits one batch, which runs in the interpreter's order
(barrier() has nothing to wait for, atomics apply lane by lane in the same
order). Larger workgroups run in the JIT only without barrier() (every
batch would have to reach it before any passes) and without atomics (their
returned values, and the results of exchange, compare-and-swap and mixed
operations, follow the order lanes apply them); those programs stay on the
interpreter. When a shader on the interpreter uses barrier(), each 64-lane
chunk keeps its own register and mask slice in Scratch (sized once from
workgroup size and slot count, with no per-barrier allocation) while chunks
advance in lockstep across every barrier, including inside loops and across
early returns. A dispatch with an image whose texels reach past its first
2^31 bytes runs on the interpreter (the x86-64 JIT's gathers take signed
32-bit offsets; arm64 keeps the same rule).
Within one run_compute call, on one thread, lanes execute in a fixed
order, (batch, then lane) in the JIT and (chunk, then lane) in the
interpreter, so runs are deterministic for a given build. When a dispatch is
split across a worker pool, buffer atomics from different threads use host
atomic instructions and interleave by thread timing, in the JIT and the
interpreter alike (out-of-bounds buffer atomics return 0 without writing).
GPU invocation and atomic order are unspecified, so portable shaders
establish output order via prefix scans rather than atomic append order.
Unsynchronized non-atomic writes to the same word or texel have unspecified
results. In the JIT, as on GPUs, an invocation that reads a word, texel or
shared element another invocation of its workgroup writes without
synchronization may see the value from before or after that write, and of
two such writes either may stay; apart from that and the differences every
stage has (see JIT below, and there the arm64 JIT's min, max and
clamp), the JIT matches the interpreter bit for bit.
texture in a fragment shader passes the sampler the level a GPU picks:
0.5 * log2(max(|duv/dx|², |duv/dy|²)) in the channel's texels
(Run_Options.channel_sizes), one per quad from its top row and left
column, plus the bias (within 2e-6 levels and the level's own rounding to
f32, exact where the squared length is a power of 4: a short f32
polynomial for the log2, which every callback waits for). It is fractional and below 0 where magnified (-inf
where uv is constant), so the sampler clamps it to the levels it has; a
channel without a size samples at the bias. GPUs approximate the level
differently (on a bent mapping radv and Apple pick up to 0.17 levels
higher), and where uv jumps inside a quad (a fract seam) which pixels
they difference decides it; tools/gpu_parity samples a mip chain to
show both.
texelFetch of a channel without an image calls the sampler only inside
a full mip chain of the channel's channel_sizes size w x h (level l
is max(w >> l, 1) x max(h >> l, 1) while max(w, h) >> l is not 0), or
its first n levels when Run_Options.channel_levels gives the channel
n > 0 (at most 16, as a bound image's; 0, or a channel past the slice,
is the full chain), and its layers, with the texel's centre in its level
((p + 0.5) / size, flipped in Shadertoy), the lod and p.z; anywhere
else it reads (0, 0, 0, 0) without a call, as a GPU does and a bound
image does. A channel without a size reads 0. The CPU takes the full
chain unless told otherwise, so a host whose GPU texture has fewer levels
sets channel_levels to its num_levels: with one level (num_levels = 1, as many hosts create textures), texelFetch(s, p, 1) reads 0 on the
GPU and, without channel_levels, the callback's texel on the CPU.
channel_levels is texelFetch's only: texture, textureLod and
textureGrad pass the sampler their level whatever it is, for the host to
clamp to the levels it has. channel_levels is validated once per run
(ensure: each from 0 to 16). In a fragment shader every lane of a quad
with a running lane fetches, as a GPU's helper invocations do, so
derivatives of the result are the quad's; a compute shader's running
invocations alone fetch. (Before v0.0.25 the callback got every fetch, out
of range included, with the uv and lod to wrap or clamp, and Shadertoy's
uv came from iChannelResolution, level 0's size, at every lod.)
For images the caller owns, Run_Options.channel_images ([]Channel_Image,
indexed by channel) binds a channel's texels directly to any run* entry
point, sampled in the JIT (AVX2 gathers on x86-64, a load per lane on
arm64) and the interpreter without calling sampler per lane:
// f32 maps, one level, clamped (as before): []f32, [][2]f32 or [][4]f32
oksl.channel_image(texels, width, height, .Linear)
// any format, wrap and mip chain (levels: []Channel_Level the caller owns,
// each oksl.channel_level(texels, width, height))
oksl.Channel_Image{format = .Rgba8, pixels = rgba_bytes, width = w, height = h,
filter = .Linear, wrap = {.Repeat, .Clamp}, levels = levels[:]}- Formats:
.F32(1, 2 or 4 floats a texel, indata), and inpixels:.Rgba8and.Gray8(byte / 255),.Gray16(little-endianu16 / 65535),.Rgba16f(IEEE halves; a NaN, like any, is 0x7fc00000 wherever it reaches the host). Missing components read(0, 0, 0, 1): the Gray formats are(g, 0, 0, 1). Nothing is decoded from sRGB: the shader decodes what it filters, as a GPU does with a_UNORMtexture (bind the GPU texture as_UNORM, not_UNORM_SRGB, for the same values). Rows arestridebytes apart (0: tightly packed). - Addressing:
wrapper axis,{u, v}:.Clampclamps the texel index to the edge,.Repeatwraps it (floored modulo), so repeating in u and clamping in v (an equirectangular map) is{.Repeat, .Clamp}. Bound images are addressed as the GPU addresses a texture: uv (0, 0) is the first texel of the first row, no flips. - Filtering, one rule for every format (measured against RADV,
tools/gpu_parity'sbound_formats): the coordinate is scaled to the level's texels exactly, in f64 (x = u * size, minus 0.5 for.Linear)..Nearestreads the texel atfloor(x)..Linearblends the four around it by each axis's fraction rounded to 1/256, to nearest even (257 steps, the 8 bits of GPU filtering), in f32 asa + (b - a) * t: the row atfloor(y)across x, the next row across x, then the two across y, on the texels' stored values (bytes and u16 as integers); the unsigned normalized formats are divided by 255 or 65535 last. On RADV this is within 3e-7 of the GPU for every format but Rgba16f (which RADV filters in less than f32's precision: within 1e-3), and exact for 49-100% of components (.Nearest: all). Apple GPUs (Metal, M4) filter differently: they round the lod to a half float and blend levels by its fraction truncated to 1/64, round texel weights half up from an f32u * n - 0.5, and return a filtered 8-bit texel to 1/16 of a step, Gray16 to a step and halves to a half. So on Metal the worst distance is about 3.9e-3 for the unorm formats'.Linearand 0.031 for Rgba16f's, where RADV is within 3e-7 and 1e-3 (the parity check's tolerances follow). A NaN coordinate reads index -2^31 (clamped: the first texel) with weight 0. - Levels:
levelsholds levels 1 and up (max(width >> l, 1) x max(height >> l, 1)each, at most 16 in all), as the caller built them. texture() takes its bias plus the level the quad's derivatives pick in level 0's texels (as the callback gets it), textureLod and textureGrad theirs. A lod not above 0 (NaN included) reads level 0; otherwisel = min(lod, levels - 1)reads levell0 = trunc(l), blended towardl0 + 1asc0 + (c1 - c0) * w / 256withwthe fractionl - l0rounded to 1/256 (to nearest even), as GPUs blend levels. - texelFetch reads its level's texel,
(0, 0, 0, 0)for a level or texel out of range (flippingyin the Shadertoy profile), as the GPU backends do whatever the sampler; textureSize gives levelclamp(lod, 0, levels - 1)'s size (auintlod clamped unsigned, so0x80000000uand up give the top level).
Since v0.0.21 the rule changed for .F32 images too: .Linear weights are
rounded to 1/256 and the coordinate scaled exactly (before: unrounded
weights from the f32 product), .Nearest floors the exact product (before:
the f32 one, which picks the next texel where it rounds up to a whole
number), and texelFetch past the one level reads 0 (before: level 0). On
RADV the f32 linear error falls from 2e-2 to 6e-7 (values in [-4, 4]).
On the GPU the host binds a texture with the matching sampler: the same
format as _UNORM or _FLOAT, CLAMP_TO_EDGE or REPEAT per axis,
NEAREST or LINEAR min and mag filters, mipmap_mode = LINEAR with the
same levels uploaded (so .Nearest with levels still blends between two
levels, on the CPU as on the GPU), max_lod at or above the top level
(SDL_GPUSamplerCreateInfo's zero default pins every sample to level 0;
tools/gpu_parity sets 1000), and no anisotropy (texelFetch takes none of
it). A textureSize lod
outside the levels (below 0 or past the top) differs: the CPU clamps it,
GPU backends give 0 or an undefined size. Bindings are validated up front via ensure (layers only on a
sampler2DArray channel, components, format, filter and wrap values,
dimensions, strides, layer strides, level sizes and counts, data lengths,
2-byte alignment for Gray16 and Rgba16f, 4-byte for F32 levels). An entry
with neither data nor pixels, or past len(channel_images), stays
unbound and calls Run_Options.sampler (sRGB-decoding textures still need
it), and bound and unbound channels may mix in the same pass.
Layers. A sampler2DArray channel binds a Channel_Image with
layers (0 or 1: one), each layer the same size, format, wrap and levels,
layer i of each level i * layer_stride bytes after the level's first
texel (Channel_Image.layer_stride for level 0, Channel_Level.layer_stride
for the others; 0: right after the layer before, height rows on):
// o3d's frame map: the light and the runs, each a whole chain, one after
// the other in one table of halves.
oksl.Channel_Image{format = .Rgba16f, pixels = light_bytes, width = w, height = h,
filter = .Linear, levels = levels, layers = 2, layer_stride = chain_bytes}A sample reads layer clamp(round_even(r), 0, layers - 1) for its layer
coordinate r, NaN as 0: what RADV reads at every tie from -8 to 20, a
few ulps and 2^-1 to 2^-24 either side of each, NaN, the infinities and
huge values (tools/gpu_parity's bound_layers; GLSL ES 3.10's `floor(r
- 0.5)
differs at 0.5, 2.5, ...). It is the layer the sampler callback gets, clamped to the layers.texelFetchreads layerp.z,(0, 0, 0, 0)outside[0, layers)as for a texel outside its level;textureSize's z islayers`. A 2D image is the one-layer case of the same path in both engines; images with layers always take the general one (in the JIT the general sampling and fetch subroutines), while one-layer images keep the one-level shortcuts.
Building the levels. channel_build_levels(im) fills im.levels
from level 0 as SDL_GPU's GenerateMipmapsForGPUTexture does, each level
from the one above and each layer on its own, into levels the caller owns
and sizes, allocating nothing:
n := oksl.channel_level_count(w, h) // the whole chain, at most 16
buf := make([][4]f16, oksl.channel_levels_bytes(.Rgba16f, 0, w, h, n, layers) / 8)
levels := make([]oksl.Channel_Level, n - 1)
oksl.channel_levels_layout(levels, buf, .Rgba16f, 0, w, h, layers)
im := oksl.Channel_Image{format = .Rgba16f, pixels = level0, width = w, height = h, layers = layers, levels = levels}
oksl.channel_build_levels(im)channel_levels_layout takes the texels as any slice type: allocated as
[][4]f16 (as here), []u16 or []f32, they are aligned as the format
reads them (2 bytes for Gray16 and Rgba16f, 4 for F32) on any allocator,
where a []u8 from an arena or context.temp_allocator may start at any
byte and fails the layout's alignment check.
Texel (x, y) of a w x h level reads its sw x sh parent at its
centre's coordinate, (x + 0.5) * sw / w - 0.5 exactly (likewise y), the
four texels around it clamped to the edge, blended by each axis's fraction
rounded to 1/256 to nearest even (the sampling rule's weights), exactly,
on the texels as the GPU reads them (byte / 255, u16 / 65535, halves,
floats), rounded once to f32 and stored: F32 as it is, Rgba16f to the
nearest half (even), the unsigned normalized formats round_even(v * 255) (65535). Even sizes come out as the 2x2 box; odd ones spread each
level over its whole parent. Chosen against RADV's
GenerateMipmapsForGPUTexture (tools/gpu_parity's built_levels, each
level built from the GPU's level above, every format at even, odd and
1-pixel sizes up to 1280 x 720):
| format | exact | within one step | worst |
|---|---|---|---|
| Rgba8, Gray8 | 87% | 100% | 1 step |
| Gray16 | 97% | 100% | 1 step |
| Rgba16f | 67% | 96% | 2.0e-3 of the largest parent |
| F32 (1, 2, 4) | 99.7-99.9% | 99.9% | 4e-7 of the largest parent |
The misses are RADV's: its 8-bit filtering keeps fewer bits, so where
the exact blend lies just above a half step it often stores the one
below; it filters halves in less than f32's precision and writes them
rounded toward zero (79% exact with that rounding; the builder rounds
to nearest even, as the CPU's rgba16f stores do); at large odd sizes (1023 x 767) its interpolated
coordinates miss a few centres that lie within 1/500 of a weight step's
tie, one weight step off. On the same sizes the alternatives measured
worse: a 2x2 box (8 bits 86% exact but up to 151 steps off at odd sizes,
F32 92.5%), o3d's blit imitation (f32 (x + 0.5) * sw / w - 0.5, weights
rounded half away from zero, a * (1 - t) + b * t: 8 bits 84.6%, Gray16
93.8% with a 227-step miss, F32 95.4%; halves the same 66.5%), and the
sampling rule's own f32 a + (b - a) * t on stored values (8 bits 88%,
a point better, but Gray16 88% and F32 87.6%). Rounding weights half away
from zero differs only at exact ties, which RADV rounds to even (513 x 3
-> 256 x 1 is all ties). SDL 3.4's Vulkan path leaves a level as it was
when width >> l or height >> l is 0 (37 x 23's last level, 1280 x
720's 1 x 1, every level of a 1 x n image): the builder makes those as
it makes the others, and built_levels lists and skips them.
- Inlining: every function is inlined into one flat
[]Instrprogram over SoA registers. A slot is one scalar component forLANES(64) lanes: 16 2x2 quads, an 8x8 block of the layer, so each instruction dispatched works on 64 pixels and neighbouring pixels diverge little. Variables and consecutive swizzles of them (.xy,.rgb) are read in place; a call keeps a return mask only when areturncan leave the function early. - Dispatch: one switch per instruction, never per lane. Arithmetic,
comparisons, conversions, the float built-ins and the vector and matrix
ones (
dot,normalize,cross,reflect, products; notdeterminantandinverse) run as whole-register loops, each specialized at compile time ($parameters andwhen), so no lane loop branches on the operation. Execution masks arebit_sets of lanes. Masked stores and selects are branchless, andflooravoidscore:math's modf. - JIT: on x86-64 Linux and macOS when the CPU has AVX2, and on arm64
Linux and macOS,
compilealso translates vertex and fragment programs into 8-lane native code (two 2x2 quads per 256-bit YMM register of AVX2, or per pair of 128-bit NEON registers) in W^X pages (on x86-64 and Linux allocated read-write, switched read-execute; on macOS arm64 aMAP_JITmapping written with the thread's JIT write protection off; released bydestroy), and compute programs into 8 consecutive invocations per batch (seerun_computeabove for which ones). Compute shaders withbarrier()or atomics in workgroups of more than 8 invocations, other targets (Windows among them), machines without AVX2, environments that refuse executable memory (PROT_EXEC), and builds with-define:OKSL_JIT=falserun on the 64-lane interpreter. The x86-64 JIT gives the interpreter's results bit for bit, NaNs included (see Precision). The arm64 JIT takes NEON's own floatmin,maxandclamp(fminnmandfmaxnm) wherever they occur, the implicit ones included (the Shadertoy wrapper's clamp of its colour to [0, 1], SkSL'ssaturate, and themaxof the squared derivatives that pickstextureGrad's level): a quiet NaN operand gives the other one (the interpreter'smin(NaN, y)is NaN), a signaling NaN gives NaN, soclamp(sNaN, lo, hi)ishi, and-0.0counts below+0.0(clamp(-0.0, 0.0, 1.0)is+0.0); a NaN derivative passestextureGrad's level from the other one to thesampler. Every other operation rounds as the interpreter's (no fused multiply-add) and gives its bits, and NaNs reaching the host or an integer are canonical as everywhere;-define:OKSL_JIT=falsegives the interpreter, identical on every platform. In compute both JITs can also differ from the interpreter in the outcome of unsynchronized accesses (undefined on GPUs too). Lanes that aren't running compute their own values: a variable, parameter or return value takes its first value in every lane (its initializer; 0 for one without an initializer, a declaration directly in aswitchbody, a?:result, and the result of a function that can return early) and later writes only in the lanes that run them, so what the lanes of a sampled quad that aren't running pass asamplercallback, and the derivatives andtexturelevel that read them, are the same in both. Signed zeros agree (in the x86-64 JIT; arm64's are above):clampis GLSL'smin(max(x, lo), hi)withmax(x, y)=x < y ? y : x, soclamp(-0.0, 0.0, 1.0)is-0.0, and a NaN operand gives the other one. CI runs the tests and goldens both ways and requires identical output. - Uniform work: what follows from constants and uniforms alone moves
to the front of the program and runs once per run, before the batches,
even from inside loops and branches: a raymarcher's
rot(iTime)is computed once rather than at every step of every batch. An instruction moves when its op reads only its operands (not texture samples, derivatives or dynamic indexing), its operands are such values, and nothing else writes its registers; variables are written only by stores, so their registers are never a moved instruction's. - Divergence: divergent control flow runs every path under execution
masks (break, continue, return and discard masks per construct; a
switchlets each label's lanes join the running ones). Only stores to variables honour the mask, so helper lanes keepdFdx/dFdy(fine derivatives) correct. Discarded pixels are left untouched. - Precision: f32 throughout, matching GPU semantics: GLSL
mod, C integer division and remainder, guarded division by zero and float-to-int conversion, and shift amounts masked to 31. - The same bits everywhere: the CPU's output is bit-identical on
x86-64 and arm64, on Linux, macOS and Windows, in the interpreter and
the x86-64 JIT (and in the arm64 JIT but for its
min,maxandclampof NaNs and signed zeros, under JIT; in IEEE 754's default environment: round to nearest, subnormals kept; a host that sets flush-to-zero changes results). No float built-in calls the platform's libm:sin,cos,tan,asin,acos,atan(both forms),sinh,cosh,tanh,asinh,acosh,atanh,exp,exp2,log,log2andpoware oksl's own (vm_math.odin; thetexturelevel'slog2too, above): eight lanes at a time in f32 with IEEE 754's basic operations only (no fused multiply-add, which Odin never contracts into), at a GPU's accuracy and within the Vulkan spec's bounds for GLSL.std.450: over every f32 argument,exp,exp2andlogwithin 1.3 ulp,sinandcoswithin 1.6 ulp on [-pi, pi] and 2.5 ulp out to 6434 (then within about half the argument's own ulp to 10^5; Cody-Waite reduction, no 2/pi table),tan3.7 ulp on [-pi, pi],atan1.8 ulp andatan(y, x)1.9,asin,acos,log2and the hyperbolic functions 3 ulp, andpowwithin 1.5 + 3 * |y * log2(x)| ulp, asexp2(y * log2(x))on a GPU (pow(x, 2.0)isx * x), withpowandatan(y, x)following C99's special cases. A NaN's sign and payload depend on the CPU (x86 makes0xffc00000, arm640x7fc00000) and on the operand order a compiler picks, so wherever a float's bits reach the host or an integer they are canonical: every NaN in a target, arun_vertexposition or varying, a storage buffer or image store, asamplercallback'suvorlod, and every NaNfloatBitsToIntorfloatBitsToUintsees is0x7fc00000(anrgba16ftexel's0x7e00). Inside a shader NaNs propagate as the CPU makes them, which nothing observes. A signaling NaN (fromuintBitsToFloat, a uniform, a buffer, an image or a callback) gives what the same NaN quiet gives, everywhere but in the arm64 JIT'smin,maxandclamp(JIT): thefmaxnmandfminnmLLVM makes of some of oksl's clamps and selects on arm64 (which quiet a signaling NaN and return it, not the other operand) each take values arithmetic, a canonicalization or a+ 0has already quieted, but foratan's, whose NaN lanes the result overrides, so none changes a result.
Data-oriented throughout:
- Flat arrays: tokens, syntax, symbols, functions and struct fields
are flat arrays of plain structs in one
Unit, referenced by integer ids (Expr_Id,Stmt_Id,Sym_Id, ...). Child lists are ranges into one id array. - Types: interned in
Unit.types(Type_Id). - Annotations: the checker annotates expressions in place by index and
adds
Convertexpressions instead of rewriting trees. - Dialects, profiles and stages are data:
DIALECT_RULES(the language's spelling: SkSL or GLSL),PROFILE_RULES(a host's conventions on a dialect: SkSL effects, Shadertoy, GLSL fragment shaders, with their entry points, predeclared inputs, uv flip and macros) andSTAGE_RULES(the pipeline stage: SPIR-V execution model and modes, SDL_GPU descriptor sets, the Metal qualifier, location limits). A feature is available when the dialect has it and neither the profile nor the stage takes it away, and each table says what using a missing one reports. The shared passes consult them; there is no per-dialect code path or class hierarchy.SOURCE_EXTENSIONSmaps the tools' file extensions to profiles and stages. - Inputs are a table:
INPUTS(name, type, block offset or binding) drives SkSL's uniform binding, GLSL's predeclarations, the block layout every backend emits and the host'swrite_input. - Built-ins and operators are tables:
BUILTINSgives each built-in its name, argument count, argument rule, result rule and the arguments that broadcast from scalars; the checker types every call from it. Each backend lowers from its own table indexed by built-in (or operator) and operand base:VM_BUILTINS/VM_BINOPS/VM_CONVERT,SPV_EXT_BUILTINS/SPV_OP_BUILTINS/SPV_BINOPS/SPV_CONVERT,MSL_BUILTINS, with a short hand-written list for the few that are not one instruction or call. - The stage is IR plus a table: the checker synthesizes the entry
point (
stage.odin: the layer coordinate,sk_FragCoord, global initializers, a vertex shader's taps, the call tomain) as ordinary IR, a tap being a copy of the statements its position depends on, and lists what it reads and writes inChecked.interface(stage inputs and outputs, the uniform block, the channels, with locations, sets and bindings). Backends declare those rows and emit the entry like any other function. - Errors are values:
Erroris a position, anError_Codeand plain operands;ERROR_TEXTmakes the message only informat_errors/error_message. - Backends: keep per-id scratch arrays (SPIR-V ids, register slots) rather than fields on nodes.
- Memory: a compile allocates from one arena owned by the
Module, released bydestroy(along with any executable pages the JIT mapped); the preprocessor expands into a scratch arena of its own.
The pipeline: lexer.odin (tokens) -> preprocess.odin (macro table
indexed by id, a frame stack for rescans, flat tokens out) -> parser.odin
-> check.odin (names, types, lowering, dialect.odin's rules, the
inputs.odin and builtins.odin tables, the Shadertoy entry adapter in
shadertoy.odin, the stage entry and interface in stage.odin, both
built with nodes.odin) ->
spirv.odin / spirv_emit.odin, msl.odin, dxbc.odin / dxbc_emit.odin
and vm.odin / vm_run.odin / vm_jit.odin.
errors.odin holds the error codes and their text. switch reaches each
backend natively: SPIR-V as OpSwitch (fallthrough as the following
labels' code, since structured SPIR-V only falls into the next operand),
MSL as switch, DXBC as switch with each case's code from its label
to the end (no case falls into another), the interpreter under masks.
program.odin builds multipass programs on these pieces: one
Preprocessor runs Common, marks its macro table and resets to the mark
for each pass (preprocess_unit / preprocess_mark / preprocess_reset);
Common is parsed into one Unit whose syntax arrays seed each pass's unit
(unit_copy_syntax), and each pass is checked, with the entry adapter,
and emitted like a single compile.
odin test . -vet -strict-style # SkSL, GLSL/Shadertoy, the preprocessor, diagnostics,
# built-ins on the CPU, control flow and switch, discard,
# uniforms, children and channels, programs, corpus
# (+ spirv-val, and vkd3d for DXBC, when installed)
odin test . -vet -strict-style -define:OKSL_JIT=false # force the portable interpreter
odin run tools/gpu_parity -- out_dir # SDL_GPU vs CPU interpreter on testdata/ through the layer vertex shader, and a tap of it
odin run tools/d3d12_parity -- out_dir # the same checks (compute too) with the DXBC through Direct3D 12 on vkd3d (Linux)
# or on WARP under the debug layer and GPU-based validation (Windows;
# -hardware: the first hardware adapter), and the DXBC emitter's
# own cases (tools/parity: the shared CPU side)
odin run tools/okslc -- a.sksl b.glsl ... # compile (by extension: SOURCE_EXTENSIONS); -o prefix writes .spv / .metal / .dxbc
odin run tools/cpu_render -- shader.sksl out.png # CPU render
odin run tools/golden -- snapshot ref # before a refactor: ~95k generated cases + every shader
odin run tools/golden -- compare ref out # after (snapshot out first): what changed, by kind
odin check . -no-entry-point -target:darwin_arm64testdata/ holds representative shaders across SkSL (.sksl), Shadertoy
code (.glsl), GLSL fragment (.frag) and compute (.comp) shaders, and
the layer vertex shader in GLSL (layer.vert): gradients, value noise and fbm, SDF raymarching, a
textured tunnel, swizzles, out parameters, structs and arrays, defines,
derivatives, premultiplied alpha, SkSL types and built-ins, matrices,
integer hashing, loops, uniforms, ternaries and short-circuiting,
matrix comparison, children, storage buffers, RGBA-to-NV12 conversion,
storage images, explicit-LOD compute sampling, workgroup shared reductions,
histograms, prefix-scan cell binning, integer atomics and bound float channels, and Shadertoy-style snippets (st_*.glsl) with function-like
macros, texture / texelFetch / textureSize, switch and discard.
- Stages: fragment, GLSL vertex and GLSL compute shaders, on the GPU
and the CPU (
run_vertex,run_fragment,run_compute). Compute shaders withbarrier()or atomics in workgroups of more than 8 invocations run on the 64-lane interpreter rather than the JIT. Compute capssharedworkgroup memory at 16,384 bytes (the GLSL ES 3.10 minimum), and omitsatomic_uintcounters (Vulkan disallows SPIR-V'sAtomicStoragecapability) andimageAtomic*(outside GLSL ES 3.10 core). Storage images and writable storage buffers are compute-only. Programs run their passes as fragment shaders and the host owns the float targets and swaps them each frame. GLSL shaders have nogl_FragDepthorgl_InstanceID(draw instances as vertex ranges and dividegl_VertexID), no user uniform blocks, and no array stage variables. - MSL is compiled only on macOS: Metal has no Linux compiler, so on
Linux the emitter is checked textually; on macOS
tools/gpu_parityruns the MSL through SDL_GPU's Metal driver against the CPU interpreter. - DXBC, not DXIL: Direct3D 12 takes the shaders as DXBC (SM5.1); a
compute shader reading
gl_NumWorkGroupsneeds the count in a uniform (Options.num_work_groups_uniform). The DXBC is checked with vkd3d (Wine's D3D12 over Vulkan:vkd3d-dxbc,vkd3d-compilerandtools/d3d12_parity) and on Windows' own runtime with WARP, its software device, under the debug layer and GPU-based validation (tools/d3d12_parity), not yet on vendor drivers. - Not supported: struct uniforms, arrays of arrays,
colorFilter/blenderchildren; in GLSL, cubemap and 3D samplers, arrays of samplers and Shadertoy's keyboard, sound and webcam inputs. Children and channels are images bound by the host (no shader trees);sk_FragCoordis layer-local. - Precision: transcendental functions differ by a few ulps between
GPU and CPU, and thresholds (
step, comparisons) right at such values can flip.tools/gpu_parityreports these as threshold edges. - Runaway loops: the interpreter has no iteration cap, so a shader that loops forever hangs it, as it would hang a GPU.
- Uniform blocks past 4 KB on Vulkan: SDL_GPU's Vulkan backend binds
4,096 bytes of each uniform push (
MAX_UBO_SECTION_SIZEin SDL 3.4), so a larger block (Module.block_size) reads zeros beyond it there, with no error; Metal and the CPU see all of it. Put large tables in storage buffers.
What would make oksl useful well beyond onimite:
- DXIL / HLSL output for D3D12, SDL_GPU's preferred driver on Windows.
- WGSL output for WebGPU and browsers.
- A loop iteration cap (and SkSL's ES2 loop rules enforced) so untrusted shaders can't hang the CPU interpreter.
MIT, see LICENSE.
The mascot, a firefly whose lantern is the shader, is drawn by tools/mascot
(odin run tools/mascot -- assets): assets/logo.svg keeps its lantern (lit or
out), two glow halos, eyes and mouths as layers a script can switch by id,
each one path per colour, and a hidden silhouette: the whole firefly as one
outline, to morph, extrude or collide.
