File size: 7,611 Bytes
2b0432b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0d0800
2b0432b
 
 
 
 
 
 
 
c0d0800
 
 
 
 
 
 
 
c5a2609
 
 
 
c0d0800
 
 
 
 
 
2b0432b
 
 
 
 
44d2dac
2b0432b
 
44d2dac
2b0432b
44d2dac
 
 
 
 
2b0432b
 
 
44d2dac
2b0432b
 
44d2dac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b0432b
 
 
44d2dac
 
 
 
 
 
 
 
 
 
2b0432b
 
 
 
 
 
 
 
 
 
 
44d2dac
2b0432b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b02b26f
2b0432b
 
 
 
c0d0800
2b0432b
 
 
 
 
44d2dac
2b0432b
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Post-processing: god rays, bloom, ACES tone mapping and a filmic grade
// (split toning, vignette, grain, gentle chromatic aberration).
import * as THREE from 'three'
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js'
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js'
import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js'
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js'

const GodRaysShader = {
  uniforms: {
    tDiffuse: { value: null as THREE.Texture | null },
    uSun: { value: new THREE.Vector2(0.5, 0.5) },
    uStrength: { value: 0 },
    uAspect: { value: 16 / 9 },
    uTint: { value: new THREE.Color(1, 0.7, 0.45) },
  },
  vertexShader: /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
  fragmentShader: /* glsl */ `
    uniform sampler2D tDiffuse; uniform vec2 uSun; uniform float uStrength; uniform float uAspect; uniform vec3 uTint;
    varying vec2 vUv;
    float h(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
    void main() {
      vec4 base = texture2D(tDiffuse, vUv);
      if (uStrength <= 0.001) { gl_FragColor = base; return; }
      vec2 d = (uSun - vUv);
      float len = length(d * vec2(uAspect, 1.0));
      const int N = 40;
      vec2 stepv = d / float(N) * 0.85;
      vec2 uv = vUv + stepv * h(vUv * 913.0);
      float decay = 1.0;
      vec3 acc = vec3(0.0);
      for (int i = 0; i < N; i++) {
        uv += stepv;
        vec3 c = texture2D(tDiffuse, clamp(uv, 0.0, 1.0)).rgb;
        float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
        acc += c * smoothstep(2.0, 5.0, l) * decay;
        decay *= 0.965;
      }
      acc /= float(N);
      float fall = exp(-len * 1.6);
      gl_FragColor = vec4(base.rgb + acc * uTint * uStrength * fall * 2.2, base.a);
    }`,
}

// soft-compress extreme HDR highlights (sun disk, glints) so bloom stays a halo, not a flood
const HighlightShader = {
  uniforms: { tDiffuse: { value: null as THREE.Texture | null } },
  vertexShader: /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
  fragmentShader: /* glsl */ `
    uniform sampler2D tDiffuse; varying vec2 vUv;
    void main() {
      vec3 c = texture2D(tDiffuse, vUv).rgb;
      // NaN / Inf guard: a single bad pixel (0/0 in a wave normal, overflow in a sun glint) would
      // otherwise spread through the bloom blur and black out the whole frame for one frame
      if (any(isnan(c)) || any(isinf(c))) c = vec3(0.0);
      c = clamp(c, 0.0, 4096.0);
      float m = max(max(c.r, c.g), c.b);
      float k = m > 4.0 ? (4.0 + (m - 4.0) / (1.0 + (m - 4.0) * 0.35)) / m : 1.0;
      gl_FragColor = vec4(c * k, 1.0);
    }`,
}

