Coordinates
Center the origin and undo the aspect-ratio stretch
screenUV starts at the top-left with y pointing down. Flip y with oneMinus, then shift to the center. Multiply x by the aspect so circles stay round
openconst aspect = screenSize.x.div(screenSize.y); const uv = vec2(screenUV.x, screenUV.y.oneMinus()); const p = uv.sub(0.5).mul(vec2(aspect, 1)); // x: -aspect/2..aspect/2, y: -0.5..0.5Polar coordinates (radius and angle)
atan(y, x) with two arguments works as atan2. The angle runs from -PI to PI
openconst r = p.length(); const a = atan(p.y, p.x); const spiral = sin(r.mul(20).sub(a.mul(3)).sub(time));Repeat in a grid
fract gives the position inside a cell, floor gives the cell index. Feed the index to hash for a per-cell random value
openconst cell = fract(p.mul(6)).sub(0.5); // -0.5..0.5 inside each cell const id = floor(p.mul(6)); const rnd = hash(id.x.add(id.y.mul(131)));Rotate
openconst q = rotate(p, time.mul(0.5)); // vec2 and an angle in radiansMirror / kaleidoscope
openconst m = abs(p); // mirror on both axes const k = abs(fract(atan(p.y, p.x).div(6.28318).mul(6)).sub(0.5)); // 6-fold
Time and motion
Speed up or slow down
openconst t = time.mul(0.3); // slower const fast = time.mul(4);Bounce between 0 and 1
openconst wave = sin(time).mul(0.5).add(0.5); // smooth const tri = abs(fract(time.mul(0.5)).mul(2).sub(1)); // linearLoop with a fixed period
openconst t = fract(time.div(4)); // 0..1 every 4 secondsEase a value
openconst eased = smoothstep(0, 1, t); // ease in-out const sharp = t.mul(t); // ease in const soft = t.oneMinus().pow(2).oneMinus(); // ease out
Color
Cycle the hue (specify in HSV)
openconst rgb = mx_hsvtorgb(vec3(fract(time.mul(0.1)), 0.8, 1)); // hue, saturation, valueTurn one number into a nice gradient
A cosine palette. Change the vec3 phase offsets to change the mood
openconst palette = Fn(([t]) => vec3(0.5).add(cos(t.add(vec3(0, 0.33, 0.67)).mul(6.28318)).mul(0.5))); const col = palette(p.length().add(time.mul(0.2)));Blend two colors
openconst col = mix(color(0x2a6dff), color(0xff5aa5), k); // k: 0..1Vertical or horizontal gradient
openconst vertical = mix(color(0x05050a), color(0x2a6dff), screenUV.y.oneMinus()); // bright at the top const radial = mix(color(0xffffff), color(0x000000), p.length().mul(1.5));Change brightness and contrast
openconst darker = col.mul(0.6); const contrast = col.sub(0.5).mul(1.4).add(0.5); const gamma = col.pow(2.2);
Shapes
Draw a circle
Swap the two smoothstep edges so the inside becomes 1. A smaller gap gives a sharper edge
openconst d = p.length(); const circle = smoothstep(0.31, 0.3, d); // 1 inside, 0 outsideDraw a ring
openconst ring = smoothstep(0.02, 0, abs(d.sub(0.3)));Draw a box
A signed distance function: 0 on the outline, negative inside
openconst q = abs(p).sub(vec2(0.3, 0.2)); const box = max(q, 0).length().add(min(max(q.x, q.y), 0)); const fill = smoothstep(0.005, 0, box);Draw a curve as a line
openconst y = sin(p.x.mul(6).add(time)).mul(0.2); const line = smoothstep(0.01, 0, abs(p.y.sub(y)));Remove jagged edges
fwidth is the change per pixel. Softening by one pixel keeps edges smooth at any resolution
openconst w = fwidth(d); const shape = smoothstep(float(0.3).add(w), float(0.3).sub(w), d);
Noise
Smooth noise
Ranges from -1 to 1; use mul(0.5).add(0.5) for 0 to 1
openconst n = mx_noise_float(p.mul(3).add(time.mul(0.2))).mul(0.5).add(0.5);Cloud-like noise (fbm)
The second argument is the number of octaves. More is finer detail and slower
openconst n = mx_fractal_noise_float(p.mul(2).add(time.mul(0.1)), 5);Warp noise into marble
openconst warp = vec2(mx_noise_float(p.add(time.mul(0.1))), mx_noise_float(p.add(5.2))); const n = mx_noise_float(p.mul(2).add(warp.mul(0.8)));Cellular (Worley) pattern
openconst cells = mx_worley_noise_float(p.mul(4).add(time.mul(0.2)));Add film grain
openconst grain = hash(screenUV.x.add(screenUV.y.mul(7.13)).add(time)).sub(0.5).mul(0.06); const out = col.add(grain);
Control flow and functions
Accumulate in a variable / loop
Values changed inside a loop must be created with toVar. Plain consts cannot be reassigned
openconst acc = float(0).toVar(); Loop({ start: 0, end: 5 }, ({ i }) => { acc.addAssign(sin(p.x.mul(float(i).add(1)).add(time)).div(float(i).add(1))); });Change color by a condition
select for a simple either-or. If / Else when you need several assignments
openconst col = select(d.lessThan(0.3), color(0xff5aa5), color(0x05050a)); const c = vec3(0).toVar(); If(d.lessThan(0.3), () => { c.assign(color(0xff5aa5)); }).Else(() => { c.assign(color(0x05050a)); });Reuse a calculation as a function
Arguments arrive as an array. Call it like a normal function
openconst sdCircle = Fn(([q, r]) => q.length().sub(r)); const d1 = sdCircle(p, 0.3); const d2 = sdCircle(p.sub(vec2(0.4, 0)), 0.2); const both = min(d1, d2);Exit a loop early (raymarching)
openconst dist = float(0).toVar(); Loop({ start: 0, end: 64 }, () => { const d = sdf(ro.add(rd.mul(dist))); If(d.lessThan(0.001), () => { Break(); }); dist.addAssign(d); });
Interaction
React to the mouse (touch) position
mouse is 0..1 with the same top-left origin as screenUV, so you can subtract directly
openimport { mouse } from "nijimi"; const d = screenUV.sub(mouse).length(); const glow = smoothstep(0.3, 0, d);Change only while pressed
openimport { mouseDown } from "nijimi"; const col = mix(calm, excited, mouseDown); // mouseDown is 0 or 1Let viewers adjust a value with a slider
List the same name in controls with its range: [min, max, step]
openexport const speed = uniform(1); export const count = uniform(8); export const controls = { speed: [0, 5, 0.1], count: [1, 32, 1] };
3D (scene mode)
Draw a 3D scene instead of a full-screen image
Export setup to enter scene mode. The camera sits at z = 5 looking at the origin
openexport function setup({ THREE, scene }) { const mesh = new THREE.Mesh(new THREE.TorusKnotGeometry(1, 0.3, 200, 32), new THREE.MeshStandardNodeMaterial()); scene.add(mesh, new THREE.DirectionalLight(0xffffff, 2).translateX(3).translateY(4).translateZ(5)); return { update: ({ delta }) => { mesh.rotation.y += delta * 0.5; } }; }Wave the vertices (vertex shader)
openconst wave = sin(positionLocal.y.mul(6).add(time.mul(3))).mul(0.2); material.positionNode = positionLocal.add(normalLocal.mul(wave));Color by normal or position
openmaterial.colorNode = normalWorld.mul(0.5).add(0.5); material.colorNode = mix(color(0x2a6dff), color(0xff5aa5), positionLocal.y.mul(0.5).add(0.5));Make things glow (bloom)
Colors brighter than 1 glow. Return render() to take over drawing. See the Bloom sample for the full version
openimport { pass } from "three/tsl"; import { bloom } from "three/addons/tsl/display/BloomNode.js"; const pipeline = new THREE.RenderPipeline(renderer); const beauty = pass(scene, camera).getTextureNode("output"); pipeline.outputNode = beauty.add(bloom(beauty, 1, 0.4, 0.3)); return { render: () => pipeline.render() };Use the previous frame (trails, bleeding)
Keep two render targets: read the previous frame while drawing the next, then swap. Sample it with screenUV and free the targets in dispose
openlet front = new THREE.RenderTarget(w, h, { type: THREE.HalfFloatType }); let back = new THREE.RenderTarget(w, h, { type: THREE.HalfFloatType }); const prev = texture(front.texture, screenUV); sim.colorNode = max(prev.rgb.mul(0.98), brush); // fade the old frame, draw on top // in render(): prev.value = front.texture; draw sim into back; show back; swap front / backMove many particles (compute)
Update a GPU array with compute each frame and draw it with a Sprite. See the Particles sample for the full version
openconst positions = instancedArray(count, "vec3"); const step = Fn(() => { const p = positions.element(instanceIndex); p.addAssign(vec3(0, deltaTime.mul(0.1), 0)); })().compute(count); // in update(): renderer.compute(step) // material.positionNode = positions.toAttribute()
Finishing touches
Darken the edges (vignette)
openconst vignette = smoothstep(0.4, 1.3, screenUV.sub(0.5).length().mul(2)).oneMinus(); const out = col.mul(vignette);Keep it working in portrait (phones)
Correct the coordinates by the aspect ratio and shapes stay intact. Check with 9:16 in the editor
openconst aspect = screenSize.x.div(screenSize.y); const p = screenUV.sub(0.5).mul(vec2(aspect, 1)); // see "Coordinates"Inspect a value (debugging)
Show the value as a color. Anything outside 0..1 is clamped, so rescale it into range first
openreturn vec3(n.mul(0.5).add(0.5)); // -1..1 -> 0..1
Math tricks
A smooth sign (tanh)
sign jumps from -1 to 1 at 0. tanh connects the two with an S curve. A larger multiplier makes the switch steeper and closer to sign
openconst s = tanh(x.mul(4)); // -1..1 const col = mix(colorA, colorB, s.mul(0.5).add(0.5));Tame colors that are too bright without clipping
Colors above 1 are cut to 1 on screen and lose their hue. tanh only approaches 1, so bright areas keep their gradation. In the demo the top half is raw and the bottom half uses tanh
openconst out = tanh(col.mul(1.5));Blend two shapes smoothly (smooth min)
min joins two shapes and leaves a crease. smin rounds the place where they come close. The last argument is the width of the blend
openconst smin = Fn(([a, b, k]) => { const h = max(k.sub(abs(a.sub(b))), 0).div(k); return min(a, b).sub(h.mul(h).mul(k).mul(0.25)); }); const d = smin(d1, d2, 0.1);Map a value from one range to another (remap)
Instead of combining mul and add, write the input range and the output range. remap keeps going outside the range, remapClamp stops at the ends. In the demo the left half is remap and the right half is remapClamp
openconst n = mx_noise_float(p.mul(3)); // -1..1 const v = remap(n, -1, 1, 0.2, 1); const c = remapClamp(n, 0, 0.5, 0, 1);Shift the balance of light and dark (pow)
pow on a 0..1 value keeps both ends in place and moves only the middle. Above 1 it moves toward dark, below 1 toward light. Wrapping it in oneMinus gives the mirrored curve
openconst dark = v.pow(2.5); const light = v.oneMinus().pow(2.5).oneMinus();
More
Dissolve into the next scene with noise
Pixels switch in order of their noise value, lowest first. progress runs from 0 to 1; in real use make it a uniform and drive it from JS. Lighting only the boundary makes it look like it is burning through
openconst progress = sin(time.mul(0.5)).mul(0.5).add(0.5); // 0..1 const n = mx_noise_float(p.mul(3)).mul(0.5).add(0.5); const k = smoothstep(0, 0.1, progress.mul(1.1).sub(n)); // 0: scene A, 1: scene B const edge = k.mul(k.oneMinus()).mul(4); // bright only on the boundary const col = mix(sceneA, sceneB, k).add(vec3(1, 0.6, 0.2).mul(edge));Switch scenes in turn over time
floor gives the index of the current scene, fract the progress within it. select evaluates every scene each time, so branch with If when the scenes are heavy
openconst t = time.div(2); // seconds per scene const i = floor(t).mod(3); // 0, 1, 2, 0, ... const k = smoothstep(0.8, 1, fract(t)); // crossfade over the last 20% const now = select(i.equal(0), a, select(i.equal(1), b, c)); const next = select(i.equal(0), b, select(i.equal(1), c, a)); const col = mix(now, next, k);Light up the silhouette of a 3D object (rim light)
Build a value that approaches 1 as the surface turns away from the camera (fresnel) and multiply the emissive color by it. A higher pow narrows the lit band
openconst fresnel = normalView.dot(positionViewDirection).max(0).oneMinus().pow(3); material.emissiveNode = color(0x4dc3ff).mul(fresnel).mul(2);Step the shading for a cartoon look (toon)
floor cuts the lighting into steps. three also has MeshToonNodeMaterial; write it this way when you want to choose the number of steps and the colors yourself
openconst lit = normalWorld.dot(light).mul(0.5).add(0.5); // 0..1 const band = floor(lit.mul(4)).div(4); material.colorNode = color(0xff7a59).mul(band.add(0.15));Outline a 3D object
Inflate the same shape along its normals and draw only its back faces in a flat color. The body in front hides it, so only the part that sticks out shows as a line. On hard-edged shapes such as a cube, the line breaks at the corners
openconst outline = new THREE.MeshBasicNodeMaterial({ side: THREE.BackSide }); outline.colorNode = color(0xfff3c4); outline.positionNode = positionLocal.add(normalLocal.mul(0.04)); mesh.add(new THREE.Mesh(mesh.geometry, outline));Overlay scanlines for a screen look (post effect)
Apply it last, to the finished color. In scene mode, take the image drawn by pass and apply it there. Keep the line count under half the display height; above that the stripes collapse into moire
openconst col = pass(scene, camera).getTextureNode("output"); const lines = sin(screenUV.y.mul(60).mul(6.28318)).mul(0.5).add(0.5); const roll = smoothstep(0.1, 0, abs(fract(screenUV.y.sub(time.mul(0.1))).sub(0.5))); // slow bright bar pipeline.outputNode = col.mul(mix(float(1), lines, 0.35)).add(roll.mul(0.06));A band of light like an aurora
Add it over a dark background. Noise sways the band, and a finer noise along x turns it into vertical streaks
openconst wave = mx_noise_float(vec2(p.x.mul(2), time.mul(0.15))).mul(0.15); const band = smoothstep(0.35, 0, abs(p.y.sub(wave))); const streak = mx_noise_float(vec2(p.x.mul(12).add(time.mul(0.3)), p.y.mul(0.5))).mul(0.5).add(0.5); const col = sky.add(glow.mul(band).mul(streak.mul(0.8).add(0.2)));
When things go wrong
a * b or a + 1 throws an error
JS operators do not work on nodes. Use the methods. Wrap a number in float() when it comes first
openconst x = a.mul(b).add(1); const y = float(1).sub(a); // not 1 - aNo error but the screen is black (or white)
The value is outside 0..1, or NaN (division by zero, sqrt of a negative, normalize of a zero vector). Guard with max or clamp
openconst safe = d.max(0.001); const col = clamp(value, 0, 1);The error says "(line N)"
The editor underlines that line. A build error happened while assembling the TSL, a runtime error while running
It is slow or stutters
Reduce loop counts and noise octaves. Calling noise inside a loop is especially expensive. Phones have a fraction of a desktop GPU