UNPKG

@thi.ng/shader-ast-optimize

Version:

Shader AST code/tree optimization passes/strategies

91 lines 2.58 kB
import type { Maybe } from "@thi.ng/api"; import { type FnCall, type Term } from "@thi.ng/shader-ast"; /** @internal */ export declare const foldNode: import("@thi.ng/defmulti/api").MultiFn1<Term<any>, Maybe<boolean>>; /** * Similar to {@link foldNode}, but specialized for function calls of builtin's * (aka `call_i` AST nodes). * * @remarks * Currently, implementations are only dealing with these builtins: * * - exp2 * - pow * * This function delegates based on the function name of the builtin and is * extensible, i.e. custom optimizations can be added by calling * `foldBuiltin.add("functionname", (node) => ...)`. * * @internal */ export declare const foldBuiltin: import("@thi.ng/defmulti/api").MultiFn1<FnCall<any>, Maybe<boolean>>; /** * Traverses given AST (potentially several times) and applies constant folding * optimizations where possible. Returns possibly updated tree (mutates * original). * * @remarks * Currently, only the following operations are supported / considered: * * - scalar math operators * - scalar math built-in functions * - single component vector swizzling * - literal hoisting * * @example * ```ts tangle:../export/constant-folding.ts * import { * add, defn, float, mul, neg, ret, scope, vec2, $x, $y * } from "@thi.ng/shader-ast"; * import { targetGLSL } from "@thi.ng/shader-ast-glsl"; * import { constantFolding } from "@thi.ng/shader-ast-optimize"; * * // function def * const foo = defn("float", "foo", ["float"], (x) => [ * ret(mul(x, add(neg(float(10)), 42))) * ]); * * const bar = vec2(100, 200); * * // program def * const prog = scope([ * foo, * foo(add(float(1), float(2))), * foo(add($x(bar), $y(bar))) * ], true); * * // GLSL codegen * const glsl = targetGLSL(); * * // unoptimized AST as GLSL (see section above) * console.log(glsl(prog)); * // #version 300 es * // float foo(in float _s0) { * // return (_s0 * ((-10.0) + 42.0)); * // } * // foo((1.0 + 2.0)); * // foo((vec2(100.0, 200.0).x + vec2(100.0, 200.0).y)); * * // with constant folding * console.log(glsl(constantFolding(prog))) * // #version 300 es * // float foo(in float _s0) { * // return (_s0 * 32.0); * // } * // foo(3.0); * // foo(300.0); * * const expr = mul(float(4), $x(vec2(2))) * * console.log(glsl(expr)) * // (4.0 * vec2(2.0).x) * * // optimize single expression * console.log(glsl(constantFolding(expr))) * // 8.0 * ``` * * @param tree - */ export declare const constantFolding: (tree: Term<any>) => Term<any>; //# sourceMappingURL=constant-folding.d.ts.map