0.18.14 • Published 10 days ago

@thi.ng/shader-ast-stdlib v0.18.14

Weekly downloads
234
License
Apache-2.0
Repository
github
Last release
10 days ago

shader-ast-stdlib

npm version npm downloads Twitter Follow

This project is part of the @thi.ng/umbrella monorepo.

About

Function collection for modular GPGPU / shader programming with @thi.ng/shader-ast.

A growing collection (currently ~170) of useful functions & higher order constructs (incl. meta programming approaches) for GPU / shader programming, acting as optional standard library for @thi.ng/shader-ast based workflows.

These functions can be imported like normal TS/JS functions and (in TS) are fully type checked.

Some of the functions have been ported from GLSL:

  • Signed Distance Field primitives and operations are based on work by Inigo Quilezles (iq), HG_SDF (Mercury).
  • Hash functions (PRNGs) by Dave Hoskins
  • Noise functions by Ashima Arts / Stefan Gustavson
  • Various other functions ported from thi.ng/shadergraph, thi.ng/vectors, thi.ng/matrices, thi.ng/color, thi.ng/dsp

Reference:

Status

STABLE - used in production

Search or submit any issues for this package

Related packages

Installation

yarn add @thi.ng/shader-ast-stdlib

ES module import:

<script type="module" src="https://cdn.skypack.dev/@thi.ng/shader-ast-stdlib"></script>

Skypack documentation

For Node.js REPL:

# with flag only for < v16
node --experimental-repl-await

> const shaderAstStdlib = await import("@thi.ng/shader-ast-stdlib");

Package sizes (gzipped, pre-treeshake): ESM: 7.18 KB

Dependencies

Usage examples

Several demos in this repo's /examples directory are using this package.

A selection:

ScreenshotDescriptionLive demoSource
2D canvas shader emulationDemoSource
Evolutionary shader generation using genetic programmingDemoSource
HOF shader procedural noise function compositionDemoSource
WebGL & JS canvas2D raymarch shader cross-compilationDemoSource
WebGL & JS canvas 2D SDFDemoSource
WebGL & Canvas2D textured tunnel shaderDemoSource
Fork-join worker-based raymarch renderer (JS/CPU only)DemoSource
Minimal multi-pass / GPGPU exampleDemoSource
Shadertoy-like WebGL setupDemoSource
WebGL screenspace ambient occlusionDemoSource

API

Generated API docs

Basic Lambert shader

Below is a brief demonstration of a fully defined shader pair, implementing basic diffuse lighting:

import { assign, defMain, vec4 } from "@thi.ng/shader-ast";
import { diffuseLighting, halfLambert, transformMVP } from "@thi.ng/shader-ast-stdlib";
import { shader } from "@thi.ng/webgl";

// obtain WebGL/WebGL2 context
// the generated shader code will automatically target the right GLSL version
const gl = ...

// transpile & instantiate fully working shader
const myShader = shader(gl, {
    // vertex shader fn
    // given args are symbolic uniforms, attribs, varyings & GL builtin vars
    // here `ins` are vertex attribs and `outs` are "varying"
    vs: (gl, unis, ins, outs) => [
        defMain(() => [
            assign(outs.vnormal, ins.normal),
            assign(gl.gl_Position, transformMVP(ins.position, unis.model, unis.view, unis.proj)),
        ])
    ],
    // fragment shader fn
    // here `ins` are "varying" & `outs` are output variables
    fs: (gl, unis, ins, outs) => [
        defMain(() => [
            assign(
                outs.fragCol,
                vec4(
                    diffuseLighting(
                        halfLambert(normalize(ins.vnormal), unis.lightDir),
                        unis.diffuseCol,
                        unis.lightCol,
                        unis.ambientCol
                    ),
                    1
                )
            )
        ])
    ],
    // attribs w/ optional location info
    attribs: {
        position: ["vec3", 0],
        normal: ["vec3", 1]
    },
    varying: {
        vnormal: "vec3"
    },
    // uniforms with optional default values / functions
    uniforms: {
        model: "mat4",
        view: "mat4",
        proj: "mat4",
        lightDir: ["vec3", [0, 1, 0]],
        lightCol: ["vec3", [1, 1, 1]],
        diffuseCol: ["vec3", [0.8, 0, 0]],
        ambientCol: ["vec3", [0.1, 0.1, 0.1]]
    }
});

Generated vertex shader

The #defines are auto-injected by default, but can be disabled / customized / replaced...

