constExpr
On this page

constExpr()

Function in Authoring

Author a module-level constant from an IR value expression: the form for a constant that is not a plain scalar.

import { constExpr } from 'typeshade'

The signature, the description and the examples come from the compiler's own source at commit 26de7be8.

Syntax

function constExpr<T extends ShaderType>(
name: string,
type: T,
value: Node,
): ConstExprDecl<T>

Parameters

name string

the emitted constant name, and the name every reference spells.

type T extends ShaderType

the constant’s shader type, emitted as its declared type.

value Node

a constant-foldable literal node holding the value.

Return value

ConstExprDecl<T>

the ConstDecl to put in module({ consts }), carrying .node.

Description

value is any constant-foldable literal node, a vec4(...), an arrayLit(...), a struct constructor. It emits const <name>: <type> = <value>; on both WGSL and GLSL ES 3.00, and the CPU oracle, the same module run in double precision on the CPU, evaluates the same expression, so all three agree on the value.

A scalar constant is the other form. constDecl takes a { wgsl, cpu } pair and writes them into a ConstDecl’s wgslValue and cpuValue: the shader gets the spelling you want in the source, often a truncated one such as 3.14159265, while the oracle evaluates the full double. constExpr has no such split, because a folded literal node carries one value for both.

The declaration carries .node, the typed reference to read it through, so the name is written once. Without it a reader is spelled constRef('SKY', vec4fT) — a string the type checker never compares against the declaration, and a second copy of the type, so a rename or a retype is silent at every call site until the GPU compiler sees it.

Examples

Example

import { constExpr, arrayLit, arrayT, vec4, vec4fT } from 'typeshade'
const SKY = constExpr('SKY', vec4fT, vec4(0.4, 0.6, 0.9, 1))
const PALETTE = constExpr('PALETTE', arrayT(vec4fT, 2), arrayLit(vec4fT, c0, c1))
const bg = fn('bg', {}, () => SKY.node) // no constRef('SKY', vec4fT)
const m = module({ consts: [SKY], funcs: [bg] })

In the guide

See also

Source

src/core/ir/builder.ts, line 1383, at commit 26de7be8

Edit this page Report a problem