@threedog/post-effects 0.5.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -7
- package/depth.js +26 -0
- package/dof.js +13 -14
- package/hdr.js +8 -8
- package/index.d.ts +10 -8
- package/index.js +45 -15
- package/outline.js +32 -36
- package/package.json +8 -4
- package/tsl.d.ts +12 -0
- package/tsl.js +126 -0
package/README.md
CHANGED
|
@@ -1,26 +1,37 @@
|
|
|
1
1
|
# @threedog/post-effects
|
|
2
2
|
|
|
3
|
-
Optional post effects for [threedog](https://www.npmjs.com/package/threedog): `bloom`, `ao` (ambient occlusion), `outline`, `dof` (depth of field) on the HDR side, and `lut` (color grade), `grain`, `vignette`, `chromatic` (chromatic aberration) fused into one fullscreen LDR pass. Import only what you use; the engine itself ships no effects.
|
|
3
|
+
Optional post effects for [threedog](https://www.npmjs.com/package/threedog): `bloom`, `ao` (ambient occlusion), `outline`, `dof` (depth of field) on the HDR side, and `lut` (color grade; `paletteLut` makes its LUT from a fixed palette), `grain`, `vignette`, `chromatic` (chromatic aberration) fused into one fullscreen LDR pass. Import only what you use; the engine itself ships no effects.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
npm install @threedog/post-effects@0.
|
|
6
|
+
npm install @threedog/post-effects@0.8
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
This describes 0.
|
|
9
|
+
This describes 0.8.0: `npm install @threedog/post-effects@0.8` (games made in the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine) already have it).
|
|
10
10
|
|
|
11
|
-
Each effect is one value that runs on WebGL and on WebGPU. It goes in the way every post effect does, `engine.
|
|
11
|
+
Each effect is one value that runs on WebGL and on WebGPU. It goes in the way every post effect does, `engine.post.add`:
|
|
12
12
|
|
|
13
13
|
```js
|
|
14
14
|
import { bloom, vignette } from '@threedog/post-effects';
|
|
15
15
|
|
|
16
|
-
engine.
|
|
16
|
+
engine.post.add(bloom({ strength: 0.6 })); // game code
|
|
17
17
|
// or a file in the game's plugins/ folder, or in a style's style/plugins/ folder:
|
|
18
18
|
// plugins/20-vignette.js
|
|
19
19
|
export default vignette();
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
-
An added effect is on unless it says `enabled: false
|
|
22
|
+
An added effect is on unless it says `enabled: false`. The heavy ones (`bloom`, `ao`, `dof`, outline `normal` / `both`) are the game's call on weak devices: read `engine.tier` before adding them. `engine.post.add` returns a handle; on / off and tuning go through it: `glow.enabled = false`, `engine.post.get('ao').set({ radius: 0.6 })`.
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
Four effects exist only as TSL nodes and live in a subpath, for games on WebGPURenderer: `voxelGI`, `temporalAA`, `sunShafts`, `lightVolumes`, from `@threedog/post-effects/tsl`. That file imports `three/webgpu`; the main entry does not, so a WebGL game's bundle does not grow.
|
|
25
|
+
|
|
26
|
+
What each does, by how the game runs (held: switched off, the game's `enabled` stays as written, and `describe().render.post` says why):
|
|
27
|
+
|
|
28
|
+
| Case | voxelGI | temporalAA, sunShafts, lightVolumes |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| Real WebGPU | runs (held on `engine.tier` 'low') | run |
|
|
31
|
+
| WebGL2 backend (no WebGPU in the browser, or `forceWebGL: true`) | held | run |
|
|
32
|
+
| Fell back to `WebGLRenderer` | held | held |
|
|
33
|
+
| Game chose WebGL (`--webgl`) | throws by name | throw by name |
|
|
34
|
+
|
|
35
|
+
Docs ship with the engine: `node_modules/threedog/docs/recipes/52-around-the-picture.md` (post-effect chain, order, depth readers) and `docs/AI.md`.
|
|
25
36
|
|
|
26
37
|
Peer dependencies: `threedog` and `three` (the same copy the game uses). MIT license.
|
package/depth.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// What the depth-reading effects (dof, outline) share: the fullscreen vertex shader and scene depth as distance from the camera, in GLSL and as nodes.
|
|
2
|
+
import { CopyShader } from 'three/addons/shaders/CopyShader.js';
|
|
3
|
+
|
|
4
|
+
export const FULLSCREEN_VERT = CopyShader.vertexShader;
|
|
5
|
+
|
|
6
|
+
/** GLSL lin(depth texture, uv): distance from the camera. Goes with depthUniforms() */
|
|
7
|
+
export const DEPTH_GLSL = `uniform float uNear; uniform float uFar; uniform float uOrtho;
|
|
8
|
+
float lin(sampler2D t, vec2 uv){ float z = texture2D(t, uv).x * 2.0 - 1.0; if (uOrtho > 0.5) return uNear + (z * 0.5 + 0.5) * (uFar - uNear); return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }`;
|
|
9
|
+
|
|
10
|
+
export const depthUniforms = () => ({ uNear: { value: 0.3 }, uFar: { value: 1000 }, uOrtho: { value: 0 } });
|
|
11
|
+
|
|
12
|
+
/** The camera into depthUniforms() before a draw; ortho depth is linear already @param {any} u @param {any} camera */
|
|
13
|
+
export function writeDepthUniforms(u, camera) {
|
|
14
|
+
u.uNear.value = camera.near; u.uFar.value = camera.far; u.uOrtho.value = camera.isOrthographicCamera ? 1 : 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The same on WebGPU. far: the camera's far as a uniform node; lin(texture node, uv): distance from the camera (the depth -> view z helpers follow the backend's depth range).
|
|
19
|
+
* @param {any} T three/tsl @param {any} camera
|
|
20
|
+
*/
|
|
21
|
+
export function depthNodes(T, camera) {
|
|
22
|
+
const near = T.uniform(camera.near).onRenderUpdate(() => camera.near), far = T.uniform(camera.far).onRenderUpdate(() => camera.far);
|
|
23
|
+
const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
|
|
24
|
+
const lin = (tex, uv) => { const d = tex.sample(uv).x; return T.select(ortho.greaterThan(0.5), T.orthographicDepthToViewZ(d, near, far), T.perspectiveDepthToViewZ(d, near, far)).negate(); };
|
|
25
|
+
return { far, lin };
|
|
26
|
+
}
|
package/dof.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// so a later depth reader such as outline still finds the scene's depth in the buffer it reads; keepsDepth tells the chain check so.
|
|
4
4
|
import * as THREE from 'three';
|
|
5
5
|
import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
|
|
6
|
+
import { FULLSCREEN_VERT, DEPTH_GLSL, depthUniforms, writeDepthUniforms, depthNodes } from './depth.js';
|
|
6
7
|
/** @import { PostEffect } from 'threedog' */
|
|
7
8
|
|
|
8
9
|
class DofPass extends Pass {
|
|
@@ -11,24 +12,24 @@ class DofPass extends Pass {
|
|
|
11
12
|
this.camera = camera;
|
|
12
13
|
this.keepsDepth = true;
|
|
13
14
|
this.material = new THREE.ShaderMaterial({
|
|
14
|
-
uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, uTexel: { value: new THREE.Vector2() },
|
|
15
|
+
uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, uTexel: { value: new THREE.Vector2() }, ...depthUniforms(),
|
|
15
16
|
uFocus: { value: 10 }, uRange: { value: 2 }, uFalloff: { value: 20 }, uMaxBlur: { value: 6 } },
|
|
16
|
-
vertexShader:
|
|
17
|
-
fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform vec2 uTexel;
|
|
17
|
+
vertexShader: FULLSCREEN_VERT,
|
|
18
|
+
fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform vec2 uTexel;
|
|
18
19
|
uniform float uFocus; uniform float uRange; uniform float uFalloff; uniform float uMaxBlur;
|
|
19
20
|
varying vec2 vUv;
|
|
20
|
-
|
|
21
|
+
${DEPTH_GLSL}
|
|
21
22
|
float coc(float d){ return clamp((abs(d - uFocus) - uRange) / uFalloff, 0.0, 1.0) * uMaxBlur; }
|
|
22
23
|
void main(){
|
|
23
24
|
gl_FragDepth = texture2D(tDepth, vUv).x;
|
|
24
|
-
float r = coc(lin(vUv));
|
|
25
|
+
float r = coc(lin(tDepth, vUv));
|
|
25
26
|
if (r < 0.5) { gl_FragColor = texture2D(tDiffuse, vUv); return; }
|
|
26
27
|
vec3 sum = texture2D(tDiffuse, vUv).rgb; float w = 1.0;
|
|
27
28
|
// golden-angle disk; a neighbor in sharp focus (smaller blur than its distance) is left out so a crisp object does not bleed into the haze
|
|
28
29
|
for (int i = 1; i < 16; i++) {
|
|
29
30
|
float t = float(i) / 16.0, a = float(i) * 2.39996;
|
|
30
31
|
vec2 o = vec2(cos(a), sin(a)) * sqrt(t) * r;
|
|
31
|
-
float s = step(length(o) * 0.5, coc(lin(vUv + o * uTexel)) + 0.5);
|
|
32
|
+
float s = step(length(o) * 0.5, coc(lin(tDepth, vUv + o * uTexel)) + 0.5);
|
|
32
33
|
sum += texture2D(tDiffuse, vUv + o * uTexel).rgb * s; w += s;
|
|
33
34
|
}
|
|
34
35
|
gl_FragColor = vec4(sum / w, 1.0);
|
|
@@ -42,7 +43,7 @@ class DofPass extends Pass {
|
|
|
42
43
|
const u = this.material.uniforms;
|
|
43
44
|
u.tDiffuse.value = readBuffer.texture; u.tDepth.value = readBuffer.depthTexture;
|
|
44
45
|
u.uTexel.value.set(1 / readBuffer.width, 1 / readBuffer.height);
|
|
45
|
-
u
|
|
46
|
+
writeDepthUniforms(u, this.camera);
|
|
46
47
|
renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
|
|
47
48
|
this.quad.render(renderer);
|
|
48
49
|
}
|
|
@@ -50,18 +51,18 @@ class DofPass extends Pass {
|
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
/**
|
|
53
|
-
* Depth of field (hdr slot,
|
|
54
|
+
* Depth of field (hdr slot, heavy on weak devices): everything farther from `focus` than `range` blurs, up to `maxBlur` pixels over `falloff` meters.
|
|
54
55
|
* It reads scene depth, so it must run before any pass that swaps buffers; it passes the scene depth on in its output, so a depth reader
|
|
55
56
|
* after it (outline, whose default order is later) works: both can be on, lines drawn over the blurred image. Move the focus per frame with
|
|
56
|
-
* engine.
|
|
57
|
-
* @example engine.
|
|
57
|
+
* engine.post.get('dof').set({ focus: distanceToTarget }).
|
|
58
|
+
* @example engine.post.add(dof({ focus: 8, range: 3, maxBlur: 5 }))
|
|
58
59
|
* @param {{ focus?: number, range?: number, falloff?: number, maxBlur?: number, enabled?: boolean, order?: number }} [o]
|
|
59
60
|
* focus, range, falloff in meters; maxBlur in device pixels
|
|
60
61
|
* @returns {PostEffect}
|
|
61
62
|
*/
|
|
62
63
|
export function dof({ focus = 10, range = 2, falloff = 20, maxBlur = 6, enabled, order = 5 } = {}) {
|
|
63
64
|
const update = (pass, p) => { const u = pass.material.uniforms; u.uFocus.value = p.focus; u.uRange.value = p.range; u.uFalloff.value = p.falloff; u.uMaxBlur.value = p.maxBlur; };
|
|
64
|
-
return { name: 'dof', slot: 'hdr', order, enabled,
|
|
65
|
+
return { name: 'dof', slot: 'hdr', order, enabled, needsDepth: true, params: { focus, range, falloff, maxBlur },
|
|
65
66
|
create: ({ camera, params }) => { const pass = new DofPass(camera); update(pass, params); return pass; }, update, node: dofNode };
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -73,10 +74,8 @@ export function dof({ focus = 10, range = 2, falloff = 20, maxBlur = 6, enabled,
|
|
|
73
74
|
* @param {any} input @param {any} ctx
|
|
74
75
|
*/
|
|
75
76
|
function dofNode(input, { tsl: T, display, scenePass, camera, p }) {
|
|
76
|
-
const near = T.uniform(camera.near).onRenderUpdate(() => camera.near), far = T.uniform(camera.far).onRenderUpdate(() => camera.far);
|
|
77
|
-
const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
|
|
78
77
|
const depth = scenePass.getTextureNode('depth'), color = display.texture(input), uv = T.screenUV, texel = T.vec2(1).div(T.screenSize);
|
|
79
|
-
const lin
|
|
78
|
+
const { lin: linOf } = depthNodes(T, camera), lin = q => linOf(depth, q);
|
|
80
79
|
const coc = d => T.clamp(d.sub(p.focus).abs().sub(p.range).div(p.falloff), 0, 1).mul(p.maxBlur);
|
|
81
80
|
const r = coc(lin(uv)).toVar();
|
|
82
81
|
let sum = color.sample(uv).rgb, w = T.float(1);
|
package/hdr.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Bloom and ambient occlusion (GTAO) as engine.post effects (hdr slot). Both are
|
|
1
|
+
// Bloom and ambient occlusion (GTAO) as engine.post effects (hdr slot). Both are heavy on weak devices: the game reads engine.tier to decide whether to add them.
|
|
2
2
|
import * as THREE from 'three';
|
|
3
3
|
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
|
|
4
4
|
import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
|
|
@@ -12,13 +12,13 @@ import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
|
|
|
12
12
|
const BLOOM_NODE_STRENGTH = 3;
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
|
-
* Bloom (glow around bright pixels), hdr slot.
|
|
16
|
-
* @example engine.
|
|
15
|
+
* Bloom (glow around bright pixels), hdr slot.
|
|
16
|
+
* @example engine.post.add(bloom({ strength: 0.35, radius: 0.5, threshold: 0.85 }))
|
|
17
17
|
* @param {{ strength?: number, radius?: number, threshold?: number, enabled?: boolean, order?: number }} [o]
|
|
18
18
|
* @returns {PostEffect}
|
|
19
19
|
*/
|
|
20
20
|
export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled, order = 30 } = {}) {
|
|
21
|
-
return { name: 'bloom', slot: 'hdr', order, enabled,
|
|
21
|
+
return { name: 'bloom', slot: 'hdr', order, enabled, params: { strength, radius, threshold },
|
|
22
22
|
create: ({ width, height, params: p }) => new UnrealBloomPass(new THREE.Vector2(width, height), p.strength, p.radius, p.threshold),
|
|
23
23
|
update: (pass, p) => { pass.strength = p.strength; pass.radius = p.radius; pass.threshold = p.threshold; },
|
|
24
24
|
// WebGPU: three's BloomNode returns only the glow, so it is added to the input. Same params do not give the same picture: UnrealBloomPass
|
|
@@ -28,17 +28,17 @@ export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
|
-
* Ambient occlusion (soft contact shadows in corners;
|
|
31
|
+
* Ambient occlusion (soft contact shadows in corners; heavy on weak devices), hdr slot. radius: how far a surface looks for
|
|
32
32
|
* occluders, in world units; intensity: 0 = none, 1 = full. Defaults are three's GTAOPass defaults (no look chosen here).
|
|
33
|
-
* Order 20 puts it before bloom (30)
|
|
34
|
-
* @example engine.
|
|
33
|
+
* Order 20 puts it before bloom (30), so bloom sees the darkened corners. Other GTAOPass settings: post.object().
|
|
34
|
+
* @example engine.post.add(ao({ radius: 0.5 }))
|
|
35
35
|
* @param {{ radius?: number, intensity?: number, enabled?: boolean, order?: number }} [o]
|
|
36
36
|
* @returns {PostEffect}
|
|
37
37
|
*/
|
|
38
38
|
export function ao({ radius = 0.25, intensity = 1, enabled, order = 20 } = {}) {
|
|
39
39
|
// update in place: GTAOPass keeps its targets and noise, so changing radius never rebuilds it
|
|
40
40
|
const update = (pass, p) => { pass.updateGtaoMaterial({ radius: p.radius }); pass.blendIntensity = p.intensity; };
|
|
41
|
-
return { name: 'ao', slot: 'hdr', order, enabled,
|
|
41
|
+
return { name: 'ao', slot: 'hdr', order, enabled, params: { radius, intensity }, update,
|
|
42
42
|
create: ({ scene, camera, width, height, params }) => { const pass = new GTAOPass(scene, camera, width, height); update(pass, params); return pass; },
|
|
43
43
|
// WebGPU: GTAONode on the scene pass's depth (normals reconstructed from depth), its .r darkens the color; intensity mixes toward no AO as blendIntensity does
|
|
44
44
|
node: (input, { display, scenePass, camera, tsl, p }) => {
|
package/index.d.ts
CHANGED
|
@@ -3,22 +3,24 @@
|
|
|
3
3
|
import type { PostEffect, ColorLike } from 'threedog';
|
|
4
4
|
import type { Data3DTexture } from 'three';
|
|
5
5
|
|
|
6
|
-
/** Color grading (ldr, fused): contrast / saturation 1 = unchanged, temperature -1 cool .. 1 warm, optional 3D LUT (e.g. LUTCubeLoader's texture3D). On when
|
|
6
|
+
/** Color grading (ldr, fused): contrast / saturation 1 = unchanged, temperature -1 cool .. 1 warm, optional 3D LUT (e.g. LUTCubeLoader's texture3D). On when added (enabled: false adds it off) */
|
|
7
7
|
export function lut(o?: { lut?: Data3DTexture | null; amount?: number; contrast?: number; saturation?: number; temperature?: number; enabled?: boolean; order?: number }): PostEffect;
|
|
8
|
-
/**
|
|
8
|
+
/** A 3D LUT that snaps every color to the nearest of `colors` (display sRGB, nearest filter), for lut({ lut }). colors: at least 2; size: cells per side (default 32). */
|
|
9
|
+
export function paletteLut(colors: ColorLike[], size?: number): Data3DTexture;
|
|
10
|
+
/** Film grain (ldr, fused); size in device pixels, animated = new noise 24 times a second. On when added (enabled: false adds it off) */
|
|
9
11
|
export function grain(o?: { amount?: number; size?: number; animated?: boolean; enabled?: boolean; order?: number }): PostEffect;
|
|
10
|
-
/** Darker corners (ldr, fused); start: 0 center .. 1 corner. On when
|
|
12
|
+
/** Darker corners (ldr, fused); start: 0 center .. 1 corner. On when added (enabled: false adds it off) */
|
|
11
13
|
export function vignette(o?: { strength?: number; start?: number; enabled?: boolean; order?: number }): PostEffect;
|
|
12
|
-
/** Red / blue shift apart toward the screen edge (ldr, fused; starts a fused group because it samples the input). On when
|
|
14
|
+
/** Red / blue shift apart toward the screen edge (ldr, fused; starts a fused group because it samples the input). On when added (enabled: false adds it off) */
|
|
13
15
|
export function chromatic(o?: { amount?: number; enabled?: boolean; order?: number }): PostEffect;
|
|
14
|
-
/** Depth of field (hdr,
|
|
16
|
+
/** Depth of field (hdr, heavy on weak devices, reads scene depth; passes it on, so it can be on with outline when its order is lower, lines then stay sharp); meters / device pixels. On when added (enabled: false adds it off) */
|
|
15
17
|
export function dof(o?: { focus?: number; range?: number; falloff?: number; maxBlur?: number; enabled?: boolean; order?: number }): PostEffect;
|
|
16
18
|
|
|
17
|
-
/** Bloom (glow around bright pixels; hdr,
|
|
19
|
+
/** Bloom (glow around bright pixels; hdr, heavy on weak devices). On when added (enabled: false adds it off) */
|
|
18
20
|
export function bloom(o?: { strength?: number; radius?: number; threshold?: number; enabled?: boolean; order?: number }): PostEffect;
|
|
19
|
-
/** Ambient occlusion (soft contact shadows in corners; hdr,
|
|
21
|
+
/** Ambient occlusion (soft contact shadows in corners; hdr, heavy on weak devices). On when added (enabled: false adds it off) */
|
|
20
22
|
export function ao(o?: { radius?: number; intensity?: number; enabled?: boolean; order?: number }): PostEffect;
|
|
21
|
-
/** Outline (hdr, reads scene depth). On when
|
|
23
|
+
/** Outline (hdr, reads scene depth). On when added (enabled: false adds it off). mode 'depth' (default) = silhouettes, 'normal' = creases (an extra scene render), 'both'; wobble = line jitter in pixels; offLayer = objects with that three.js layer enabled get no lines (use OUTLINE_OFF_LAYER) */
|
|
22
24
|
export function outline(o?: { color?: ColorLike; thickness?: number; strength?: number; mode?: 'depth' | 'normal' | 'both'; fadeWithDistance?: boolean; wobble?: number; offLayer?: number | null; enabled?: boolean; order?: number }): PostEffect;
|
|
23
25
|
/** Layer number (29) for outline({ offLayer }): mesh.layers.enable(OUTLINE_OFF_LAYER) exempts that object from the lines */
|
|
24
26
|
export const OUTLINE_OFF_LAYER: number;
|
package/index.js
CHANGED
|
@@ -1,19 +1,24 @@
|
|
|
1
1
|
// @threedog/post-effects: optional post effects. The engine ships none (it owns no look); a style or a game adds the ones it wants, the one
|
|
2
|
-
// way every post effect gets in (engine.
|
|
2
|
+
// way every post effect gets in (engine.post.add). Each effect gives create (WebGL) and node (WebGPU), so one value runs on both:
|
|
3
3
|
// import { vignette, grain } from '@threedog/post-effects';
|
|
4
|
-
// engine.
|
|
4
|
+
// engine.post.add(vignette()); // game code
|
|
5
5
|
// plugins/20-grain.js: export default grain(); // the game's plugins folder, or a style's style/plugins/ folder
|
|
6
6
|
// Styles bring bloom / ao / outline as their own plugin files; they all import from here, never from each other.
|
|
7
|
-
//
|
|
7
|
+
// Effects that exist only as TSL nodes (voxelGI, temporalAA, sunShafts, lightVolumes) live in the subpath @threedog/post-effects/tsl: they import three/webgpu, this entry does not.
|
|
8
|
+
// hdr slot (linear, before tone mapping): bloom, ao, outline, dof. ldr slot (display sRGB, after it): lut, paletteLut through lut, grain, vignette, chromatic.
|
|
8
9
|
// lut / grain / vignette / chromatic carry a `fuse` GLSL snippet, so when several are on they run as one fullscreen pass.
|
|
9
|
-
// Added = on: an effect given to
|
|
10
|
-
//
|
|
11
|
-
//
|
|
10
|
+
// Added = on: an effect given to engine.post.add (or exported by a plugin file) is on unless it says enabled: false (added off for the game to switch on later with
|
|
11
|
+
// handle.enabled = true); the engine's rule for every effect, so adding one never silently does nothing. Tier rule, the same as at skipOnLowTier in the engine's render/PostFX.js:
|
|
12
|
+
// an effect declares skipOnLowTier itself, the engine only follows that declaration, and says so in describe() and with one console note when it holds one. None here declare it, so the heavy
|
|
13
|
+
// ones (bloom, ao, dof, outline mode normal/both) stay the game's call on weak devices: read engine.tier and leave them out.
|
|
12
14
|
import * as THREE from 'three';
|
|
15
|
+
import { codedError } from 'threedog/error-hints';
|
|
13
16
|
export { dof } from './dof.js';
|
|
14
17
|
export { bloom, ao } from './hdr.js';
|
|
15
18
|
export { outline, OUTLINE_OFF_LAYER } from './outline.js';
|
|
16
19
|
/** @import { PostEffect } from 'threedog' */
|
|
20
|
+
// luminance weights: Rec. 709 for lut's saturation, Rec. 601 for grain's fade on bright pixels (the engine's own are in render/fxNumbers.js, which is not public)
|
|
21
|
+
const LUMA = [0.2126, 0.7152, 0.0722], LUMA_601 = [0.299, 0.587, 0.114];
|
|
17
22
|
|
|
18
23
|
// A 2x2x2 identity LUT stands in until the game gives a real one (a sampler uniform must always hold a texture)
|
|
19
24
|
const identity = new THREE.Data3DTexture(new Uint8Array([0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 255, 255, 0, 255,
|
|
@@ -21,11 +26,13 @@ const identity = new THREE.Data3DTexture(new Uint8Array([0, 0, 0, 255, 255, 0, 0
|
|
|
21
26
|
identity.format = THREE.RGBAFormat; identity.minFilter = identity.magFilter = THREE.LinearFilter; identity.unpackAlignment = 1; identity.needsUpdate = true;
|
|
22
27
|
|
|
23
28
|
/**
|
|
24
|
-
* Color grading
|
|
29
|
+
* Color grading (ldr slot): contrast, saturation, warm/cool shift and an optional 3D LUT, in one fused snippet.
|
|
30
|
+
* It reads the picture after tone mapping and the output encoding (display sRGB, 0..1), so a LUT is one made on a finished display image, and
|
|
31
|
+
* nothing here tone-maps again; for a grade on linear light before the tone curve, write an hdr effect of your own.
|
|
25
32
|
* @example
|
|
26
33
|
* import { LUTCubeLoader } from 'three/addons/loaders/LUTCubeLoader.js';
|
|
27
34
|
* const { texture3D } = await new LUTCubeLoader().loadAsync('/luts/warm.cube');
|
|
28
|
-
* engine.
|
|
35
|
+
* engine.post.add(lut({ lut: texture3D, amount: 0.8, saturation: 1.1, temperature: 0.2 }))
|
|
29
36
|
* @param {{ lut?: import('three').Data3DTexture | null, amount?: number, contrast?: number, saturation?: number, temperature?: number, enabled?: boolean, order?: number }} [o]
|
|
30
37
|
* lut: a 3D LUT texture (null = only the numbers below); amount: how much of the LUT result to use (0..1); contrast, saturation: 1 = unchanged;
|
|
31
38
|
* temperature: -1 cool .. 1 warm
|
|
@@ -39,21 +46,44 @@ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temp
|
|
|
39
46
|
uLutContrast: p.contrast, uLutSaturation: p.saturation, uLutTemp: p.temperature }),
|
|
40
47
|
glsl: `color.rgb += vec3(uLutTemp * 0.06, 0.0, -uLutTemp * 0.06);
|
|
41
48
|
color.rgb = clamp((color.rgb - 0.5) * uLutContrast + 0.5, 0.0, 1.0);
|
|
42
|
-
color.rgb = mix(vec3(dot(color.rgb, vec3(
|
|
49
|
+
color.rgb = mix(vec3(dot(color.rgb, vec3(${LUMA.join(', ')}))), color.rgb, uLutSaturation);
|
|
43
50
|
if (uLutAmount > 0.0) color.rgb = mix(color.rgb, texture(uLutTex, clamp(color.rgb, 0.0, 1.0) * ((uLutSize - 1.0) / uLutSize) + 0.5 / uLutSize).rgb, uLutAmount);`,
|
|
44
51
|
// the same steps as the GLSL above; the LUT texture is not a live param (changing it rebuilds the chain), so its branch is chosen here
|
|
45
52
|
tsl: (color, uv, { tsl: T, p, params }) => {
|
|
46
53
|
let c = color.rgb.add(T.vec3(p.temperature.mul(0.06), 0, p.temperature.mul(-0.06)));
|
|
47
54
|
c = T.clamp(c.sub(0.5).mul(p.contrast).add(0.5), 0, 1);
|
|
48
|
-
c = T.mix(T.vec3(T.dot(c, T.vec3(
|
|
55
|
+
c = T.mix(T.vec3(T.dot(c, T.vec3(...LUMA))), c, p.saturation);
|
|
49
56
|
if (params.lut) { const n = params.lut.image.width; c = T.mix(c, T.texture3D(params.lut, T.clamp(c, 0, 1).mul((n - 1) / n).add(0.5 / n)).rgb, p.amount); }
|
|
50
57
|
return T.vec4(c, color.a);
|
|
51
58
|
} } };
|
|
52
59
|
}
|
|
53
60
|
|
|
61
|
+
/**
|
|
62
|
+
* A 3D LUT that snaps every color to the nearest of `colors` (nearest in display sRGB), for lut({ lut }): the picture then holds only those colors.
|
|
63
|
+
* Nearest filtering on purpose: a linear lookup would blend neighbors into colors outside the palette. Whatever runs after lut (grain, vignette) moves off it again.
|
|
64
|
+
* @example engine.post.add(lut({ lut: paletteLut([0x101014, 0x8a8a90, 0xf4f1e8]), saturation: 0 }))
|
|
65
|
+
* @param {import('three').ColorRepresentation[]} colors at least 2
|
|
66
|
+
* @param {number} [size] cells per side; a higher size places the borders between colors more finely
|
|
67
|
+
* @returns {import('three').Data3DTexture}
|
|
68
|
+
*/
|
|
69
|
+
export function paletteLut(colors, size = 32) {
|
|
70
|
+
if (!Array.isArray(colors) || colors.length < 2) throw codedError('post-effect', 'paletteLut(colors): colors must be an array of at least 2 colors, e.g. [0x101014, 0xf4f1e8]');
|
|
71
|
+
const pal = colors.map(c => new THREE.Color(c).getRGB({ r: 0, g: 0, b: 0 }, THREE.SRGBColorSpace));
|
|
72
|
+
const data = new Uint8Array(size ** 3 * 4);
|
|
73
|
+
for (let i = 0, b = 0; b < size; b++) for (let g = 0; g < size; g++) for (let r = 0; r < size; r++, i += 4) {
|
|
74
|
+
const x = r / (size - 1), y = g / (size - 1), z = b / (size - 1);
|
|
75
|
+
let best = pal[0], bestD = Infinity;
|
|
76
|
+
for (const c of pal) { const d = (c.r - x) ** 2 + (c.g - y) ** 2 + (c.b - z) ** 2; if (d < bestD) { bestD = d; best = c; } }
|
|
77
|
+
data.set([best.r * 255 + 0.5, best.g * 255 + 0.5, best.b * 255 + 0.5, 255], i);
|
|
78
|
+
}
|
|
79
|
+
const t = new THREE.Data3DTexture(data, size, size, size);
|
|
80
|
+
t.format = THREE.RGBAFormat; t.minFilter = t.magFilter = THREE.NearestFilter; t.unpackAlignment = 1; t.needsUpdate = true;
|
|
81
|
+
return t;
|
|
82
|
+
}
|
|
83
|
+
|
|
54
84
|
/**
|
|
55
85
|
* Film grain (ldr slot): per-pixel noise, a little weaker in highlights.
|
|
56
|
-
* @example engine.
|
|
86
|
+
* @example engine.post.add(grain({ amount: 0.06 }))
|
|
57
87
|
* @param {{ amount?: number, size?: number, animated?: boolean, enabled?: boolean, order?: number }} [o]
|
|
58
88
|
* amount: noise strength; size: grain size in device pixels; animated: new noise every frame (24 per second)
|
|
59
89
|
* @returns {PostEffect}
|
|
@@ -64,18 +94,18 @@ export function grain({ amount = 0.06, size = 1, animated = true, enabled, order
|
|
|
64
94
|
uniforms: { uGrainAmount: 'float', uGrainSize: 'float', uGrainAnimated: 'float' },
|
|
65
95
|
values: p => ({ uGrainAmount: p.amount, uGrainSize: Math.max(1, p.size), uGrainAnimated: p.animated ? 1 : 0 }),
|
|
66
96
|
glsl: `float n = fxHash(floor(vUv * uResolution / uGrainSize) + (uGrainAnimated > 0.5 ? floor(uTime * 24.0) * 17.0 : 0.0)) - 0.5;
|
|
67
|
-
color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(
|
|
97
|
+
color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(${LUMA_601.join(', ')})));`,
|
|
68
98
|
// same shape; three's hash() stands in for fxHash, so the noise pattern differs from WebGL's (its strength does not)
|
|
69
99
|
tsl: (color, uv, { tsl: T, p, time, resolution }) => {
|
|
70
100
|
const q = T.floor(uv.mul(resolution).div(T.max(p.size, 1))), frame = T.floor(time.mul(24)).mul(17).mul(p.animated);
|
|
71
101
|
const n = T.hash(q.x.add(q.y.mul(1103)).add(frame)).sub(0.5);
|
|
72
|
-
return T.vec4(color.rgb.add(n.mul(p.amount).mul(T.float(1).sub(T.dot(color.rgb, T.vec3(
|
|
102
|
+
return T.vec4(color.rgb.add(n.mul(p.amount).mul(T.float(1).sub(T.dot(color.rgb, T.vec3(...LUMA_601)).mul(0.5)))), color.a);
|
|
73
103
|
} } };
|
|
74
104
|
}
|
|
75
105
|
|
|
76
106
|
/**
|
|
77
107
|
* Vignette (ldr slot): darker screen corners.
|
|
78
|
-
* @example engine.
|
|
108
|
+
* @example engine.post.add(vignette({ strength: 0.4 }))
|
|
79
109
|
* @param {{ strength?: number, start?: number, enabled?: boolean, order?: number }} [o]
|
|
80
110
|
* strength: darkness at the corners (0..1); start: distance from the center where darkening begins (0 center .. 1 corner)
|
|
81
111
|
* @returns {PostEffect}
|
|
@@ -92,7 +122,7 @@ export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 }
|
|
|
92
122
|
/**
|
|
93
123
|
* Chromatic aberration (ldr slot): red and blue shift apart toward the screen edge. Samples the pass input, so it starts a fused group
|
|
94
124
|
* (default order puts it first, so it still joins the others).
|
|
95
|
-
* @example engine.
|
|
125
|
+
* @example engine.post.add(chromatic({ amount: 0.004 }))
|
|
96
126
|
* @param {{ amount?: number, enabled?: boolean, order?: number }} [o] amount: edge shift in screen fractions
|
|
97
127
|
* @returns {PostEffect}
|
|
98
128
|
*/
|
package/outline.js
CHANGED
|
@@ -2,11 +2,17 @@
|
|
|
2
2
|
// optional hand-drawn wobble and per-object exemption through a three.js layer.
|
|
3
3
|
import * as THREE from 'three';
|
|
4
4
|
import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
|
|
5
|
+
import { RESERVED_LAYERS } from 'threedog/layers';
|
|
6
|
+
import { codedError } from 'threedog/error-hints';
|
|
7
|
+
import { FULLSCREEN_VERT, DEPTH_GLSL, depthUniforms, writeDepthUniforms, depthNodes } from './depth.js';
|
|
5
8
|
/** @import { PostEffect } from 'threedog' */
|
|
6
9
|
|
|
7
10
|
/** Layer number to put on objects that should get no outline: mesh.layers.enable(OUTLINE_OFF_LAYER), with outline({ offLayer: OUTLINE_OFF_LAYER }) */
|
|
8
|
-
export const OUTLINE_OFF_LAYER =
|
|
11
|
+
export const OUTLINE_OFF_LAYER = RESERVED_LAYERS.outlineOff;
|
|
9
12
|
const MODES = { depth: 0, normal: 1, both: 2 };
|
|
13
|
+
// linear (0.5, 0.5, 1): an empty pixel reads as a normal facing the camera, and for the mask its red 0.5 stays below the > 0.5 test
|
|
14
|
+
const EMPTY = new THREE.Color().setRGB(0.5, 0.5, 1, THREE.LinearSRGBColorSpace), _clear = new THREE.Color();
|
|
15
|
+
const badMode = mode => codedError('post-effect', `outline: unknown mode '${mode}', use 'depth' | 'normal' | 'both'`);
|
|
10
16
|
|
|
11
17
|
class OutlinePass extends Pass {
|
|
12
18
|
/** @param {any} scene @param {any} camera @param {Record<string, any>} p */
|
|
@@ -18,24 +24,22 @@ class OutlinePass extends Pass {
|
|
|
18
24
|
this.normalRT = null; this.maskRT = null;
|
|
19
25
|
this.material = new THREE.ShaderMaterial({
|
|
20
26
|
uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, tNormal: { value: null }, tMask: { value: null }, tMaskDepth: { value: null },
|
|
21
|
-
uTexel: { value: new THREE.Vector2() },
|
|
27
|
+
uTexel: { value: new THREE.Vector2() }, ...depthUniforms(), uColor: { value: new THREE.Color(p.color) },
|
|
22
28
|
uThick: { value: 1 }, uStrength: { value: 1 }, uMode: { value: 0 }, uFade: { value: 1 }, uWobble: { value: 0 }, uTime: { value: 0 }, uUseMask: { value: 0 } },
|
|
23
|
-
vertexShader:
|
|
29
|
+
vertexShader: FULLSCREEN_VERT,
|
|
24
30
|
fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform sampler2D tNormal; uniform sampler2D tMask; uniform sampler2D tMaskDepth;
|
|
25
|
-
uniform vec2 uTexel; uniform
|
|
31
|
+
uniform vec2 uTexel; uniform vec3 uColor; uniform float uThick; uniform float uStrength;
|
|
26
32
|
uniform float uMode; uniform float uFade; uniform float uWobble; uniform float uTime; uniform float uUseMask;
|
|
27
33
|
varying vec2 vUv;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
|
|
31
|
-
return mix(mix(h2(i), h2(i + vec2(1, 0)), f.x), mix(h2(i + vec2(0, 1)), h2(i + vec2(1, 1)), f.x), f.y); }
|
|
34
|
+
${DEPTH_GLSL}
|
|
35
|
+
#include <threedog_noise>
|
|
32
36
|
// object in the exempt layer at this pixel: its own render is not behind what the scene depth saw
|
|
33
37
|
float masked(vec2 uv){ return texture2D(tMask, uv).r > 0.5 && lin(tMaskDepth, uv) <= lin(tDepth, uv) + 0.05 ? 1.0 : 0.0; }
|
|
34
38
|
void main(){
|
|
35
39
|
vec4 c = texture2D(tDiffuse, vUv);
|
|
36
40
|
vec2 o = uTexel * uThick;
|
|
37
41
|
vec2 uv = vUv;
|
|
38
|
-
if (uWobble > 0.0) uv += (vec2(
|
|
42
|
+
if (uWobble > 0.0) uv += (vec2(threedogNoise(vUv / uTexel * 0.04 + uTime), threedogNoise(vUv / uTexel * 0.04 + 17.3 + uTime)) - 0.5) * 2.0 * uWobble * uTexel;
|
|
39
43
|
vec2 nb[4] = vec2[4](vec2(o.x, 0.0), vec2(-o.x, 0.0), vec2(0.0, o.y), vec2(0.0, -o.y)); // the four neighbors, thickness apart
|
|
40
44
|
float d = lin(tDepth, uv), edge = 0.0;
|
|
41
45
|
if (uMode != 1.0) {
|
|
@@ -58,16 +62,14 @@ class OutlinePass extends Pass {
|
|
|
58
62
|
}
|
|
59
63
|
// Render the scene once with an override material into a target the size of the input
|
|
60
64
|
_pass(renderer, rt, mat, layer) {
|
|
61
|
-
const { scene, camera } = this, bg = scene.background, fog = scene.fog,
|
|
62
|
-
|
|
63
|
-
renderer.shadowMap.autoUpdate = false; // an override material is unlit: redrawing the shadow maps for it would be pure waste
|
|
65
|
+
const { scene, camera } = this, bg = scene.background, fog = scene.fog, over = scene.overrideMaterial, mask = camera.layers.mask, alpha = renderer.getClearAlpha();
|
|
66
|
+
renderer.getClearColor(_clear);
|
|
64
67
|
scene.overrideMaterial = mat; scene.background = null; scene.fog = null;
|
|
65
68
|
if (layer != null) camera.layers.set(layer);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
renderer.setRenderTarget(rt); renderer.clear(); renderer.render(scene, camera);
|
|
69
|
-
scene.overrideMaterial =
|
|
70
|
-
renderer.shadowMap.autoUpdate = shadows;
|
|
69
|
+
renderer.setClearColor(EMPTY, 1);
|
|
70
|
+
// what was there goes back, even when the render throws: an override may be a debug view's, and it must outlive this pass
|
|
71
|
+
try { renderer.setRenderTarget(rt); renderer.clear(); renderer.render(scene, camera); }
|
|
72
|
+
finally { scene.overrideMaterial = over; scene.background = bg; scene.fog = fog; camera.layers.mask = mask; renderer.setClearColor(_clear, alpha); }
|
|
71
73
|
}
|
|
72
74
|
_target(rt, w, h, depth) {
|
|
73
75
|
if (rt && (rt.width !== w || rt.height !== h)) { rt.setSize(w, h); return rt; }
|
|
@@ -85,7 +87,7 @@ class OutlinePass extends Pass {
|
|
|
85
87
|
if (useMask) { this.maskRT = this._target(this.maskRT, w, h, true); this._pass(renderer, this.maskRT, this.maskMat, p.offLayer); u.tMask.value = this.maskRT.texture; u.tMaskDepth.value = this.maskRT.depthTexture; }
|
|
86
88
|
u.tDiffuse.value = readBuffer.texture; u.tDepth.value = readBuffer.depthTexture;
|
|
87
89
|
u.uTexel.value.set(1 / w, 1 / h);
|
|
88
|
-
u
|
|
90
|
+
writeDepthUniforms(u, this.camera);
|
|
89
91
|
u.uMode.value = mode; u.uUseMask.value = useMask ? 1 : 0; u.uTime.value = Math.floor(this.time * 8);
|
|
90
92
|
renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
|
|
91
93
|
this.quad.render(renderer);
|
|
@@ -94,7 +96,7 @@ class OutlinePass extends Pass {
|
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
function apply(pass, p) {
|
|
97
|
-
if (!(p.mode in MODES)) throw
|
|
99
|
+
if (!(p.mode in MODES)) throw badMode(p.mode);
|
|
98
100
|
pass.p = p;
|
|
99
101
|
const u = pass.material.uniforms;
|
|
100
102
|
u.uColor.value.set(p.color); u.uThick.value = p.thickness; u.uStrength.value = p.strength; u.uFade.value = p.fadeWithDistance ? 1 : 0; u.uWobble.value = p.wobble;
|
|
@@ -103,10 +105,10 @@ function apply(pass, p) {
|
|
|
103
105
|
/**
|
|
104
106
|
* Dark lines (cartoon look), hdr slot, before bloom so the glow does not blur the lines.
|
|
105
107
|
* mode 'depth' (default): silhouettes where depth jumps; 'normal': creases where surface normals turn (the scene is drawn once more with
|
|
106
|
-
* normals;
|
|
108
|
+
* normals; heavy on weak devices); 'both': either. Objects can opt out of the lines with offLayer.
|
|
107
109
|
* @example
|
|
108
|
-
* engine.
|
|
109
|
-
* engine.
|
|
110
|
+
* engine.post.add(outline({ color: 0x222222, thickness: 1.5 }))
|
|
111
|
+
* engine.post.add(outline({ mode: 'both', wobble: 1.5, offLayer: OUTLINE_OFF_LAYER })) // hand-drawn; then: sky.layers.enable(OUTLINE_OFF_LAYER)
|
|
110
112
|
* @param {{ color?: any, thickness?: number, strength?: number, mode?: 'depth' | 'normal' | 'both', fadeWithDistance?: boolean, wobble?: number,
|
|
111
113
|
* offLayer?: number | null, enabled?: boolean, order?: number }} [o]
|
|
112
114
|
* fadeWithDistance: lines fade out in the far 40..90% of the camera range (default true); wobble: line jitter in pixels (0 = straight);
|
|
@@ -114,7 +116,7 @@ function apply(pass, p) {
|
|
|
114
116
|
* @returns {PostEffect}
|
|
115
117
|
*/
|
|
116
118
|
export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled, order = 10 } = {}) {
|
|
117
|
-
return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true,
|
|
119
|
+
return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
|
|
118
120
|
create: ({ scene, camera, params }) => { const pass = new OutlinePass(scene, camera, params); apply(pass, params); return pass; },
|
|
119
121
|
update: apply, node: outlineNode };
|
|
120
122
|
}
|
|
@@ -125,24 +127,18 @@ export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode
|
|
|
125
127
|
* imports three/webgpu. Number / boolean params are live uniforms (ctx.p); mode and offLayer on / off rebuild the node, as any non-number param does.
|
|
126
128
|
* @param {any} input @param {any} ctx
|
|
127
129
|
*/
|
|
128
|
-
function outlineNode(input, { tsl: T, display, scenePass, scene, camera, params, p }) {
|
|
130
|
+
function outlineNode(input, { tsl: T, fx, display, scenePass, scene, camera, params, p }) {
|
|
129
131
|
const mode = MODES[params.mode];
|
|
130
|
-
if (mode === undefined) throw
|
|
131
|
-
const
|
|
132
|
-
const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
|
|
132
|
+
if (mode === undefined) throw badMode(params.mode);
|
|
133
|
+
const { far, lin } = depthNodes(T, camera);
|
|
133
134
|
// the color param may be a number (then ctx.p holds a float uniform, not a color) or a Color: read the param itself every render
|
|
134
135
|
const tint = new THREE.Color(), col = T.uniform(tint).onRenderUpdate(() => { tint.set(params.color); });
|
|
135
|
-
// distance from the camera, from a depth texture; the depth -> view z helpers follow the backend's depth range, the GLSL does it by hand
|
|
136
|
-
const lin = (tex, uv) => { const d = tex.sample(uv).x; return T.select(ortho.greaterThan(0.5), T.orthographicDepthToViewZ(d, near, far), T.perspectiveDepthToViewZ(d, near, far)).negate(); };
|
|
137
136
|
const depthTex = scenePass.getTextureNode('depth');
|
|
138
137
|
const texel = T.vec2(1).div(T.screenSize), o = texel.mul(p.thickness), base = T.screenUV;
|
|
139
138
|
const nb = [T.vec2(o.x, 0), T.vec2(o.x.negate(), 0), T.vec2(0, o.y), T.vec2(0, o.y.negate())]; // the four neighbors, thickness apart
|
|
140
139
|
// wobble: value noise on the pixel grid, redrawn 8 times a second (flip-book trembling); the GLSL counts its own clock modulo 64 s the same way
|
|
141
|
-
const h2 = q => T.fract(T.sin(T.dot(q, T.vec2(127.1, 311.7))).mul(43758.5453));
|
|
142
|
-
const vn = q => { const i = T.floor(q), f0 = T.fract(q), f = f0.mul(f0).mul(f0.mul(-2).add(3));
|
|
143
|
-
return T.mix(T.mix(h2(i), h2(i.add(T.vec2(1, 0))), f.x), T.mix(h2(i.add(T.vec2(0, 1))), h2(i.add(T.vec2(1, 1))), f.x), f.y); };
|
|
144
140
|
const tick = T.floor(T.mod(T.time, 64).mul(8)), px = base.div(texel).mul(0.04);
|
|
145
|
-
const jitter = T.vec2(
|
|
141
|
+
const jitter = T.vec2(fx.noise(px.add(tick)), fx.noise(px.add(17.3).add(tick))).sub(0.5).mul(2).mul(p.wobble).mul(texel);
|
|
146
142
|
const uv = T.select(p.wobble.greaterThan(0), base.add(jitter), base);
|
|
147
143
|
const d = lin(depthTex, uv);
|
|
148
144
|
let edge = T.float(0);
|
|
@@ -160,12 +156,12 @@ function outlineNode(input, { tsl: T, display, scenePass, scene, camera, params,
|
|
|
160
156
|
const L = layer && new THREE.Layers(), run = v.updateBefore.bind(v), free = v.dispose.bind(v), clear = new THREE.Color(), was = new THREE.Color();
|
|
161
157
|
if (L) v.setLayers(L);
|
|
162
158
|
v.updateBefore = frame => {
|
|
163
|
-
const r = frame.renderer, bg = scene.background, fog = scene.fog, a = r.getClearAlpha();
|
|
159
|
+
const r = frame.renderer, bg = scene.background, bgNode = scene.backgroundNode, fog = scene.fog, a = r.getClearAlpha();
|
|
164
160
|
if (L) L.set(params.offLayer);
|
|
165
161
|
r.getClearColor(was);
|
|
166
162
|
r.setClearColor(clear.setRGB(0.5, 0.5, 1, THREE.SRGBColorSpace), 1);
|
|
167
|
-
scene.background = null; scene.fog = null;
|
|
168
|
-
try { run(frame); } finally { scene.background = bg; scene.fog = fog; r.setClearColor(was, a); }
|
|
163
|
+
scene.background = scene.backgroundNode = null; scene.fog = null; // three prefers backgroundNode over background, so both go
|
|
164
|
+
try { run(frame); } finally { scene.background = bg; scene.backgroundNode = bgNode; scene.fog = fog; r.setClearColor(was, a); }
|
|
169
165
|
};
|
|
170
166
|
v.dispose = () => { free(); mat.dispose(); };
|
|
171
167
|
return v;
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threedog/post-effects",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Optional post effects for threedog: bloom, ambient occlusion, outline, LUT color grading, film grain, vignette, chromatic aberration and depth of field (light ldr effects are fused into one fullscreen pass)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
|
-
"url": "git+https://github.com/penstic123-code/
|
|
8
|
+
"url": "git+https://github.com/penstic123-code/Threedog.js-Game-Engine.git",
|
|
9
9
|
"directory": "packages/post-effects"
|
|
10
10
|
},
|
|
11
|
-
"homepage": "https://github.com/penstic123-code/
|
|
11
|
+
"homepage": "https://github.com/penstic123-code/Threedog.js-Game-Engine#readme",
|
|
12
12
|
"type": "module",
|
|
13
13
|
"engines": {
|
|
14
14
|
"node": "^20.19.0 || >=22.12.0"
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
"types": "./index.d.ts",
|
|
21
21
|
"default": "./index.js"
|
|
22
22
|
},
|
|
23
|
+
"./tsl": {
|
|
24
|
+
"types": "./tsl.d.ts",
|
|
25
|
+
"default": "./tsl.js"
|
|
26
|
+
},
|
|
23
27
|
"./package.json": "./package.json"
|
|
24
28
|
},
|
|
25
29
|
"files": [
|
|
@@ -27,7 +31,7 @@
|
|
|
27
31
|
"*.d.ts"
|
|
28
32
|
],
|
|
29
33
|
"peerDependencies": {
|
|
30
|
-
"threedog": "^0.
|
|
34
|
+
"threedog": "^0.8.0",
|
|
31
35
|
"three": "^0.187.0"
|
|
32
36
|
}
|
|
33
37
|
}
|
package/tsl.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Types of @threedog/post-effects/tsl for code that imports it from the published package.
|
|
2
|
+
import type { PostEffect } from 'threedog';
|
|
3
|
+
import type { Box3, Light } from 'three';
|
|
4
|
+
|
|
5
|
+
/** Real-time bounced light (three's vxgi; hdr). Needs three's WebGPU backend; held off on low tier and on WebGPURenderer's WebGL2 backend, and describe().render.post says why. setup gets the VXGINode @experimental */
|
|
6
|
+
export function voxelGI(o?: { resolution?: number; bounds?: Box3; intensity?: number; occlusion?: number; setup?: (gi: any) => void; enabled?: boolean; order?: number; name?: string }): PostEffect;
|
|
7
|
+
/** Temporal antialiasing (three's TRAANode; last in hdr): clears the dots of stochastic effects before it and replaces MSAA while on. WebGPURenderer only @experimental */
|
|
8
|
+
export function temporalAA(o?: { enabled?: boolean; order?: number; name?: string }): PostEffect;
|
|
9
|
+
/** Sun shafts through gaps, from the light's shadow map (three's GodraysNode; hdr). Best where most of the air is in shadow; open scenes turn to haze. WebGPURenderer only @experimental */
|
|
10
|
+
export function sunShafts(o?: { light?: Light; density?: number; maxDensity?: number; falloff?: number; color?: any; steps?: number; setup?: (rays: any) => void; enabled?: boolean; order?: number; name?: string }): PostEffect;
|
|
11
|
+
/** Lit air in a box: spot cones and point glows with shadows (three's VolumeNodeMaterial; hdr). Point and spot lights only, the sun does nothing here. WebGPURenderer only @experimental */
|
|
12
|
+
export function lightVolumes(o: { bounds: Box3; density?: number; steps?: number; scale?: number; blur?: number; scattering?: (tsl: any, at: { positionRay: any; density: any }) => any; enabled?: boolean; order?: number; name?: string }): PostEffect;
|
package/tsl.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// @threedog/post-effects/tsl: post effects that exist only as TSL nodes, for games that chose WebGPU when they started.
|
|
2
|
+
// import { voxelGI, temporalAA } from '@threedog/post-effects/tsl';
|
|
3
|
+
// engine.post.add(voxelGI({ bounds })); engine.post.add(temporalAA());
|
|
4
|
+
// Why a subpath and not the main entry: these import three's vxgi and display nodes, which import three/webgpu; a WebGL game never loads this file, so its bundle stays as it is.
|
|
5
|
+
// Everything here is plain three.js plugged into engine.post: voxelGI and sunShafts hand three's node back through setup(), so its settings stay the game's.
|
|
6
|
+
// Default order in the hdr slot, low first, one scale with the main entry: voxelGI 2 (the bounce is scene light, so the rest works on it), dof 5, outline 10, ao 20, bloom 30,
|
|
7
|
+
// sunShafts and lightVolumes 200, temporalAA 900 (last: it clears the dots of everything before it).
|
|
8
|
+
// Tier rule as in index.js: of these only voxelGI declares skipOnLowTier. Each effect is held, and describe().render.post says why, on a device where start() fell back to WebGLRenderer;
|
|
9
|
+
// voxelGI also on WebGPURenderer's WebGL2 backend. On a WebGLRenderer the game chose, adding any of them throws by name.
|
|
10
|
+
import { vxgi } from 'three/addons/lighting/vxgi/VXGINode.js';
|
|
11
|
+
import { traa } from 'three/addons/tsl/display/TRAANode.js';
|
|
12
|
+
import { godrays } from 'three/addons/tsl/display/GodraysNode.js';
|
|
13
|
+
import { depthAwareBlend } from 'three/addons/tsl/display/depthAwareBlend.js';
|
|
14
|
+
import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
|
|
15
|
+
import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
|
|
16
|
+
import { Box3, BoxGeometry, Color, Layers, Mesh, Vector3, VolumeNodeMaterial } from 'three/webgpu';
|
|
17
|
+
import { RESERVED_LAYERS } from 'threedog/layers';
|
|
18
|
+
import { codedError } from 'threedog/error-hints';
|
|
19
|
+
/** @import { PostEffect } from 'threedog' */
|
|
20
|
+
|
|
21
|
+
const { lightVolumes: VOLUME_LAYER } = RESERVED_LAYERS;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Real-time bounced light from a voxel volume (three's vxgi), added to the scene color in the hdr slot. Only on three's WebGPU backend; held off on low tier.
|
|
25
|
+
* Light may move every frame (three notices); geometry that moves needs a new voxelization, too slow per frame, so keep moving things out of the volume
|
|
26
|
+
* (gi.volume.layers) and call gi.needsUpdate = true only for a rare change. It injects direct light only: sky light stays the game's. Metal counts as diffuse.
|
|
27
|
+
* What occlusion culling hides stays in the volume (its layer is on gi.volume.layers; setup can take it off). Changing any effect of the chain rebuilds the chain, which voxelizes the scene again: a stall.
|
|
28
|
+
* @param {{ resolution?: number, bounds?: import('three').Box3, intensity?: number, occlusion?: number, setup?: (gi: any) => void, order?: number, enabled?: boolean, name?: string }} [o]
|
|
29
|
+
* resolution: voxels along the longest side; bounds: the part of the world to voxelize (default: the whole scene, so a far sky mesh makes voxels huge);
|
|
30
|
+
* intensity: how strong the bounce is; occlusion: 0 to 1, how much the voxel occlusion darkens the picture (it darkens direct light too, so it starts at 0);
|
|
31
|
+
* setup(gi): gets three's VXGINode each time the chain builds it (coneCount, volume.bounces ...).
|
|
32
|
+
* @returns {PostEffect}
|
|
33
|
+
*/
|
|
34
|
+
export function voxelGI({ resolution = 128, bounds, intensity = 1, occlusion = 0, setup, order = 2, enabled, name = 'voxelGI' } = {}) {
|
|
35
|
+
/** @type {any} */ let gi = null;
|
|
36
|
+
return { name, slot: 'hdr', order, enabled, backend: 'webgpu', skipOnLowTier: true, needsBuffers: ['normal', 'diffuse'], params: { intensity, occlusion },
|
|
37
|
+
node(input, ctx) {
|
|
38
|
+
const { tsl, p, scenePass, scene, camera, display } = ctx;
|
|
39
|
+
gi = display.own(vxgi(scenePass.getTextureNode('depth'), scenePass.getTextureNode('normal'), scene, camera, resolution));
|
|
40
|
+
display.own({ dispose() { gi = null; } });
|
|
41
|
+
gi.volume.layers.enable(RESERVED_LAYERS.occlusionHidden); // a wall out of the camera's sight still throws its color
|
|
42
|
+
if (bounds) gi.volume.bounds.copy(bounds);
|
|
43
|
+
setup?.(gi);
|
|
44
|
+
const light = gi.getGINode().rgb.mul(scenePass.getTextureNode('diffuse').rgb).mul(p.intensity);
|
|
45
|
+
return tsl.vec4(input.rgb.mul(tsl.mix(tsl.float(1), gi.getAONode().r, p.occlusion)).add(light), input.a);
|
|
46
|
+
},
|
|
47
|
+
// voxelSize is 0 until the first frame voxelized the scene
|
|
48
|
+
facts: () => (gi ? { resolution, voxelSize: +gi.volume.voxelSizeNode.value.toFixed(3) } : null) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Temporal antialiasing (three's TRAANode): averages jittered frames, so it also clears the dots of every stochastic effect before it (voxelGI, lightVolumes).
|
|
53
|
+
* Runs last in the hdr slot. It replaces MSAA while it is on. Moving things can trail; judge it in motion.
|
|
54
|
+
* @param {{ order?: number, enabled?: boolean, name?: string }} [o]
|
|
55
|
+
* @returns {PostEffect}
|
|
56
|
+
*/
|
|
57
|
+
export function temporalAA({ order = 900, enabled, name = 'temporalAA' } = {}) {
|
|
58
|
+
return { name, slot: 'hdr', order, enabled, needsBuffers: ['velocity'],
|
|
59
|
+
node: (input, { scenePass, camera, display }) => display.own(traa(input, scenePass.getTextureNode('depth'), scenePass.getTextureNode('velocity'), camera)) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Light shafts from the sun (or a point light) through gaps, from its shadow map (three's GodraysNode), blended over the picture in the hdr slot. The light and the things that make the
|
|
64
|
+
* gaps must cast shadows. It lights the air everywhere the shadow map says is lit, so a big open scene turns to haze: it reads best where most of the air is in shadow (a room with a window).
|
|
65
|
+
* @param {{ light?: any, density?: number, maxDensity?: number, falloff?: number, color?: any, steps?: number, setup?: (rays: any) => void, order?: number, enabled?: boolean, name?: string }} [o]
|
|
66
|
+
* light: default engine.lights.sun; one that is not in the scene or casts no shadow throws by name; density and maxDensity: how thick the air is, and the ceiling of what one pixel can gather; falloff: how fast the shafts fade away from the light;
|
|
67
|
+
* setup(rays): gets three's GodraysNode each time the chain builds it.
|
|
68
|
+
* @returns {PostEffect}
|
|
69
|
+
*/
|
|
70
|
+
export function sunShafts({ light, density = 2, maxDensity = 0.6, falloff = 2, color = new Color(1, 1, 1), steps = 60, setup, order = 200, enabled, name = 'sunShafts' } = {}) {
|
|
71
|
+
return { name, slot: 'hdr', order, enabled, params: { density, maxDensity, falloff, color: new Color(color) },
|
|
72
|
+
node(input, { engine, tsl, p, scenePass, camera, display }) {
|
|
73
|
+
const depth = scenePass.getTextureNode('depth'), sun = light ?? engine.lights?.sun;
|
|
74
|
+
// engine.lights.sun exists even under createEngine({ lights: false }), out of the scene; three's own error for a light with no shadow map names nothing
|
|
75
|
+
if (!sun?.parent || !sun.castShadow) throw codedError('post-effect', 'sunShafts: no light to follow; give sunShafts({ light }) a light that is in the scene and casts shadows (default: engine.lights.sun)');
|
|
76
|
+
const rays = display.own(godrays(depth, camera, sun));
|
|
77
|
+
Object.assign(rays, { density: p.density, maxDensity: p.maxDensity, distanceAttenuation: p.falloff });
|
|
78
|
+
rays.raymarchSteps.value = steps;
|
|
79
|
+
setup?.(rays);
|
|
80
|
+
const blended = depthAwareBlend(display.texture(input), rays.getTextureNode(), depth, camera, { blendColor: p.color });
|
|
81
|
+
return tsl.vec4(blended.rgb, input.a);
|
|
82
|
+
} };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Lit air inside a box: spot light cones and point light glows with their shadows (three's VolumeNodeMaterial), drawn at a fraction of the screen size (scale), blurred and added in the hdr slot.
|
|
87
|
+
* Reads point and spot lights only: three skips lights at infinity, so the sun and directional lights do nothing here (use sunShafts). Dithered, so temporalAA after it clears the pattern.
|
|
88
|
+
* @param {{ bounds: Box3, density?: number, steps?: number, scale?: number, blur?: number, scattering?: (tsl: any, at: { positionRay: any, density: any }) => any, order?: number, enabled?: boolean, name?: string }} o
|
|
89
|
+
* bounds: the box of air, required (the march covers it, so keep it tight); density: how thick the air is; scale: fraction of the screen size the air is drawn at; scattering: density per point, for smoke or ground fog
|
|
90
|
+
* (it gets the world position of the sample and the density uniform).
|
|
91
|
+
* @returns {PostEffect}
|
|
92
|
+
*/
|
|
93
|
+
export function lightVolumes({ bounds, density = 0.3, steps = 16, scale = 0.25, blur = 4, scattering, order = 200, enabled, name = 'lightVolumes' } = /** @type {any} */ ({})) {
|
|
94
|
+
if (!bounds?.isBox3) throw codedError('post-effect', 'lightVolumes: bounds is required, the box of air to light: lightVolumes({ bounds: new THREE.Box3(min, max) })');
|
|
95
|
+
return { name, slot: 'hdr', order, enabled, params: { density },
|
|
96
|
+
node(input, { tsl, p, scene, camera, scenePass, display }) {
|
|
97
|
+
const size = bounds.getSize(new Vector3()), mat = new VolumeNodeMaterial();
|
|
98
|
+
mat.steps = steps;
|
|
99
|
+
mat.offsetNode = bayer16(tsl.screenCoordinate);
|
|
100
|
+
mat.scatteringNode = ({ positionRay }) => (scattering ? scattering(tsl, { positionRay, density: p.density }) : p.density);
|
|
101
|
+
mat.depthNode = scenePass.getTextureNode('depth').sample(tsl.screenUV);
|
|
102
|
+
const box = new Mesh(new BoxGeometry(size.x, size.y, size.z), mat);
|
|
103
|
+
bounds.getCenter(box.position);
|
|
104
|
+
box.receiveShadow = true;
|
|
105
|
+
box.layers.set(VOLUME_LAYER); // not on the view camera: only the small pass below draws it, and voxel GI or probes never take it for geometry
|
|
106
|
+
scene.add(box);
|
|
107
|
+
const layers = new Layers(); layers.set(VOLUME_LAYER);
|
|
108
|
+
const air = display.pass(scene, camera, { depthBuffer: false, samples: 0 });
|
|
109
|
+
air.setLayers(layers); air.setResolutionScale(scale);
|
|
110
|
+
// a pass clears to the scene's background and the renderer's clear color; this one is added over the picture, so it must start from nothing
|
|
111
|
+
const draw = air.updateBefore;
|
|
112
|
+
const lamps = new Set();
|
|
113
|
+
let look = 0;
|
|
114
|
+
air.updateBefore = frame => {
|
|
115
|
+
// three lights a pass only with the lights on its layers; a new lamp is found within half a second
|
|
116
|
+
if (look-- <= 0) { look = 30; scene.traverse(l => { if ((l.isPointLight || l.isSpotLight) && !l.layers.isEnabled(VOLUME_LAYER)) { l.layers.enable(VOLUME_LAYER); lamps.add(l); } }); }
|
|
117
|
+
const r = frame.renderer, { background, backgroundNode } = scene, clear = r.getClearColor(new Color()), alpha = r.getClearAlpha();
|
|
118
|
+
// three prefers backgroundNode over background, so both go
|
|
119
|
+
scene.background = scene.backgroundNode = null; r.setClearColor(0x000000, 0);
|
|
120
|
+
try { draw.call(air, frame); } finally { scene.background = background; scene.backgroundNode = backgroundNode; r.setClearColor(clear, alpha); }
|
|
121
|
+
};
|
|
122
|
+
display.own({ dispose() { for (const l of lamps) l.layers.disable(VOLUME_LAYER); box.removeFromParent(); box.geometry.dispose(); mat.dispose(); } });
|
|
123
|
+
return tsl.vec4(input.rgb.add(display.own(gaussianBlur(air.getTextureNode(), blur)).rgb), input.a);
|
|
124
|
+
},
|
|
125
|
+
facts: () => ({ lights: 'point and spot only; the sun does nothing here (sunShafts)' }) };
|
|
126
|
+
}
|