#version 300 es
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp int;
precision highp float;
#else
precision mediump int;
precision mediump float;
#endif
#ifndef PI
#define PI 3.141592653589793
#endif
#ifndef TAU
#define TAU 6.283185307179586
#endif
#ifndef HALF_PI
#define HALF_PI 1.570796326794896
#endif

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
uniform vec3 lightDir;
uniform vec3 lightCol;
uniform vec3 diffuseCol;
uniform vec3 ambientCol;
layout(location=0) in vec3 position;
layout(location=1) in vec3 normal;
out vec3 vnormal;
void main() {
vnormal = normal;
gl_Position = ((proj * (view * model)) * vec4(position, 1.0));
}

Generated fragment shader

The fragColor output variable is auto-created by @thi.ng/webgl if no other output vars are defined. For WebGL v1 this is defined as an alias for gl_FragColor...

#version 300 es

/* (omitting #define's for brevity, same as in VS) */

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
uniform vec3 lightDir;
uniform vec3 lightCol;
uniform vec3 diffuseCol;
uniform vec3 ambientCol;
in vec3 vnormal;
layout(location=0) out vec4 fragColor;
void main() {
fragColor = vec4((((lightCol * ((dot(normalize(vnormal), lightDir) * 0.5) + 0.5)) * diffuseCol) + ambientCol), 1.0);
}

Using higher order functions

Several of the functions included here are defined as higher-order functions, providing powerful functional compositional features not usually seen in shader code and not easily achievable via the usual string templating approach used by most other GLSL libraries.

For example, the additive() HOF takes a single-arg scalar function and a number of octaves. It returns a new function which computes the summed value of fn over the given number octaves, with a user defined phase shift & decay factor (per octave). This can be used for additive wave synthesis, multi-octave noise or any other similar use cases...

Due to the way user defined AST functions keep track of their own call graph, the anonymous function returned by additive does not need to be pre-declared in any way and also ensures all of its own function dependencies are resolved and emitted in the correct topological order during later code generation.

Below is the main shader code of the Simplex noise example.

import { add, defn, float, ret, sym, vec2, vec3, vec4 } from "@thi.ng/shader-ast";
import { additive, aspectCorrectedUV, fit1101, snoise2 } from "@thi.ng/shader-ast-stdlib";

const mainImage = defn(
    "vec4",
    "mainImage",
    ["vec2", "vec2", "float"],
    (frag, res, time) => {
        let uv;
        let noise;
        return [
            // compute UV coords and assign to `uv`
            uv = sym(aspectCorrectedUV(frag, res)),
            // dynamically create a multi-octave version of `snoise2`
            // computed over 4 octaves w/ given phase shift and decay
            // factor (both per octave)
            noise = sym(
                additive("vec2", snoise2, 4)(add(uv, time), vec2(2), float(0.5))
            ),
            // `noise` is in [-1..1] interval, use fit1101 to fit to [0..1]
            ret(vec4(vec3(fit1101(noise)), 1))
        ];
    }
);

Run the above-linked example and view the console to see the full generated shader code. Also check out the raymarching demo which uses several other HOFs from this library to drastically simplify user code.

API

TODO. For now, please see doc strings in source for details...

Color

/src/color

  • toLinear
  • toSRGB
  • luminanceRGB
  • decodeRGBE

Porter-Duff alpha blending

Use the porterDuff higher order function to define new blend modes. See @thi.ng/porter-duff for reference.

12 standard PD operators for vec4 RGBA colors:

  • blendSrcOver
  • blendDestOver
  • blendSrcIn
  • blendDestIn
  • blendSrcOut
  • blendDestOut
  • blendSrcAtop
  • blendDestAtop
  • blendXor
  • blendPlus

Fog

/src/fog

  • fogLinear
  • fogExp
  • fogExp2

Lighting

/src/light

  • lambert
  • halfLambert
  • diffuseLighting
  • trilight

Math

/src/math

  • additive
  • cartesian2 / cartesian3
  • clamp01 / clamp11
  • cross2 / crossC2
  • distChebyshev2 / distChebyshev3 / distChebyshev4
  • distManhattan2 / distManhattan3 / distManhattan4
  • fit01 / fit11 / fit1101 / fit0111
  • magSq2 / magSq3 / magSq4
  • maxComp2 / maxComp3 / maxComp4
  • minComp2 / minComp3 / minComp4
  • perpendicularCCW / perpendicularCW
  • orthogonal3
  • polar2 / polar3
  • sincos / cossin