const GradeShader = {
  uniforms: {
    tDiffuse: { value: null as THREE.Texture | null },
    uTime: { value: 0 },
    uVignette: { value: 0.32 },
    uGrain: { value: 0.010 },
    uFade: { value: 0 },
    uNight: { value: 0 },
    /** output (canvas) resolution — grain and sharpening work in output pixels */
    uRes: { value: new THREE.Vector2(1920, 1080) },
    uCA: { value: 0.0007 },
    /** internal supersampling factor of tDiffuse relative to uRes (1 = none) */
    uSS: { value: 1 },
    /** unsharp-mask amount applied after downsampling (0 = off; exports use ~0.18) */
    uSharpen: { value: 0 },
  },
  vertexShader: /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
  fragmentShader: /* glsl */ `
    uniform sampler2D tDiffuse; uniform float uTime; uniform float uVignette; uniform float uGrain; uniform float uFade; uniform float uNight; uniform vec2 uRes; uniform float uCA; uniform float uSS; uniform float uSharpen;
    varying vec2 vUv;
    float h(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
    // Downsampling fetch. tDiffuse is uSS× larger than the output: at exactly 2× one bilinear tap
    // at the output pixel centre is an exact 2×2 box filter; for other factors four quarter-pixel
    // taps make a tent filter so that nothing crawls or aliases.
    vec3 fetch(vec2 uv) {
      if (uSS < 1.01 || abs(uSS - 2.0) < 0.01) return texture2D(tDiffuse, uv).rgb;
      vec2 q = 0.25 / uRes;
      return 0.25 * (texture2D(tDiffuse, uv + vec2(-q.x, -q.y)).rgb + texture2D(tDiffuse, uv + vec2(q.x, -q.y)).rgb
                   + texture2D(tDiffuse, uv + vec2(-q.x, q.y)).rgb + texture2D(tDiffuse, uv + vec2(q.x, q.y)).rgb);
    }
    // gentle lens chromatic aberration toward the corners
    vec3 fetchCA(vec2 uv) {
      vec2 c = uv - 0.5;
      vec2 off = c * dot(c, c) * uCA * 8.0;
      return vec3(fetch(uv + off).r, fetch(uv).g, fetch(uv - off).b);
    }
    void main() {
      vec2 c = vUv - 0.5;
      float r2 = dot(c, c);
      vec3 col = fetchCA(vUv);
      if (uSharpen > 0.001) {
        // luminance-only unsharp mask on the downsampled image (no colour fringing)
        vec2 px = 1.0 / uRes;
        vec3 n = fetchCA(vUv + vec2(0.0, px.y)), s = fetchCA(vUv - vec2(0.0, px.y));
        vec3 e = fetchCA(vUv + vec2(px.x, 0.0)), w = fetchCA(vUv - vec2(px.x, 0.0));
        vec3 lw = vec3(0.2126, 0.7152, 0.0722);
        float lap = 4.0 * dot(col, lw) - dot(n, lw) - dot(s, lw) - dot(e, lw) - dot(w, lw);
        col *= 1.0 + uSharpen * clamp(lap, -0.35, 0.35) / max(dot(col, lw), 0.03);
      }
      // split toning: warm highlights, teal-blue shadows (stronger at night)
      float l = dot(col, vec3(0.2126, 0.7152, 0.0722));
      vec3 shadowTint = mix(vec3(0.96, 1.0, 1.05), vec3(0.9, 0.98, 1.12), uNight);
      vec3 hiTint = vec3(1.04, 1.0, 0.94);
      col *= mix(shadowTint, hiTint, smoothstep(0.15, 0.75, l));
      // gentle S-curve
      col = mix(col, col * col * (3.0 - 2.0 * col), 0.22);
      // vignette
      float vig = 1.0 - uVignette * smoothstep(0.12, 0.75, r2 * 1.6);
      col *= vig;
      // film grain (luma weighted, frame-locked to film time so export is deterministic)
      float g = h(floor(vUv * uRes) + fract(uTime * 24.0) * 97.0) - 0.5;
      col += g * uGrain * (0.6 + 0.4 * (1.0 - l));
      col *= 1.0 - uFade;
      gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
    }`,
}

export interface Post {
  composer: EffectComposer
  bloom: UnrealBloomPass
  rays: ShaderPass
  grade: ShaderPass
  setSize: (w: number, h: number) => void
}

export function createPost(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, w: number, h: number, samples = 4): Post {
  const rt = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType, samples })
  rt.depthTexture = new THREE.DepthTexture(w, h, THREE.FloatType)
  const composer = new EffectComposer(renderer, rt)
  composer.addPass(new RenderPass(scene, camera))
  const rays = new ShaderPass(GodRaysShader)
  composer.addPass(rays)
  composer.addPass(new ShaderPass(HighlightShader))
  const bloom = new UnrealBloomPass(new THREE.Vector2(w, h), 0.5, 0.55, 0.92)
  composer.addPass(bloom)
  composer.addPass(new OutputPass())
  const grade = new ShaderPass(GradeShader)
  composer.addPass(grade)
  // W × H is the internal (possibly supersampled) size; the caller sets grade.uRes / uSS to the output size
  const setSize = (W: number, H: number) => {
    composer.setSize(W, H)
    rays.uniforms.uAspect.value = W / H
  }
  setSize(w, h)
  return { composer, bloom, rays, grade, setSize }
}