Oscillators

/src/math

  • sinOsc / sawOsc / triOsc / rectOsc

Matrix operations

/src/matrix

  • lookat
  • transformMVP
  • surfaceNormal
  • rotation2
  • rotationX3 / rotationY3 / rotationZ3
  • rotationX4 / rotationY4 / rotationZ4

Noise / randomness

/src/noise

  • hash2 / hash3
  • hash11 / hash12 / hash13
  • hash21 / hash22 / hash23
  • hash31 / hash32 / hash33
  • hash41 / hash42 / hash43 / hash44
  • permute / permute3 / permute4
  • snoise2
  • voronoise2
  • worley2 / worleyDist / worleyDistManhattan

Raymarching

/src/raymarch

  • raymarchAO
  • raymarchDir
  • raymarchNormal
  • raymarchScene
  • rayPointAt

Screen coordinates

/src/screen

  • aspectCorrectedUV

Signed Distance Fields

/src/sdf

Primitives

  • sdfBox2
  • sdfBox3
  • sdfCircle
  • sdfCylinder
  • sdfLine2
  • sdfLine3
  • sdfPlane2
  • sdfPlane3
  • sdfSphere
  • sdfTorus
  • sdfTriangle2

Polyhedra

  • sdfDodecahedron / sdfDodecahedronSmooth
  • sdfIcosahedron / sdfIcosahedronSmooth
  • sdfOctahedron / sdfOctahedronSmooth
  • sdfTruncatedOctahedron / sdfTruncatedOctahedronSmooth
  • sdfTruncatedIcosahedron / sdfTruncatedIcosahedronSmooth

Operators / combinators

  • sdfAnnular
  • sdfIntersect
  • sdfMirror2
  • sdfRepeat2
  • sdfRepeatPolar2
  • sdfRepeat3
  • sdfRound
  • sdfSubtract
  • sdfSmoothIntersect / sdfSmoothIntersectAll
  • sdfSmoothSubtract / sdfSmoothSubtractAll
  • sdfSmoothUnion / sdfSmoothUnionAll
  • sdfUnion

Texture lookups

/src/tex

  • indexToCoord / coordToIndex
  • indexToUV / uvToIndex
  • readIndex1 / readIndex2 / readIndex3 / readIndex4

Authors

Karsten Schmidt

If this project contributes to an academic publication, please cite it as:

@misc{thing-shader-ast-stdlib,
  title = "@thi.ng/shader-ast-stdlib",
  author = "Karsten Schmidt",
  note = "https://thi.ng/shader-ast-stdlib",
  year = 2019
}

License

© 2019 - 2021 Karsten Schmidt // Apache Software License 2.0

0.18.14

10 days ago

0.18.13

13 days ago

0.18.12

16 days ago

0.18.11

25 days ago

0.18.10

28 days ago

0.18.9

1 month ago

0.18.8

1 month ago

0.18.7

1 month ago

0.18.6

2 months ago

0.18.5

2 months ago

0.18.4

2 months ago

0.18.3

2 months ago

0.18.2

2 months ago

0.18.1

2 months ago

0.18.0

2 months ago

0.17.0

2 months ago

0.16.31

2 months ago

0.16.30

2 months ago

0.16.29

2 months ago

0.16.27

2 months ago

0.16.28

2 months ago

0.16.25

3 months ago

0.16.26

3 months ago

0.16.24

3 months ago

0.16.23

3 months ago

0.16.22

3 months ago

0.16.18

3 months ago

0.16.19

3 months ago

0.16.21

3 months ago

0.16.20

3 months ago

0.16.17

3 months ago

0.16.16

3 months ago

0.16.14

4 months ago

0.16.15

4 months ago

0.16.11

5 months ago

0.16.12

5 months ago

0.16.13

5 months ago

0.16.10

5 months ago

0.16.9

5 months ago

0.14.13

8 months ago

0.14.12

8 months ago

0.14.11

8 months ago

0.14.10

8 months ago

0.14.17

7 months ago

0.14.16

7 months ago

0.14.15

7 months ago

0.14.14

8 months ago

0.14.19

7 months ago

0.14.18

7 months ago

0.14.20

6 months ago

0.14.5

9 months ago

0.14.6

9 months ago

0.14.7

9 months ago

0.14.8

9 months ago

0.14.9

8 months ago

0.14.0

10 months ago

0.14.1

9 months ago

0.14.2

9 months ago

0.14.3

9 months ago

0.14.4

9 months ago

0.15.0

6 months ago

0.16.3

6 months ago

0.16.4

6 months ago

0.16.5

6 months ago

0.16.6

6 months ago

0.16.7

5 months ago

0.16.8

5 months ago

0.16.0

6 months ago

0.16.1

6 months ago

0.16.2

6 months ago

0.13.17

11 months ago

0.13.16

12 months ago

0.13.15

12 months ago

0.13.14

1 year ago

0.13.12

1 year ago

0.13.13

1 year ago

0.13.6

1 year ago

0.13.7

1 year ago

0.13.8

1 year ago

0.13.9

1 year ago

0.13.11

1 year ago

0.13.10

1 year ago

0.13.5

1 year ago

0.13.4

1 year ago

0.13.1

1 year ago

0.13.2

1 year ago

0.13.3

1 year ago

0.13.0

1 year ago

0.12.27

1 year ago

0.12.28

1 year ago

0.12.29

1 year ago

0.12.26

1 year ago

0.12.16

2 years ago

0.12.17

2 years ago

0.12.18

2 years ago

0.12.19

2 years ago

0.12.15

2 years ago

0.12.20

2 years ago

0.12.21

2 years ago

0.12.22

2 years ago

0.12.23

1 year ago

0.12.24

1 year ago

0.12.25

1 year ago

0.12.13

2 years ago

0.12.14

2 years ago

0.12.12

2 years ago

0.12.10

2 years ago

0.12.11

2 years ago

0.12.7

2 years ago

0.12.8

2 years ago

0.12.9

2 years ago

0.12.4

2 years ago

0.12.5

2 years ago

0.12.6

2 years ago

0.12.0

2 years ago

0.12.1

2 years ago

0.12.2

2 years ago

0.12.3

2 years ago

0.11.6

2 years ago

0.11.5

2 years ago

0.10.9

2 years ago

0.11.0

2 years ago

0.11.1

2 years ago

0.11.2

2 years ago

0.11.3

2 years ago

0.11.4

2 years ago

0.10.8

3 years ago

0.10.4

3 years ago

0.10.7

3 years ago

0.10.1

3 years ago

0.10.3

3 years ago

0.10.0

3 years ago

0.9.4

3 years ago

0.9.2

3 years ago

0.9.1

3 years ago

0.9.3

3 years ago

0.9.0

3 years ago

0.8.0

3 years ago

0.7.0

3 years ago

0.6.7

3 years ago

0.6.6

3 years ago

0.6.5

3 years ago

0.6.4

3 years ago

0.6.3

3 years ago

0.6.2

3 years ago

0.6.1

3 years ago

0.6.0

3 years ago

0.5.26

3 years ago

0.5.25

3 years ago

0.5.24

3 years ago

0.5.23

3 years ago

0.5.22

3 years ago

0.5.21

3 years ago

0.5.20

3 years ago

0.5.19

3 years ago

0.5.18

3 years ago

0.5.14

3 years ago

0.5.13

3 years ago

0.5.12

3 years ago

0.5.11

3 years ago

0.5.10

3 years ago

0.5.9

3 years ago

0.5.8

3 years ago

0.5.7

3 years ago

0.5.6

3 years ago

0.5.5

3 years ago

0.5.4

3 years ago

0.5.3

4 years ago

0.5.2

4 years ago

0.5.1

4 years ago

0.5.0

4 years ago

0.4.6

4 years ago

0.4.5

4 years ago

0.4.4

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.4.3

4 years ago

0.4.2

4 years ago

0.3.33

4 years ago

0.3.31

4 years ago

0.3.32

4 years ago

0.3.30

4 years ago

0.3.29

4 years ago

0.3.28

4 years ago

0.3.27

4 years ago

0.3.26

4 years ago

0.3.25

4 years ago

0.3.24

4 years ago

0.3.23

4 years ago

0.3.22

4 years ago

0.3.21

4 years ago

0.3.20

4 years ago

0.3.19

4 years ago

0.3.18

4 years ago

0.3.17

4 years ago

0.3.16

4 years ago

0.3.15

4 years ago

0.3.14

4 years ago

0.3.13

4 years ago

0.3.12

4 years ago

0.3.11

4 years ago

0.3.10

4 years ago

0.3.9

4 years ago

0.3.8

4 years ago

0.3.7

4 years ago

0.3.4

4 years ago

0.3.3

4 years ago

0.3.2

4 years ago

0.3.1

4 years ago

0.3.0

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago