0b3ab76405
Immich connections stay server-side with an encrypted API key, albums can be imported, and photos are only sent back when an event's push button is pressed: originals upload once, edited photos re-render, and edits hashes plus checksums skip anything already in Immich. This also lands the accompanying editor, cloud and administration work that was still uncommitted. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1748 lines
66 KiB
TypeScript
1748 lines
66 KiB
TypeScript
import type { LensCorrection } from '../lib/lensfun';
|
||
import type { Edits, GeometryEdits } from '../types';
|
||
import { buildSampler, clamp01 } from '../lib/curves';
|
||
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
|
||
import { buildLocalMasks, maskSignature } from './masks';
|
||
|
||
const VERT = `#version 300 es
|
||
layout(location = 0) in vec2 a_pos;
|
||
out vec2 v_uv;
|
||
void main(){
|
||
v_uv = a_pos * 0.5 + 0.5;
|
||
gl_Position = vec4(a_pos, 0.0, 1.0);
|
||
}`;
|
||
|
||
const GRADE_FRAG = `#version 300 es
|
||
precision highp float;
|
||
in vec2 v_uv;
|
||
out vec4 outColor;
|
||
|
||
uniform sampler2D u_src;
|
||
uniform sampler2D u_curve;
|
||
// Detail-preserving denoise, produced on the server at proxy resolution and
|
||
// blended here before any grading so it grades exactly like the source.
|
||
uniform sampler2D u_den;
|
||
uniform float u_denMix;
|
||
uniform vec2 u_srcSize;
|
||
uniform vec2 u_frameSize;
|
||
uniform vec4 u_crop;
|
||
uniform vec4 u_valid;
|
||
uniform float u_angle;
|
||
uniform int u_quarter;
|
||
uniform vec2 u_flip;
|
||
uniform float u_upscale;
|
||
/** Explicit source mip level: 0 at 1:1 or magnification, log2(scale) when shrinking. */
|
||
uniform float u_srcLod;
|
||
|
||
uniform float u_temp;
|
||
uniform float u_tint;
|
||
uniform float u_exposure;
|
||
uniform float u_recovery;
|
||
uniform float u_contrast;
|
||
uniform float u_highlights;
|
||
uniform float u_shadows;
|
||
uniform float u_whites;
|
||
uniform float u_blacks;
|
||
uniform float u_vibrance;
|
||
uniform float u_saturation;
|
||
uniform float u_bw;
|
||
uniform vec3 u_bwFilter;
|
||
uniform float u_bwFilterAmt;
|
||
uniform float u_hue[8];
|
||
uniform float u_sat[8];
|
||
uniform float u_lum[8];
|
||
uniform float u_gSh;
|
||
uniform float u_gSs;
|
||
uniform float u_gHi;
|
||
uniform float u_gHs;
|
||
uniform float u_gBal;
|
||
uniform float u_pick;
|
||
uniform vec2 u_pickUv;
|
||
|
||
// Spot healing: xy is the spot centre, zw the centre of the sampled patch.
|
||
uniform int u_healCount;
|
||
uniform vec4 u_healSpot[24];
|
||
// x = radius as a fraction of the source width, y = feather (0–1).
|
||
uniform vec2 u_healSize[24];
|
||
|
||
// Local adjustments: four masks packed into one RGBA texture.
|
||
uniform sampler2D u_masks;
|
||
uniform int u_localCount;
|
||
uniform vec4 u_localAdj[4]; // exposure, contrast, temp, tint
|
||
uniform vec4 u_localAdj2[4]; // saturation, highlights, shadows, unused
|
||
uniform vec4 u_localRange[4]; // lumaMin, lumaMax, hue, hueRange
|
||
uniform vec4 u_localRange2[4]; // satMin, enabled, unused, unused
|
||
|
||
// Lens/perspective correction: distortion, vertical, horizontal, rotation.
|
||
uniform vec4 u_geom;
|
||
uniform float u_geomScale;
|
||
|
||
// Lensfun calibration maps: source coordinates, TCA offsets and vignette gains.
|
||
uniform sampler2D u_lensGeom;
|
||
uniform sampler2D u_lensTca;
|
||
uniform sampler2D u_lensVig;
|
||
uniform ivec2 u_lensGeomSize;
|
||
uniform ivec2 u_lensTcaSize;
|
||
uniform ivec2 u_lensVigSize;
|
||
uniform int u_lensFlags;
|
||
uniform float u_lensScale;
|
||
/** Screen-space split for the Optics panel; negative means no split. */
|
||
uniform float u_lensSplit;
|
||
|
||
const float HUE_CENTERS[8] = float[8](0.0, 32.0, 62.0, 120.0, 180.0, 230.0, 280.0, 320.0);
|
||
|
||
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
|
||
|
||
// Float correction maps are sampled with texelFetch and filtered by hand so the
|
||
// renderer does not depend on OES_texture_float_linear.
|
||
vec4 lensSample(sampler2D map, ivec2 size, vec2 uv) {
|
||
vec2 pos = clamp(uv, 0.0, 1.0) * vec2(size - ivec2(1));
|
||
ivec2 i0 = ivec2(floor(pos));
|
||
ivec2 i1 = min(i0 + ivec2(1), size - ivec2(1));
|
||
vec2 f = fract(pos);
|
||
vec4 a = texelFetch(map, clamp(i0, ivec2(0), size - ivec2(1)), 0);
|
||
vec4 b = texelFetch(map, ivec2(i1.x, i0.y), 0);
|
||
vec4 c = texelFetch(map, ivec2(i0.x, i1.y), 0);
|
||
vec4 d = texelFetch(map, i1, 0);
|
||
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
|
||
}
|
||
|
||
vec3 toLinear(vec3 c){
|
||
c = max(c, vec3(0.0));
|
||
return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
|
||
}
|
||
|
||
vec3 toSRGB(vec3 c){
|
||
c = max(c, vec3(0.0));
|
||
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
|
||
}
|
||
|
||
vec3 rgb2hsv(vec3 c){
|
||
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
|
||
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
|
||
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
|
||
float d = q.x - min(q.w, q.y);
|
||
float e = 1.0e-10;
|
||
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
|
||
}
|
||
|
||
vec3 hsv2rgb(vec3 c){
|
||
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
|
||
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
|
||
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
|
||
}
|
||
|
||
// Catmull-Rom weights for one axis; t is the fraction inside a texel.
|
||
vec4 cubicWeights(float t){
|
||
float t2 = t * t;
|
||
float t3 = t2 * t;
|
||
return vec4(
|
||
-0.5 * t3 + t2 - 0.5 * t,
|
||
1.5 * t3 - 2.5 * t2 + 1.0,
|
||
-1.5 * t3 + 2.0 * t2 + 0.5 * t,
|
||
0.5 * t3 - 0.5 * t2
|
||
);
|
||
}
|
||
|
||
// Bicubic magnification. Bilinear leaves texel-sized squares with hard edges
|
||
// once a photo is zoomed past 1:1, which reads as blocky rather than soft.
|
||
vec3 sampleBicubic(sampler2D tex, vec2 uv, vec2 size){
|
||
vec2 coord = uv * size - 0.5;
|
||
vec2 base = floor(coord);
|
||
vec2 f = coord - base;
|
||
vec4 wx = cubicWeights(f.x);
|
||
vec4 wy = cubicWeights(f.y);
|
||
float ax[4] = float[4](wx.x, wx.y, wx.z, wx.w);
|
||
float ay[4] = float[4](wy.x, wy.y, wy.z, wy.w);
|
||
vec3 sum = vec3(0.0);
|
||
for (int j = 0; j < 4; j++){
|
||
for (int i = 0; i < 4; i++){
|
||
vec2 p = (base + vec2(float(i) - 1.0, float(j) - 1.0) + 0.5) / size;
|
||
sum += textureLod(tex, clamp(p, vec2(0.0), vec2(1.0)), u_srcLod).rgb * ax[i] * ay[j];
|
||
}
|
||
}
|
||
return sum;
|
||
}
|
||
|
||
// Mirrors warpGeometryPoint() on the CPU. Perspective is applied as a
|
||
// projective divide, distortion as a radial scale, then the whole frame is
|
||
// scaled up so corrected corners can be cropped away with the Scale slider.
|
||
vec2 warpGeometry(vec2 s){
|
||
vec2 q = s - 0.5;
|
||
q = q / max(0.1, u_geomScale);
|
||
float ca = cos(u_geom.w);
|
||
float sa = sin(u_geom.w);
|
||
q = vec2(q.x * ca - q.y * sa, q.x * sa + q.y * ca);
|
||
q.x /= max(0.15, 1.0 + u_geom.y * q.y * 2.0);
|
||
q.y /= max(0.15, 1.0 + u_geom.z * q.x * 2.0);
|
||
float aspect = u_srcSize.x / max(1.0, u_srcSize.y);
|
||
vec2 aq = vec2(q.x * aspect, q.y);
|
||
float r2 = dot(aq, aq);
|
||
q = vec2(aq.x * (1.0 + u_geom.x * r2) / aspect, aq.y * (1.0 + u_geom.x * r2));
|
||
return q + 0.5;
|
||
}
|
||
|
||
void main(){
|
||
// The eyedropper renders one pixel at an arbitrary point, so the mapping below
|
||
// takes its coordinate from the uniform instead of the fragment position.
|
||
vec2 outUv = u_pick > 0.5 ? u_pickUv : v_uv;
|
||
vec2 frame = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(outUv.x, 1.0 - outUv.y));
|
||
|
||
// Only the cropped area carries picture data; the rest is letterbox when the
|
||
// view is zoomed out or the window aspect differs from the photo.
|
||
if (frame.x < u_valid.x || frame.y < u_valid.y ||
|
||
frame.x > u_valid.x + u_valid.z || frame.y > u_valid.y + u_valid.w) {
|
||
outColor = vec4(0.035, 0.035, 0.04, 1.0);
|
||
return;
|
||
}
|
||
|
||
vec2 p = (frame - 0.5) * u_frameSize;
|
||
float a = -(u_angle + float(u_quarter) * 1.57079632679);
|
||
float ca = cos(a);
|
||
float sa = sin(a);
|
||
vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca);
|
||
vec2 s = rp / u_srcSize + 0.5;
|
||
s = (s - 0.5) * u_flip + 0.5;
|
||
if (u_geom.x != 0.0 || u_geom.y != 0.0 || u_geom.z != 0.0 || u_geom.w != 0.0 || u_geomScale != 1.0) {
|
||
s = warpGeometry(s);
|
||
}
|
||
|
||
if (s.x < 0.0 || s.x > 1.0 || s.y < 0.0 || s.y > 1.0) {
|
||
outColor = vec4(0.035, 0.035, 0.04, 1.0);
|
||
return;
|
||
}
|
||
|
||
// Lens profile correction happens in source space, after the manual
|
||
// perspective warp. The map stores the source pixel that should appear at
|
||
// each output pixel; TCA stores small red/blue offsets around that point.
|
||
bool showLens = u_lensSplit < 0.0 || outUv.x >= u_lensSplit;
|
||
vec2 lensQ = s;
|
||
vec2 lensCoord = s;
|
||
if (showLens && (u_lensFlags & 3) != 0) {
|
||
lensQ = 0.5 + (s - 0.5) / max(0.5, u_lensScale);
|
||
lensCoord = (u_lensFlags & 1) != 0
|
||
? clamp(lensSample(u_lensGeom, u_lensGeomSize, lensQ).rg, 0.0, 1.0)
|
||
: lensQ;
|
||
}
|
||
vec2 uv = lensCoord;
|
||
vec3 src;
|
||
if (showLens && (u_lensFlags & 2) != 0) {
|
||
vec4 t = lensSample(u_lensTca, u_lensTcaSize, lensCoord);
|
||
src = vec3(
|
||
textureLod(u_src, clamp(lensCoord + t.rg, 0.0, 1.0), u_srcLod).r,
|
||
textureLod(u_src, lensCoord, u_srcLod).g,
|
||
textureLod(u_src, clamp(lensCoord + t.ba, 0.0, 1.0), u_srcLod).b
|
||
);
|
||
} else {
|
||
src = u_upscale > 0.5
|
||
? sampleBicubic(u_src, uv, u_srcSize)
|
||
: textureLod(u_src, uv, u_srcLod).rgb;
|
||
}
|
||
if (showLens && (u_lensFlags & 4) != 0) {
|
||
src *= lensSample(u_lensVig, u_lensVigSize, lensQ).rgb;
|
||
}
|
||
|
||
// The denoised proxy is the same frame as the source, so it samples at the
|
||
// same coordinate and is mixed in before white balance and tone. Grading the
|
||
// blend rather than the source keeps the edit looking identical with the
|
||
// denoise at 0 and at 100.
|
||
if (u_denMix > 0.0) {
|
||
src = mix(src, textureLod(u_den, uv, u_srcLod).rgb, u_denMix);
|
||
}
|
||
|
||
// Eyedropper: hand back the untouched source colour at the sampled point.
|
||
if (u_pick > 0.5) {
|
||
outColor = vec4(src, 1.0);
|
||
return;
|
||
}
|
||
|
||
// Spot healing copies a clean patch over the blemish, feathered at the rim.
|
||
// It runs on the source colour, before white balance and tone, so a healed
|
||
// spot grades exactly like the pixels around it. uv and the patch offset are
|
||
// both in source space, so it follows crops and zooms.
|
||
if (u_healCount > 0) {
|
||
// Convert a uv step in y (a fraction of the height) into the same pixel
|
||
// scale as x (a fraction of the width), so the brush stays circular.
|
||
float srcAspect = u_srcSize.y / max(1.0, u_srcSize.x);
|
||
for (int i = 0; i < 24; i++) {
|
||
if (i >= u_healCount) break;
|
||
vec4 spot = u_healSpot[i];
|
||
float radius = max(u_healSize[i].x, 1e-5);
|
||
vec2 d = (uv - spot.xy) * vec2(1.0, srcAspect);
|
||
float dist = length(d) / radius;
|
||
if (dist >= 1.0) continue;
|
||
// Feather only shapes the outer rim: at 100 the patch still fully covers
|
||
// the inner half, so a brush sized to the blemish never leaves a ring of
|
||
// the original around it.
|
||
float feather = clamp(u_healSize[i].y * 0.5, 0.0, 0.5);
|
||
float falloff = feather > 0.001
|
||
? 1.0 - smoothstep(1.0 - feather, 1.0, dist)
|
||
: 1.0;
|
||
vec2 patchUv = clamp(uv + (spot.zw - spot.xy), vec2(0.0), vec2(1.0));
|
||
src = mix(src, textureLod(u_src, patchUv, u_srcLod).rgb, falloff);
|
||
}
|
||
}
|
||
|
||
vec3 col = toLinear(clamp(src, 0.0, 1.0));
|
||
|
||
// White balance (relative to as-shot)
|
||
float t = u_temp / 100.0;
|
||
float ti = u_tint / 100.0;
|
||
vec3 wb = vec3(1.0 + 0.30 * t + 0.06 * ti, 1.0 - 0.16 * ti, 1.0 - 0.26 * t + 0.06 * ti);
|
||
col *= wb / max(0.05, luma(wb));
|
||
|
||
// Exposure
|
||
col *= exp2(u_exposure);
|
||
|
||
// Highlight recovery: compress the shoulder instead of clipping it. Scaling
|
||
// every channel by one factor keeps hue, so recovered skin stays skin instead
|
||
// of turning grey or yellow.
|
||
float rec = clamp(u_recovery / 100.0, 0.0, 1.0);
|
||
if (rec > 0.001) {
|
||
float lum = max(luma(col), 1e-5);
|
||
float knee = 0.7;
|
||
float over = max(lum - knee, 0.0);
|
||
if (over > 0.0) {
|
||
float pulled = knee + over / (1.0 + over * (2.0 + 12.0 * rec));
|
||
col *= mix(1.0, pulled / lum, rec);
|
||
}
|
||
}
|
||
|
||
// Tonal range
|
||
float lm = clamp(luma(col), 0.0, 1.0);
|
||
col += (u_shadows / 100.0) * 0.45 * pow(1.0 - lm, 3.0);
|
||
col += (u_highlights / 100.0) * 0.50 * pow(lm, 2.0);
|
||
col += (u_whites / 100.0) * 0.34 * smoothstep(0.55, 1.0, lm);
|
||
col += (u_blacks / 100.0) * 0.13 * smoothstep(0.30, 0.0, lm);
|
||
|
||
vec3 srgb = clamp(toSRGB(col), 0.0, 1.0);
|
||
|
||
// Contrast
|
||
srgb = clamp((srgb - 0.5) * (1.0 + (u_contrast / 100.0) * 1.1) + 0.5, 0.0, 1.0);
|
||
|
||
// Tone curve (composite baked with per-channel curves)
|
||
srgb = vec3(
|
||
texture(u_curve, vec2(clamp(srgb.r, 0.0, 1.0), 0.5)).r,
|
||
texture(u_curve, vec2(clamp(srgb.g, 0.0, 1.0), 0.5)).g,
|
||
texture(u_curve, vec2(clamp(srgb.b, 0.0, 1.0), 0.5)).b
|
||
);
|
||
|
||
// HSL bands
|
||
vec3 hsv = rgb2hsv(srgb);
|
||
float hdeg = hsv.x * 360.0;
|
||
float hueWeight = smoothstep(0.02, 0.18, hsv.y);
|
||
float hShift = 0.0;
|
||
float sShift = 0.0;
|
||
float lShift = 0.0;
|
||
float wsum = 0.0;
|
||
for (int i = 0; i < 8; i++) {
|
||
float d = abs(hdeg - HUE_CENTERS[i]);
|
||
d = min(d, 360.0 - d);
|
||
float w = smoothstep(52.0, 0.0, d);
|
||
hShift += w * u_hue[i];
|
||
sShift += w * u_sat[i];
|
||
lShift += w * u_lum[i];
|
||
wsum += w;
|
||
}
|
||
float norm = max(wsum, 0.0001);
|
||
hShift = (hShift / norm) * hueWeight;
|
||
sShift = sShift / norm;
|
||
lShift = lShift / norm;
|
||
|
||
hsv.x = fract(hsv.x + (hShift / 100.0) * 0.08 + 1.0);
|
||
float satMul = sShift >= 0.0 ? 1.0 + (sShift / 100.0) * 0.8 : 1.0 + sShift / 100.0;
|
||
hsv.y = clamp(hsv.y * satMul, 0.0, 1.0);
|
||
hsv.z = clamp(hsv.z * (1.0 + (lShift / 100.0) * 0.5), 0.0, 1.0);
|
||
srgb = hsv2rgb(hsv);
|
||
|
||
if (u_bw > 0.5) {
|
||
// A colored filter over the lens changes which hues turn dark in the print:
|
||
// red drops blue skies, green lifts foliage, blue opens up shadows. The
|
||
// strength blends the transmission back towards a neutral filter.
|
||
vec3 bwTint = mix(vec3(1.0), u_bwFilter, clamp(u_bwFilterAmt, 0.0, 1.0));
|
||
float wl = max(0.05, luma(bwTint));
|
||
srgb = vec3(luma(srgb * bwTint) / wl);
|
||
}
|
||
|
||
// Vibrance and saturation
|
||
vec3 satRgb = clamp(srgb, 0.0, 1.0);
|
||
float mx = max(max(satRgb.r, satRgb.g), satRgb.b);
|
||
float mn = min(min(satRgb.r, satRgb.g), satRgb.b);
|
||
float curSat = mx - mn;
|
||
float gray = luma(satRgb);
|
||
srgb = mix(vec3(gray), satRgb, clamp(1.0 + (u_vibrance / 100.0) * (1.0 - curSat) * 0.9, 0.0, 3.0));
|
||
srgb = mix(vec3(luma(srgb)), srgb, clamp(1.0 + u_saturation / 100.0, 0.0, 3.0));
|
||
|
||
// Color grading
|
||
float gl = clamp(luma(srgb), 0.0, 1.0);
|
||
float bal = u_gBal / 100.0;
|
||
float sMask = pow(1.0 - gl, 2.0 + bal);
|
||
float hMask = pow(gl, 2.0 - bal);
|
||
vec3 shCol = hsv2rgb(vec3(u_gSh, 1.0, 1.0));
|
||
shCol -= vec3(luma(shCol));
|
||
vec3 hiCol = hsv2rgb(vec3(u_gHi, 1.0, 1.0));
|
||
hiCol -= vec3(luma(hiCol));
|
||
srgb += shCol * (u_gSs / 100.0) * 0.45 * sMask;
|
||
srgb += hiCol * (u_gHs / 100.0) * 0.45 * hMask;
|
||
|
||
// Local layers ride on top of the global grade. The mask texture carries one
|
||
// layer per channel; the shape is already feathered, while the range controls
|
||
// are evaluated from the source colour so they follow skin, sky or shadow
|
||
// regardless of how the global grade moved them.
|
||
if (u_localCount > 0) {
|
||
vec4 maskTexel = texture(u_masks, uv);
|
||
float srcLuma = luma(clamp(src, 0.0, 1.0));
|
||
vec3 srcHsv = rgb2hsv(clamp(src, 0.0, 1.0));
|
||
for (int i = 0; i < 4; i++) {
|
||
if (i >= u_localCount) break;
|
||
float m = i == 0 ? maskTexel.r : i == 1 ? maskTexel.g : i == 2 ? maskTexel.b : maskTexel.a;
|
||
if (m < 0.002) continue;
|
||
vec4 adj = u_localAdj[i];
|
||
vec4 adj2 = u_localAdj2[i];
|
||
vec4 range = u_localRange[i];
|
||
vec4 range2 = u_localRange2[i];
|
||
|
||
if (range2.y > 0.5) {
|
||
float lw = smoothstep(range.x - 0.02, range.x + 0.02, srcLuma) *
|
||
(1.0 - smoothstep(range.y - 0.02, range.y + 0.02, srcLuma));
|
||
float hw = 1.0;
|
||
if (range.w < 179.0) {
|
||
float d = abs(srcHsv.x * 360.0 - range.z);
|
||
d = min(d, 360.0 - d);
|
||
hw = 1.0 - smoothstep(range.w - 8.0, range.w + 8.0, d);
|
||
}
|
||
float sw = smoothstep(range2.x - 0.02, range2.x + 0.02, srcHsv.y);
|
||
m *= lw * hw * sw;
|
||
}
|
||
if (m < 0.002) continue;
|
||
|
||
vec3 lin = toLinear(clamp(srgb, 0.0, 1.0));
|
||
lin *= exp2(adj.x);
|
||
float lt = adj.z / 100.0;
|
||
float lti = adj.w / 100.0;
|
||
vec3 lwb = vec3(1.0 + 0.30 * lt + 0.06 * lti, 1.0 - 0.16 * lti, 1.0 - 0.26 * lt + 0.06 * lti);
|
||
lin *= lwb / max(0.05, luma(lwb));
|
||
vec3 local = toSRGB(clamp(lin, 0.0, 1.0));
|
||
local = clamp((local - 0.5) * (1.0 + (adj.y / 100.0) * 1.1) + 0.5, 0.0, 1.0);
|
||
float ll = clamp(luma(local), 0.0, 1.0);
|
||
local += (adj2.z / 100.0) * 0.45 * pow(1.0 - ll, 3.0);
|
||
local += (adj2.y / 100.0) * 0.50 * pow(ll, 2.0);
|
||
// Desaturate in linear light. Mixing towards a gamma-space luma drags a
|
||
// saturated colour towards a much darker grey (a pure red collapses to
|
||
// near black), so pulling saturation down made the masked area look muddy
|
||
// instead of simply calmer. Scaling chroma around the linear luminance
|
||
// keeps the brightness of the patch where it was.
|
||
vec3 localLin = toLinear(clamp(local, 0.0, 1.0));
|
||
float localLuma = luma(localLin);
|
||
localLin = mix(vec3(localLuma), localLin, clamp(1.0 + adj2.x / 100.0, 0.0, 2.0));
|
||
local = clamp(toSRGB(max(localLin, vec3(0.0))), 0.0, 1.0);
|
||
srgb = mix(srgb, clamp(local, 0.0, 1.0), m);
|
||
}
|
||
}
|
||
|
||
outColor = vec4(clamp(srgb, 0.0, 1.0), 1.0);
|
||
}`;
|
||
|
||
const BLUR_FRAG = `#version 300 es
|
||
precision highp float;
|
||
in vec2 v_uv;
|
||
out vec4 outColor;
|
||
uniform sampler2D u_tex;
|
||
uniform vec2 u_dir;
|
||
void main(){
|
||
vec3 s = texture(u_tex, v_uv).rgb * 0.2270270270;
|
||
s += texture(u_tex, v_uv + u_dir * 1.3846153846).rgb * 0.3162162162;
|
||
s += texture(u_tex, v_uv - u_dir * 1.3846153846).rgb * 0.3162162162;
|
||
s += texture(u_tex, v_uv + u_dir * 3.2307692308).rgb * 0.0702702703;
|
||
s += texture(u_tex, v_uv - u_dir * 3.2307692308).rgb * 0.0702702703;
|
||
outColor = vec4(s, 1.0);
|
||
}`;
|
||
|
||
const FINISH_FRAG = `#version 300 es
|
||
precision highp float;
|
||
in vec2 v_uv;
|
||
out vec4 outColor;
|
||
uniform sampler2D u_graded;
|
||
uniform sampler2D u_blurSmall;
|
||
uniform sampler2D u_blurBig;
|
||
uniform float u_texture;
|
||
uniform float u_clarity;
|
||
uniform float u_dehaze;
|
||
uniform float u_sharpen;
|
||
uniform float u_sharpenMask;
|
||
uniform float u_detailScale;
|
||
uniform float u_lensSoft;
|
||
uniform float u_nr;
|
||
uniform float u_chroma;
|
||
uniform float u_chromaDetail;
|
||
uniform float u_fringePurple;
|
||
uniform float u_fringeGreen;
|
||
uniform float u_vigAmt;
|
||
uniform float u_vigMid;
|
||
uniform float u_vigFeather;
|
||
uniform float u_grainAmt;
|
||
uniform float u_grainSize;
|
||
uniform float u_grainRough;
|
||
uniform float u_clip;
|
||
uniform vec4 u_crop;
|
||
uniform vec4 u_grainFrame;
|
||
uniform vec2 u_grainSpace;
|
||
uniform vec2 u_outSize;
|
||
uniform vec2 u_frameSize;
|
||
uniform vec2 u_grainFlip;
|
||
uniform float u_grainRot;
|
||
uniform float u_grainUnits;
|
||
uniform float u_aspect;
|
||
uniform float u_proofEnable;
|
||
uniform vec3 u_proofPaper;
|
||
uniform float u_proofBlack;
|
||
uniform float u_gamut;
|
||
|
||
float luma(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
|
||
|
||
// Chroma axes of a graded texel, so a blur can act on colour alone.
|
||
vec2 chromaAt(vec2 uv){
|
||
vec3 s = texture(u_graded, uv).rgb;
|
||
float y = luma(s);
|
||
return vec2(s.r - y, s.b - y);
|
||
}
|
||
|
||
// Integer hash (Dave Hoskins). A sin-based hash correlates at whole-pixel
|
||
// lattice points, which is exactly what drew diagonal streaks through grain.
|
||
float hash(vec2 p){
|
||
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
|
||
p3 += dot(p3, p3.yzx + 33.33);
|
||
return fract((p3.x + p3.y) * p3.z);
|
||
}
|
||
|
||
// Smooth value noise: interpolates between lattice samples instead of hashing
|
||
// whole blocks, so neighbouring pixels never sit at identical values.
|
||
float valueNoise(vec2 p){
|
||
vec2 i = floor(p);
|
||
vec2 f = fract(p);
|
||
vec2 u = f * f * (3.0 - 2.0 * f);
|
||
return mix(
|
||
mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
|
||
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
|
||
u.y
|
||
);
|
||
}
|
||
|
||
void main(){
|
||
vec3 c = texture(u_graded, v_uv).rgb;
|
||
vec3 bs = texture(u_blurSmall, v_uv).rgb;
|
||
vec3 bb = texture(u_blurBig, v_uv).rgb;
|
||
|
||
// Noise reduction blends towards a smoothed version first.
|
||
float nr = clamp(u_nr / 100.0, 0.0, 1.0);
|
||
vec3 base = mix(c, mix(bs, bb, 0.5), nr * 0.6);
|
||
|
||
// Local contrast / detail work on gamma encoded values.
|
||
vec3 detailSmall = c - bs;
|
||
vec3 detailBig = base - bb;
|
||
vec3 col = base;
|
||
// Masking restricts sharpening to edges. Left at 0 the whole frame is
|
||
// sharpened; raised, only differences large enough to be structure qualify,
|
||
// so grain and skin texture stop picking up acutance.
|
||
float sm = clamp(u_sharpenMask / 100.0, 0.0, 1.0);
|
||
float sharpenAmt = (u_sharpen / 100.0) * 1.35;
|
||
if (sm > 0.001) {
|
||
float edge = smoothstep(0.003, 0.012 + sm * 0.085, length(detailSmall));
|
||
sharpenAmt *= mix(1.0, edge, sm);
|
||
}
|
||
col += detailSmall * ((u_texture / 100.0) * 0.9 + sharpenAmt);
|
||
// Lens softness compensation: add acutance towards the corners, where most
|
||
// wide/normal lenses lose resolving power. It is deliberately edge-weighted
|
||
// so the centre does not double-sharpen.
|
||
float lensSoft = clamp(u_lensSoft / 100.0, 0.0, 1.0);
|
||
if (lensSoft > 0.001) {
|
||
vec2 q = (v_uv - 0.5) * vec2(u_aspect, 1.0);
|
||
float edge = smoothstep(0.18, 0.72, length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5)));
|
||
col += detailSmall * lensSoft * edge * 1.1;
|
||
}
|
||
col += detailBig * (u_clarity / 100.0) * 1.25;
|
||
|
||
// Colour noise reduction: smooth only the chroma axes. Luminance is left alone,
|
||
// so structure and luminance grain survive while the red/green blotches that
|
||
// dominate high ISO proxies disappear. Detail shrinks the radius, keeping
|
||
// small colour differences (signed reds, fabric dyes) from washing together.
|
||
float ch = clamp(u_chroma / 100.0, 0.0, 1.0);
|
||
if (ch > 0.001) {
|
||
vec2 texel = 1.0 / vec2(textureSize(u_graded, 0));
|
||
float rad = mix(0.8, 4.5, ch) * mix(1.4, 0.55, clamp(u_chromaDetail / 100.0, 0.0, 1.0)) * u_detailScale;
|
||
// Taps on a circle, not on the axes: axis-aligned samples land on the same
|
||
// phase of a fine colour pattern and leave it untouched.
|
||
// Two rings at half and full radius: a single ring can land in phase with a
|
||
// fine repeating colour pattern and barely change it.
|
||
vec2 acc = chromaAt(v_uv);
|
||
for (int i = 0; i < 8; i++) {
|
||
float a = (float(i) + 0.5) * 0.7853981634;
|
||
vec2 dir = vec2(cos(a), sin(a)) * texel * rad;
|
||
acc += chromaAt(v_uv + dir);
|
||
acc += chromaAt(v_uv + dir * 0.5);
|
||
}
|
||
vec2 smoothed = acc / 17.0;
|
||
float y = luma(col);
|
||
vec2 chroma = mix(vec2(col.r - y, col.b - y), smoothed, ch * 0.9);
|
||
col.r = y + chroma.x;
|
||
col.b = y + chroma.y;
|
||
col.g = (y - 0.2126 * col.r - 0.0722 * col.b) / 0.7152;
|
||
}
|
||
|
||
// Defringe: lens CA puts a magenta or green cast on high-contrast edges. Only
|
||
// pixels that differ from their neighbourhood and already lean that way are
|
||
// pulled back towards green/neutral, so ordinary purple subjects stay put.
|
||
float dp = clamp(u_fringePurple / 100.0, 0.0, 1.0);
|
||
float dg = clamp(u_fringeGreen / 100.0, 0.0, 1.0);
|
||
if (dp + dg > 0.001) {
|
||
float edge = smoothstep(0.02, 0.12, length(col - bs));
|
||
float purple = clamp((min(col.r, col.b) - col.g) * 6.0, 0.0, 1.0) * edge * dp;
|
||
float green = clamp((col.g - max(col.r, col.b)) * 6.0, 0.0, 1.0) * edge * dg;
|
||
if (purple > 0.001) {
|
||
col.r = mix(col.r, col.g, purple);
|
||
col.b = mix(col.b, col.g, purple);
|
||
}
|
||
if (green > 0.001) col.g = mix(col.g, (col.r + col.b) * 0.5, green);
|
||
}
|
||
|
||
// Dehaze
|
||
float d = u_dehaze / 100.0;
|
||
if (d > 0.0) {
|
||
float veil = luma(bb);
|
||
col = (col - d * 0.32 * veil * vec3(0.95, 0.98, 1.02)) / max(0.05, 1.0 - d * 0.28);
|
||
} else if (d < 0.0) {
|
||
col = mix(col, bb * 0.85 + vec3(0.09), -d * 0.55);
|
||
}
|
||
|
||
// Vignette
|
||
float amt = u_vigAmt / 100.0;
|
||
if (abs(amt) > 0.001) {
|
||
vec2 q = (v_uv - 0.5) * vec2(u_aspect, 1.0);
|
||
float r = length(q) / max(0.05, length(vec2(u_aspect, 1.0) * 0.5));
|
||
float mid = mix(0.18, 1.05, u_vigMid / 100.0);
|
||
float feather = mix(0.05, 1.0, u_vigFeather / 100.0);
|
||
float v = smoothstep(mid, mid + feather * 0.6, r);
|
||
float strength = abs(amt) * v;
|
||
if (amt < 0.0) col *= 1.0 - strength * 0.92;
|
||
else col = mix(col, vec3(1.0), strength * 0.6);
|
||
}
|
||
|
||
// Soft proofing: paper white, black point and a reduced print gamut. This is
|
||
// a display simulation, not an ICC transform, but it makes the print intent
|
||
// visible while editing and is applied after all creative effects.
|
||
if (u_proofEnable > 0.5) {
|
||
float paperBlack = clamp(u_proofBlack / 100.0, 0.0, 0.2);
|
||
col = mix(col, u_proofPaper, 0.035);
|
||
col = paperBlack + col * (1.0 - paperBlack);
|
||
float y = luma(col);
|
||
col = mix(vec3(y), col, 0.88);
|
||
if (u_gamut > 0.5) {
|
||
float mx = max(col.r, max(col.g, col.b));
|
||
float mn = min(col.r, min(col.g, col.b));
|
||
float sat = mx > 0.001 ? (mx - mn) / mx : 0.0;
|
||
if (sat > 0.62 && (mx > 0.92 || mn < 0.06)) {
|
||
col = mix(col, vec3(1.0, 0.0, 0.75), 0.32);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Grain: film-like noise laid down in image space. Measured in output pixels
|
||
// a 6000 px export came out four times finer than the 1500 px preview, so the
|
||
// pattern is generated from the frame instead and every octave is band limited:
|
||
// nothing here depends on how many pixels the target happens to have.
|
||
float ga = u_grainAmt / 100.0;
|
||
if (ga > 0.001) {
|
||
float cell = mix(1.0, 3.0, clamp((u_grainSize - 10.0) / 90.0, 0.0, 1.0));
|
||
vec2 frameUv = mix(u_crop.xy, u_crop.xy + u_crop.zw, vec2(v_uv.x, 1.0 - v_uv.y));
|
||
// Grain lives on the photo, not on the output frame: the coordinates go
|
||
// through the same rotation/quarter/flip the frame uses, so straightening
|
||
// and rotating carry the texture along with the pixels instead of shifting
|
||
// it underneath them.
|
||
vec2 p = (frameUv - 0.5) * u_frameSize;
|
||
float ca = cos(u_grainRot);
|
||
float sa = sin(u_grainRot);
|
||
vec2 rp = vec2(p.x * ca - p.y * sa, p.x * sa + p.y * ca) * u_grainFlip;
|
||
vec2 px = rp * u_grainUnits;
|
||
float pxPerUnit = length(u_outSize) / max(1.0, length(u_grainSpace * (u_crop.zw / u_grainFrame.zw)));
|
||
// Grain below a pixel cannot be drawn: it would either moire or read as a
|
||
// different, coarser pattern, so fade it out instead of rescaling it.
|
||
float vis = smoothstep(0.45, 1.0, cell * max(pxPerUnit, 1e-4));
|
||
// Roughness adds a finer octave on top of the clumps: cream at 0, bite at 100.
|
||
float w = clamp(u_grainRough / 100.0, 0.0, 1.0) * 0.85;
|
||
float fineCell = max(cell * 0.45, 1.25 / max(pxPerUnit, 1e-4));
|
||
float n = (valueNoise(px / cell) - 0.5)
|
||
+ (valueNoise(px / fineCell + 11.7) - 0.5) * w;
|
||
n *= vis * inversesqrt(1.0 + w * w);
|
||
float mask = 1.0 - abs(clamp(luma(col), 0.0, 1.0) * 2.0 - 1.0);
|
||
col += n * ga * 0.20 * (0.6 + mask * 0.4);
|
||
}
|
||
|
||
vec3 finalCol = clamp(col, 0.0, 1.0);
|
||
// Clipping overlay: which channels have run out of headroom. Red/green/blue
|
||
// mean one channel clipped, yellow means two, white means all three — the
|
||
// same reading Aperture's exposure warnings gave while you dragged.
|
||
if (u_clip > 1.5) {
|
||
// Shadow clipping: everything that has fallen to the bottom of the range.
|
||
if (max(finalCol.r, max(finalCol.g, finalCol.b)) < 0.02) {
|
||
finalCol = vec3(0.15, 0.4, 1.0);
|
||
}
|
||
} else if (u_clip > 0.5) {
|
||
vec3 k = step(0.985, finalCol);
|
||
float n = k.r + k.g + k.b;
|
||
if (n > 0.5) {
|
||
vec3 mark = vec3(1.0);
|
||
if (n < 2.5) {
|
||
if (n > 1.5) mark = vec3(1.0, 0.9, 0.1);
|
||
else if (k.r > 0.5) mark = vec3(1.0, 0.12, 0.12);
|
||
else if (k.g > 0.5) mark = vec3(0.1, 1.0, 0.2);
|
||
else mark = vec3(0.15, 0.4, 1.0);
|
||
}
|
||
finalCol = mark;
|
||
}
|
||
}
|
||
outColor = vec4(finalCol, 1.0);
|
||
}`;
|
||
|
||
export interface Histogram {
|
||
r: Uint32Array;
|
||
g: Uint32Array;
|
||
b: Uint32Array;
|
||
l: Uint32Array;
|
||
}
|
||
|
||
interface Target {
|
||
tex: WebGLTexture;
|
||
fbo: WebGLFramebuffer;
|
||
w: number;
|
||
h: number;
|
||
/** Half-float pixels keep subtle gradients from banding between passes. */
|
||
float: boolean;
|
||
}
|
||
|
||
function makeHistogram(): Histogram {
|
||
return {
|
||
r: new Uint32Array(256),
|
||
g: new Uint32Array(256),
|
||
b: new Uint32Array(256),
|
||
l: new Uint32Array(256),
|
||
};
|
||
}
|
||
|
||
/** CPU twin of the shader's lens/perspective warp (used to place masks). */
|
||
export function warpGeometryPoint(
|
||
p: { x: number; y: number },
|
||
geometry: GeometryEdits | undefined,
|
||
srcW: number,
|
||
srcH: number,
|
||
) {
|
||
if (!geometry) return p;
|
||
const g = geometry;
|
||
if (!g.distortion && !g.vertical && !g.horizontal && !g.rotate && g.scale === 100) return p;
|
||
const aspect = Math.max(1, srcW) / Math.max(1, srcH);
|
||
let x = (p.x - 0.5) / Math.max(0.5, g.scale / 100);
|
||
let y = (p.y - 0.5) / Math.max(0.5, g.scale / 100);
|
||
const a = (g.rotate * Math.PI) / 180;
|
||
const ca = Math.cos(a);
|
||
const sa = Math.sin(a);
|
||
[x, y] = [x * ca - y * sa, x * sa + y * ca];
|
||
x /= Math.max(0.15, 1 + (g.vertical / 100) * 0.35 * y * 2);
|
||
y /= Math.max(0.15, 1 + (g.horizontal / 100) * 0.35 * x * 2);
|
||
const ax = x * aspect;
|
||
const ay = y;
|
||
const r2 = ax * ax + ay * ay;
|
||
const factor = 1 + (g.distortion / 100) * 0.35 * r2;
|
||
x = (ax * factor) / aspect;
|
||
y = ay * factor;
|
||
return { x: x + 0.5, y: y + 0.5 };
|
||
}
|
||
|
||
/** Approximate inverse of warpGeometryPoint, for drawing mask handles on screen. */
|
||
export function unwarpGeometryPoint(
|
||
target: { x: number; y: number },
|
||
geometry: GeometryEdits | undefined,
|
||
srcW: number,
|
||
srcH: number,
|
||
) {
|
||
if (!geometry) return target;
|
||
if (
|
||
!geometry.distortion &&
|
||
!geometry.vertical &&
|
||
!geometry.horizontal &&
|
||
!geometry.rotate &&
|
||
geometry.scale === 100
|
||
) {
|
||
return target;
|
||
}
|
||
let p = { ...target };
|
||
for (let i = 0; i < 8; i++) {
|
||
const warped = warpGeometryPoint(p, geometry, srcW, srcH);
|
||
p = { x: p.x + (target.x - warped.x), y: p.y + (target.y - warped.y) };
|
||
}
|
||
return p;
|
||
}
|
||
|
||
export function rotatedBounds(imgW: number, imgH: number, angleDeg: number, quarter = 0) {
|
||
const swap = (((Math.round(quarter) % 4) + 4) % 4) % 2 === 1;
|
||
const w0 = swap ? imgH : imgW;
|
||
const h0 = swap ? imgW : imgH;
|
||
const a = (angleDeg * Math.PI) / 180;
|
||
const c = Math.abs(Math.cos(a));
|
||
const s = Math.abs(Math.sin(a));
|
||
return {
|
||
w: Math.max(1, w0 * c + h0 * s),
|
||
h: Math.max(1, w0 * s + h0 * c),
|
||
};
|
||
}
|
||
|
||
export function outputSize(edits: Edits, imgW: number, imgH: number) {
|
||
const frame = rotatedBounds(imgW, imgH, edits.crop.angle, edits.crop.quarter);
|
||
return {
|
||
w: Math.max(1, Math.round(frame.w * edits.crop.w)),
|
||
h: Math.max(1, Math.round(frame.h * edits.crop.h)),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Frame-uv window for a loupe that tracks the crop: a `pxW` x `pxH` source-pixel
|
||
* window (pass the export's span for output-size patches), centred on the crop or
|
||
* on an explicit point, and clamped so it never samples outside the crop.
|
||
*/
|
||
export function grainSampleWindow(
|
||
frame: { w: number; h: number },
|
||
crop: { x: number; y: number; w: number; h: number },
|
||
pxW: number,
|
||
pxH: number,
|
||
point?: { x: number; y: number } | null,
|
||
) {
|
||
const w = Math.min(crop.w, pxW / Math.max(1, frame.w));
|
||
const h = Math.min(crop.h, pxH / Math.max(1, frame.h));
|
||
const cx = point ? Math.min(Math.max(point.x, crop.x), crop.x + crop.w) : crop.x + crop.w / 2;
|
||
const cy = point ? Math.min(Math.max(point.y, crop.y), crop.y + crop.h) : crop.y + crop.h / 2;
|
||
return {
|
||
x: Math.min(Math.max(cx - w / 2, crop.x), crop.x + crop.w - w),
|
||
y: Math.min(Math.max(cy - h / 2, crop.y), crop.y + crop.h - h),
|
||
w,
|
||
h,
|
||
};
|
||
}
|
||
|
||
function frameAngle(angle: number, quarter: number) {
|
||
return -((angle * Math.PI) / 180 + (quarter * Math.PI) / 2);
|
||
}
|
||
|
||
/**
|
||
* Photo coordinates (0-1 over the untouched file) to frame coordinates, through
|
||
* the same rotate / quarter turn / flip the renderer applies. Lets a click on an
|
||
* unrotated thumbnail pick the point that lands there in the straightened crop.
|
||
*/
|
||
export function sourceToFrame(
|
||
p: { x: number; y: number },
|
||
srcW: number,
|
||
srcH: number,
|
||
angle: number,
|
||
quarter: number,
|
||
flipH = false,
|
||
flipV = false,
|
||
) {
|
||
const b = rotatedBounds(srcW, srcH, angle, quarter);
|
||
// Frame uv grows the same way as the photo's pixels (y down, as the canvas
|
||
// draws them), so only a flip mirror the offset.
|
||
const sx = (p.x - 0.5) * srcW * (flipH ? -1 : 1);
|
||
const sy = (p.y - 0.5) * srcH * (flipV ? -1 : 1);
|
||
const a = frameAngle(angle, quarter);
|
||
const ca = Math.cos(-a);
|
||
const sa = Math.sin(-a);
|
||
return {
|
||
x: (sx * ca - sy * sa) / b.w + 0.5,
|
||
y: (sx * sa + sy * ca) / b.h + 0.5,
|
||
};
|
||
}
|
||
|
||
/** The inverse of `sourceToFrame`, for drawing a marker back onto the thumbnail. */
|
||
export function frameToSource(
|
||
p: { x: number; y: number },
|
||
srcW: number,
|
||
srcH: number,
|
||
angle: number,
|
||
quarter: number,
|
||
flipH = false,
|
||
flipV = false,
|
||
) {
|
||
const b = rotatedBounds(srcW, srcH, angle, quarter);
|
||
const dx = (p.x - 0.5) * b.w;
|
||
const dy = (p.y - 0.5) * b.h;
|
||
const a = frameAngle(angle, quarter);
|
||
const ca = Math.cos(a);
|
||
const sa = Math.sin(a);
|
||
const sx = (dx * ca - dy * sa) * (flipH ? -1 : 1);
|
||
const sy = (dx * sa + dy * ca) * (flipV ? -1 : 1);
|
||
return { x: sx / srcW + 0.5, y: sy / srcH + 0.5 };
|
||
}
|
||
|
||
/**
|
||
* Size of one grain cell in exported pixels, using the renderer's own scale:
|
||
* 1200 cells across the crop's long edge, cell size 1-3 units from the slider.
|
||
*/
|
||
export function grainCellPx(
|
||
edits: {
|
||
crop: { x: number; y: number; w: number; h: number; angle: number; quarter: number };
|
||
grain: { size: number };
|
||
},
|
||
srcW: number,
|
||
srcH: number,
|
||
outW: number,
|
||
) {
|
||
const { crop } = edits;
|
||
const base = rotatedBounds(srcW, srcH, 0, crop.quarter);
|
||
const unitsPerPx = 1200 / Math.max(1, base.w * crop.w, base.h * crop.h);
|
||
const frame = rotatedBounds(srcW, srcH, crop.angle, crop.quarter);
|
||
const pxPerSource = outW / Math.max(1, frame.w * crop.w);
|
||
const cell = 1 + 2 * Math.min(1, Math.max(0, (edits.grain.size - 10) / 90));
|
||
return (cell / unitsPerPx) * pxPerSource;
|
||
}
|
||
|
||
/** Builds a 256px LUT with the composite curve baked together with each channel curve. */
|
||
/**
|
||
* Region tone shaper, the parametric half of the tone curve: four overlapping
|
||
* bells over the shadows, darks, lights and highlights. Amounts are ±100.
|
||
*/
|
||
export function parametricTone(edits: Edits, x: number): number {
|
||
const p = edits.parametric;
|
||
const bell = (c: number, w: number) => Math.exp(-Math.pow((x - c) / w, 2));
|
||
const delta =
|
||
(p.blacks * bell(0.12, 0.16) +
|
||
p.darks * bell(0.38, 0.17) +
|
||
p.lights * bell(0.62, 0.17) +
|
||
p.highlights * bell(0.88, 0.16)) *
|
||
0.0011;
|
||
return clamp01(x + delta);
|
||
}
|
||
|
||
export function buildCurveLUT(edits: Edits): Uint8Array {
|
||
const rgb = buildSampler(edits.curve.rgb);
|
||
const red = buildSampler(edits.curve.red);
|
||
const green = buildSampler(edits.curve.green);
|
||
const blue = buildSampler(edits.curve.blue);
|
||
const data = new Uint8Array(256 * 4);
|
||
// Running maximum keeps the combined curve monotonic: four strong region
|
||
// pushes can otherwise fold the curve back on itself and posterise the frame.
|
||
let pr = 0;
|
||
let pg = 0;
|
||
let pb = 0;
|
||
for (let i = 0; i < 256; i++) {
|
||
const base = rgb(i / 255);
|
||
pr = Math.max(pr, parametricTone(edits, red(base)));
|
||
pg = Math.max(pg, parametricTone(edits, green(base)));
|
||
pb = Math.max(pb, parametricTone(edits, blue(base)));
|
||
data[i * 4 + 0] = Math.round(pr * 255);
|
||
data[i * 4 + 1] = Math.round(pg * 255);
|
||
data[i * 4 + 2] = Math.round(pb * 255);
|
||
data[i * 4 + 3] = 255;
|
||
}
|
||
return data;
|
||
}
|
||
|
||
class Prog {
|
||
private cache = new Map<string, WebGLUniformLocation | null>();
|
||
constructor(private gl: WebGL2RenderingContext, public program: WebGLProgram) {}
|
||
|
||
loc(name: string): WebGLUniformLocation | null {
|
||
if (!this.cache.has(name)) this.cache.set(name, this.gl.getUniformLocation(this.program, name));
|
||
return this.cache.get(name) ?? null;
|
||
}
|
||
f(name: string, v: number) {
|
||
const l = this.loc(name);
|
||
if (l) this.gl.uniform1f(l, v);
|
||
}
|
||
i(name: string, v: number) {
|
||
const l = this.loc(name);
|
||
if (l) this.gl.uniform1i(l, v);
|
||
}
|
||
v2(name: string, a: number, b: number) {
|
||
const l = this.loc(name);
|
||
if (l) this.gl.uniform2f(l, a, b);
|
||
}
|
||
/** Plain ivec2 uniform, used for correction-map dimensions. */
|
||
v2int(name: string, a: number, b: number) {
|
||
const l = this.loc(name);
|
||
if (l) this.gl.uniform2i(l, a, b);
|
||
}
|
||
/** Sets one element of a uniform array, e.g. `u_healSpot[3]`. */
|
||
v2i(name: string, index: number, a: number, b: number) {
|
||
const l = this.loc(`${name}[${index}]`);
|
||
if (l) this.gl.uniform2f(l, a, b);
|
||
}
|
||
v4i(name: string, index: number, a: number, b: number, c: number, d: number) {
|
||
const l = this.loc(`${name}[${index}]`);
|
||
if (l) this.gl.uniform4f(l, a, b, c, d);
|
||
}
|
||
v4(name: string, a: number, b: number, c: number, d: number) {
|
||
const l = this.loc(name);
|
||
if (l) this.gl.uniform4f(l, a, b, c, d);
|
||
}
|
||
v3(name: string, a: number, b: number, c: number) {
|
||
const l = this.loc(name);
|
||
if (l) this.gl.uniform3f(l, a, b, c);
|
||
}
|
||
fv(name: string, values: Float32Array) {
|
||
const l = this.loc(`${name}[0]`) ?? this.loc(name);
|
||
if (l) this.gl.uniform1fv(l, values);
|
||
}
|
||
tex(name: string, texture: WebGLTexture, unit: number) {
|
||
const l = this.loc(name);
|
||
if (!l) return;
|
||
this.gl.activeTexture(this.gl.TEXTURE0 + unit);
|
||
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
|
||
this.gl.uniform1i(l, unit);
|
||
}
|
||
}
|
||
|
||
function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader {
|
||
const shader = gl.createShader(type);
|
||
if (!shader) throw new Error('Unable to create shader');
|
||
gl.shaderSource(shader, source);
|
||
gl.compileShader(shader);
|
||
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
||
const log = gl.getShaderInfoLog(shader);
|
||
gl.deleteShader(shader);
|
||
throw new Error(`Shader compile error: ${log}`);
|
||
}
|
||
return shader;
|
||
}
|
||
|
||
function link(gl: WebGL2RenderingContext, vsSource: string, fsSource: string): WebGLProgram {
|
||
const vs = compile(gl, gl.VERTEX_SHADER, vsSource);
|
||
const fs = compile(gl, gl.FRAGMENT_SHADER, fsSource);
|
||
const program = gl.createProgram();
|
||
if (!program) throw new Error('Unable to create program');
|
||
gl.attachShader(program, vs);
|
||
gl.attachShader(program, fs);
|
||
gl.linkProgram(program);
|
||
gl.deleteShader(vs);
|
||
gl.deleteShader(fs);
|
||
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
||
const log = gl.getProgramInfoLog(program);
|
||
gl.deleteProgram(program);
|
||
throw new Error(`Program link error: ${log}`);
|
||
}
|
||
return program;
|
||
}
|
||
|
||
export class Renderer {
|
||
readonly canvas: HTMLCanvasElement;
|
||
private gl: WebGL2RenderingContext;
|
||
private grade: Prog;
|
||
private blur: Prog;
|
||
private finish: Prog;
|
||
private quad: WebGLBuffer;
|
||
private vao: WebGLVertexArrayObject;
|
||
private srcTex: WebGLTexture;
|
||
private maskTex: WebGLTexture;
|
||
private lensGeomTex: WebGLTexture;
|
||
private lensTcaTex: WebGLTexture;
|
||
private lensVigTex: WebGLTexture;
|
||
private lensCorrection: LensCorrection | null = null;
|
||
private lensSig = '';
|
||
private lensSplit = -1;
|
||
private maskSig = '';
|
||
private srcBitmap: ImageBitmap | null = null;
|
||
private srcW = 1;
|
||
private srcH = 1;
|
||
private denTex: WebGLTexture;
|
||
private denMix = 0;
|
||
private denBitmap: ImageBitmap | null = null;
|
||
private curveTex: WebGLTexture;
|
||
private targets: { graded?: Target; smallA?: Target; smallB?: Target; bigA?: Target; bigB?: Target } = {};
|
||
private histTarget: Target | null = null;
|
||
private pickTarget: Target | null = null;
|
||
private exportTarget: Target | null = null;
|
||
private histW = 160;
|
||
private histH = 112;
|
||
private floatOk = false;
|
||
private floatTargets = false;
|
||
private grainRef: { x: number; y: number; w: number; h: number; sx: number; sy: number; units: number } | null = null;
|
||
|
||
histogram: Histogram = makeHistogram();
|
||
|
||
constructor(canvas: HTMLCanvasElement) {
|
||
this.canvas = canvas;
|
||
const gl = canvas.getContext('webgl2', {
|
||
alpha: false,
|
||
antialias: false,
|
||
depth: false,
|
||
stencil: false,
|
||
preserveDrawingBuffer: false,
|
||
powerPreference: 'high-performance',
|
||
});
|
||
if (!gl) throw new Error('This browser does not support WebGL2, which the editor needs.');
|
||
this.gl = gl;
|
||
// Half-float intermediates are colour-renderable through this extension on
|
||
// desktop and modern mobile GPUs. Fall back to 8-bit targets when it is
|
||
// missing so the editor still runs on older devices.
|
||
this.floatOk = Boolean(
|
||
gl.getExtension('EXT_color_buffer_float') && gl.getExtension('OES_texture_float_linear'),
|
||
);
|
||
this.floatTargets = this.floatOk;
|
||
|
||
this.grade = new Prog(gl, link(gl, VERT, GRADE_FRAG));
|
||
this.blur = new Prog(gl, link(gl, VERT, BLUR_FRAG));
|
||
this.finish = new Prog(gl, link(gl, VERT, FINISH_FRAG));
|
||
|
||
const quad = gl.createBuffer();
|
||
if (!quad) throw new Error('Unable to create buffer');
|
||
this.quad = quad;
|
||
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
|
||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
|
||
|
||
const vao = gl.createVertexArray();
|
||
if (!vao) throw new Error('Unable to create vertex array');
|
||
this.vao = vao;
|
||
gl.bindVertexArray(vao);
|
||
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
|
||
gl.enableVertexAttribArray(0);
|
||
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
|
||
gl.bindVertexArray(null);
|
||
|
||
const srcTex = gl.createTexture();
|
||
if (!srcTex) throw new Error('Unable to create texture');
|
||
this.srcTex = srcTex;
|
||
gl.bindTexture(gl.TEXTURE_2D, srcTex);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||
|
||
const denTex = gl.createTexture();
|
||
if (!denTex) throw new Error('Unable to create texture');
|
||
this.denTex = denTex;
|
||
gl.bindTexture(gl.TEXTURE_2D, denTex);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||
|
||
const maskTex = gl.createTexture();
|
||
if (!maskTex) throw new Error('Unable to create texture');
|
||
this.maskTex = maskTex;
|
||
gl.bindTexture(gl.TEXTURE_2D, maskTex);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||
|
||
const curveTex = gl.createTexture();
|
||
if (!curveTex) throw new Error('Unable to create texture');
|
||
this.curveTex = curveTex;
|
||
gl.bindTexture(gl.TEXTURE_2D, curveTex);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||
|
||
this.lensGeomTex = this.makeFloatTexture();
|
||
this.lensTcaTex = this.makeFloatTexture();
|
||
this.lensVigTex = this.makeFloatTexture();
|
||
|
||
gl.disable(gl.BLEND);
|
||
gl.disable(gl.DEPTH_TEST);
|
||
}
|
||
|
||
private makeFloatTexture() {
|
||
const gl = this.gl;
|
||
const tex = gl.createTexture();
|
||
if (!tex) throw new Error('Unable to create texture');
|
||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 1, 1, 0, gl.RGBA, gl.FLOAT, new Float32Array(4));
|
||
return tex;
|
||
}
|
||
|
||
static isSupported(): boolean {
|
||
try {
|
||
const c = document.createElement('canvas');
|
||
return !!c.getContext('webgl2');
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
setLensCorrection(correction: LensCorrection | null) {
|
||
this.lensCorrection = correction;
|
||
}
|
||
|
||
/**
|
||
* Blend a denoised proxy over the source. Passing null (or amount 0) turns the
|
||
* blend off without touching the source texture.
|
||
*
|
||
* Uploaded exactly like `u_src` -- flipped and mipmapped -- because it is
|
||
* sampled with the same uv; disagreeing on either would offset the two images
|
||
* by half a frame.
|
||
*/
|
||
setDenoised(bitmap: ImageBitmap | null, amount = 1) {
|
||
this.denMix = bitmap ? Math.max(0, Math.min(1, amount)) : 0;
|
||
if (!bitmap) {
|
||
this.denBitmap = null;
|
||
return;
|
||
}
|
||
// Called on every redraw so the Amount slider is live; only the bitmap
|
||
// changing should cost a texture upload.
|
||
if (this.denBitmap === bitmap) return;
|
||
this.denBitmap = bitmap;
|
||
const gl = this.gl;
|
||
gl.bindTexture(gl.TEXTURE_2D, this.denTex);
|
||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||
gl.generateMipmap(gl.TEXTURE_2D);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||
}
|
||
|
||
setImage(bitmap: ImageBitmap) {
|
||
if (this.srcBitmap === bitmap) return;
|
||
// A denoised bitmap belongs to the previous photo; the caller re-supplies it
|
||
// after this call when the new photo has one.
|
||
this.denMix = 0;
|
||
this.denBitmap = null;
|
||
this.grainRef = null;
|
||
this.maskSig = '';
|
||
const gl = this.gl;
|
||
this.srcBitmap = bitmap;
|
||
this.srcW = bitmap.width;
|
||
this.srcH = bitmap.height;
|
||
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
|
||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bitmap);
|
||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||
// Mipmaps: a 6000 px proxy shown fitted is a 4-8x minification, which shimmers
|
||
// badly with plain bilinear sampling.
|
||
gl.generateMipmap(gl.TEXTURE_2D);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||
}
|
||
|
||
private makeTarget(w: number, h: number, float = this.floatTargets): Target {
|
||
const gl = this.gl;
|
||
const tex = gl.createTexture();
|
||
const fbo = gl.createFramebuffer();
|
||
if (!tex || !fbo) throw new Error('Unable to allocate render target');
|
||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||
if (float) {
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);
|
||
} else {
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||
}
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
|
||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
|
||
if (float && gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||
gl.deleteTexture(tex);
|
||
gl.deleteFramebuffer(fbo);
|
||
throw new Error('Half-float render targets are unavailable');
|
||
}
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||
return { tex, fbo, w, h, float };
|
||
}
|
||
|
||
private freeTarget(target?: Target) {
|
||
if (!target) return;
|
||
this.gl.deleteTexture(target.tex);
|
||
this.gl.deleteFramebuffer(target.fbo);
|
||
}
|
||
|
||
private ensureTargets(w: number, h: number) {
|
||
const t = this.targets;
|
||
if (t.graded && t.graded.w === w && t.graded.h === h) return;
|
||
this.freeTarget(t.graded);
|
||
this.freeTarget(t.smallA);
|
||
this.freeTarget(t.smallB);
|
||
this.freeTarget(t.bigA);
|
||
this.freeTarget(t.bigB);
|
||
const sw = Math.max(1, Math.ceil(w / 2));
|
||
const sh = Math.max(1, Math.ceil(h / 2));
|
||
const bw = Math.max(1, Math.ceil(w / 4));
|
||
const bh = Math.max(1, Math.ceil(h / 4));
|
||
|
||
// Allocate as a group: if one half-float target is rejected, dispose the
|
||
// partial set and retry the whole frame in 8-bit rather than mixing formats.
|
||
const modes = this.floatOk ? [true, false] : [false];
|
||
for (const useFloat of modes) {
|
||
const made: Target[] = [];
|
||
try {
|
||
const mk = (mw: number, mh: number) => {
|
||
const target = this.makeTarget(mw, mh, useFloat);
|
||
made.push(target);
|
||
return target;
|
||
};
|
||
this.targets = {
|
||
graded: mk(w, h),
|
||
smallA: mk(sw, sh),
|
||
smallB: mk(sw, sh),
|
||
bigA: mk(bw, bh),
|
||
bigB: mk(bw, bh),
|
||
};
|
||
this.floatTargets = useFloat;
|
||
return;
|
||
} catch {
|
||
for (const target of made) this.freeTarget(target);
|
||
}
|
||
}
|
||
this.targets = {};
|
||
throw new Error('Unable to allocate render targets');
|
||
}
|
||
|
||
private drawQuad() {
|
||
const gl = this.gl;
|
||
gl.bindVertexArray(this.vao);
|
||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||
gl.bindVertexArray(null);
|
||
}
|
||
|
||
private uploadCurve(edits: Edits) {
|
||
const gl = this.gl;
|
||
const data = buildCurveLUT(edits);
|
||
gl.bindTexture(gl.TEXTURE_2D, this.curveTex);
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||
}
|
||
|
||
/** Bake local masks only when their geometry changed, not for every slider. */
|
||
private uploadMasks(edits: Edits) {
|
||
const gl = this.gl;
|
||
const layers = (edits.local ?? []).slice(0, MAX_LOCAL_LAYERS);
|
||
const sig = maskSignature(layers, this.srcW, this.srcH);
|
||
if (sig !== this.maskSig) {
|
||
const packed = buildLocalMasks(layers, this.srcW, this.srcH);
|
||
gl.bindTexture(gl.TEXTURE_2D, this.maskTex);
|
||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, packed.w, packed.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, packed.data);
|
||
this.maskSig = sig;
|
||
}
|
||
return layers.length;
|
||
}
|
||
|
||
private uploadLensMaps() {
|
||
const gl = this.gl;
|
||
const correction = this.lensCorrection;
|
||
if (!correction || correction.key === this.lensSig) return;
|
||
const upload = (tex: WebGLTexture, map: { data: Float32Array; width: number; height: number }) => {
|
||
gl.bindTexture(gl.TEXTURE_2D, tex);
|
||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
|
||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, map.width, map.height, 0, gl.RGBA, gl.FLOAT, map.data);
|
||
};
|
||
upload(this.lensGeomTex, correction.geometry);
|
||
if (correction.tca) upload(this.lensTcaTex, correction.tca);
|
||
if (correction.vignette) upload(this.lensVigTex, correction.vignette);
|
||
this.lensSig = correction.key;
|
||
}
|
||
|
||
/** Grade-pass state, shared by the preview render and the eyedropper pick. */
|
||
private bindGrade(
|
||
edits: Edits,
|
||
crop: { x: number; y: number; w: number; h: number },
|
||
valid: { x: number; y: number; w: number; h: number },
|
||
bounds: { w: number; h: number },
|
||
upscale: boolean,
|
||
srcLod = 0,
|
||
) {
|
||
const g = this.grade;
|
||
this.gl.useProgram(g.program);
|
||
// Bake/upload masks before binding the source and curve textures. The upload
|
||
// leaves its texture bound to the active unit, which would otherwise replace
|
||
// the curve LUT and corrupt the first frame after a mask change.
|
||
const localCount = this.uploadMasks(edits);
|
||
this.uploadLensMaps();
|
||
g.tex('u_src', this.srcTex, 0);
|
||
g.tex('u_curve', this.curveTex, 1);
|
||
// Unit 6, not 3: the lens maps below take 3-5 and would overwrite the
|
||
// denoised texture, leaving u_den sampling a 1x1 zero texture -- black.
|
||
g.tex('u_den', this.denTex, 6);
|
||
g.f('u_denMix', this.denMix);
|
||
g.v2('u_srcSize', this.srcW, this.srcH);
|
||
g.v2('u_frameSize', bounds.w, bounds.h);
|
||
g.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
|
||
g.v4('u_valid', valid.x, valid.y, valid.w, valid.h);
|
||
g.f('u_angle', (edits.crop.angle * Math.PI) / 180);
|
||
g.i('u_quarter', edits.crop.quarter);
|
||
g.v2('u_flip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1);
|
||
g.f('u_upscale', upscale ? 1 : 0);
|
||
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
|
||
g.f('u_pick', -1);
|
||
g.v2('u_pickUv', 0, 0);
|
||
g.f('u_temp', edits.temp);
|
||
g.f('u_tint', edits.tint);
|
||
g.f('u_exposure', edits.exposure);
|
||
g.f('u_recovery', edits.recovery);
|
||
g.f('u_contrast', edits.contrast);
|
||
g.f('u_highlights', edits.highlights);
|
||
g.f('u_shadows', edits.shadows);
|
||
g.f('u_whites', edits.whites);
|
||
g.f('u_blacks', edits.blacks);
|
||
g.f('u_vibrance', edits.vibrance);
|
||
g.f('u_saturation', edits.saturation);
|
||
g.f('u_bw', edits.bw ? 1 : 0);
|
||
const bwFilter = bwFilterRgb(edits.bwFilter);
|
||
g.v3('u_bwFilter', bwFilter[0], bwFilter[1], bwFilter[2]);
|
||
g.f('u_bwFilterAmt', clamp01(edits.bwFilterAmount / 100));
|
||
g.fv('u_hue', new Float32Array(edits.hsl.hue));
|
||
g.fv('u_sat', new Float32Array(edits.hsl.sat));
|
||
g.fv('u_lum', new Float32Array(edits.hsl.lum));
|
||
g.f('u_gSh', edits.grading.shadows.h / 360);
|
||
g.f('u_gSs', edits.grading.shadows.s);
|
||
g.f('u_gHi', edits.grading.highlights.h / 360);
|
||
g.f('u_gHs', edits.grading.highlights.s);
|
||
g.f('u_gBal', edits.grading.balance);
|
||
|
||
const geom = edits.geometry;
|
||
g.v4(
|
||
'u_geom',
|
||
(geom?.distortion ?? 0) * 0.0035,
|
||
(geom?.vertical ?? 0) * 0.0035,
|
||
(geom?.horizontal ?? 0) * 0.0035,
|
||
((geom?.rotate ?? 0) * Math.PI) / 180,
|
||
);
|
||
g.f('u_geomScale', Math.max(0.5, (geom?.scale ?? 100) / 100));
|
||
|
||
const lens = this.lensCorrection;
|
||
let lensFlags = 0;
|
||
if (lens) {
|
||
lensFlags = 1 | (lens.tca ? 2 : 0) | (lens.vignette ? 4 : 0);
|
||
}
|
||
g.tex('u_lensGeom', this.lensGeomTex, 3);
|
||
g.tex('u_lensTca', this.lensTcaTex, 4);
|
||
g.tex('u_lensVig', this.lensVigTex, 5);
|
||
g.v2int('u_lensGeomSize', lens?.geometry.width ?? 1, lens?.geometry.height ?? 1);
|
||
g.v2int('u_lensTcaSize', lens?.tca?.width ?? 1, lens?.tca?.height ?? 1);
|
||
g.v2int('u_lensVigSize', lens?.vignette?.width ?? 1, lens?.vignette?.height ?? 1);
|
||
g.i('u_lensFlags', lensFlags);
|
||
g.f('u_lensScale', lens?.scale ?? 1);
|
||
g.f('u_lensSplit', this.lensSplit);
|
||
|
||
g.tex('u_masks', this.maskTex, 2);
|
||
g.i('u_localCount', localCount);
|
||
for (let i = 0; i < localCount; i++) {
|
||
const layer = edits.local[i];
|
||
g.v4i('u_localAdj', i, layer.adjust.exposure, layer.adjust.contrast, layer.adjust.temp, layer.adjust.tint);
|
||
g.v4i('u_localAdj2', i, layer.adjust.saturation, layer.adjust.highlights, layer.adjust.shadows, 0);
|
||
g.v4i('u_localRange', i, layer.range.lumaMin / 100, layer.range.lumaMax / 100, layer.range.hue, layer.range.hueRange);
|
||
g.v4i('u_localRange2', i, layer.range.satMin / 100, layer.range.enabled ? 1 : 0, 0, 0);
|
||
}
|
||
|
||
const spots = (edits.heal ?? []).slice(0, MAX_HEAL_SPOTS);
|
||
g.i('u_healCount', spots.length);
|
||
for (let i = 0; i < spots.length; i++) {
|
||
const spot = spots[i];
|
||
g.v4i('u_healSpot', i, spot.x, spot.y, spot.sx, spot.sy);
|
||
g.v2i('u_healSize', i, spot.r, clamp01(spot.feather / 100));
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Source colour under a point of the preview, using the same crop, straighten
|
||
* and zoom mapping the screen uses. The white balance eyedropper reads through
|
||
* this so the sample is the pixel the pointer is actually over.
|
||
*/
|
||
pickSource(
|
||
edits: Edits,
|
||
opts: { nx: number; ny: number; view?: { x: number; y: number; w: number; h: number }; upscale?: boolean },
|
||
): [number, number, number] | null {
|
||
const gl = this.gl;
|
||
if (!this.srcBitmap) return null;
|
||
if (!this.pickTarget) this.pickTarget = this.makeTarget(1, 1, false);
|
||
const target = this.pickTarget;
|
||
const bounds = rotatedBounds(this.srcW, this.srcH, edits.crop.angle, edits.crop.quarter);
|
||
const valid = { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h };
|
||
const crop = opts.view ?? valid;
|
||
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo);
|
||
gl.viewport(0, 0, 1, 1);
|
||
// The eyedropper always reads the corrected side, even while the preview
|
||
// shows the Optics split.
|
||
const split = this.lensSplit;
|
||
this.lensSplit = -1;
|
||
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale);
|
||
this.lensSplit = split;
|
||
this.grade.f('u_pick', 1);
|
||
this.grade.v2('u_pickUv', clamp01(opts.nx), 1 - clamp01(opts.ny));
|
||
// A one-pixel draw computes a huge LOD and would sample the smallest mip
|
||
// level (the average of the whole photo), so read the full-resolution texel.
|
||
// The filter belongs to the source texture: binding it explicitly matters,
|
||
// because the active unit is whatever the last uniform update left behind.
|
||
gl.activeTexture(gl.TEXTURE0);
|
||
gl.bindTexture(gl.TEXTURE_2D, this.srcTex);
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||
this.drawQuad();
|
||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
|
||
|
||
const px = new Uint8Array(4);
|
||
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||
return [px[0] / 255, px[1] / 255, px[2] / 255];
|
||
}
|
||
|
||
render(
|
||
edits: Edits,
|
||
opts: {
|
||
width: number;
|
||
height: number;
|
||
cropPreview?: boolean;
|
||
histogram?: boolean;
|
||
/** visible sub-rect of the frame, normalized; defaults to the whole crop */
|
||
view?: { x: number; y: number; w: number; h: number };
|
||
/** sample bicubically, for when the view magnifies the source beyond 1:1 */
|
||
upscale?: boolean;
|
||
/** Lensfun calibration maps for this photo, if a profile is applied */
|
||
lens?: LensCorrection | null;
|
||
/** 0–1 screen split: left is uncorrected, right is corrected. */
|
||
lensSplit?: number;
|
||
/** hold the grain pattern still, e.g. while a crop handle is being dragged */
|
||
freezeGrain?: boolean;
|
||
/** paint clipped channels while the exposure control is being dragged */
|
||
clipPreview?: boolean;
|
||
/** paint blown highlights or crushed shadows outside the range */
|
||
clipping?: 'highlights' | 'shadows';
|
||
/** return the finished image as linear-space floats instead of drawing the canvas */
|
||
floatOut?: boolean;
|
||
},
|
||
): Float32Array | null {
|
||
const gl = this.gl;
|
||
if (!this.srcBitmap) return null;
|
||
if (opts.lens !== undefined) this.setLensCorrection(opts.lens);
|
||
this.lensSplit = opts.lensSplit ?? -1;
|
||
const w = Math.max(1, Math.round(opts.width));
|
||
const h = Math.max(1, Math.round(opts.height));
|
||
if (this.canvas.width !== w) this.canvas.width = w;
|
||
if (this.canvas.height !== h) this.canvas.height = h;
|
||
|
||
this.ensureTargets(w, h);
|
||
const t = this.targets;
|
||
if (!t.graded || !t.smallA || !t.smallB || !t.bigA || !t.bigB) return null;
|
||
|
||
this.uploadCurve(edits);
|
||
|
||
const bounds = rotatedBounds(this.srcW, this.srcH, edits.crop.angle, edits.crop.quarter);
|
||
const valid = opts.cropPreview
|
||
? { x: 0, y: 0, w: 1, h: 1 }
|
||
: { x: edits.crop.x, y: edits.crop.y, w: edits.crop.w, h: edits.crop.h };
|
||
const crop = opts.view ?? valid;
|
||
// Detail radii are authored relative to a 2000 px image. Scaling them by
|
||
// the source crop, rather than the output buffer, keeps the preview and a
|
||
// 6000 px export looking like the same edit.
|
||
const detailScale = Math.max(
|
||
0.25,
|
||
Math.min(4, Math.max(bounds.w * crop.w, bounds.h * crop.h) / 2000),
|
||
);
|
||
|
||
// Pass 1: white balance, tone, curve, color
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, t.graded.fbo);
|
||
gl.viewport(0, 0, w, h);
|
||
// A derivative-based texture() lookup can pick the smallest mip at the very
|
||
// top or bottom edge of a 1:1 frame. Derive the LOD from the actual source
|
||
// window instead, so full-resolution output reads full-resolution texels.
|
||
const cropPxW = Math.max(1, bounds.w * crop.w);
|
||
const cropPxH = Math.max(1, bounds.h * crop.h);
|
||
const srcLod = Math.max(0, Math.log2(Math.max(cropPxW / w, cropPxH / h)));
|
||
this.bindGrade(edits, crop, valid, bounds, !!opts.upscale, srcLod);
|
||
this.drawQuad();
|
||
|
||
// Passes 2-3: small blur (detail) and large blur (clarity) from the graded image
|
||
const blurPass = (from: Target, to: Target, dx: number, dy: number, srcTex: WebGLTexture) => {
|
||
const gl2 = this.gl;
|
||
gl2.bindFramebuffer(gl2.FRAMEBUFFER, to.fbo);
|
||
gl2.viewport(0, 0, to.w, to.h);
|
||
gl2.useProgram(this.blur.program);
|
||
this.blur.tex('u_tex', srcTex, 0);
|
||
this.blur.v2('u_dir', dx, dy);
|
||
this.drawQuad();
|
||
};
|
||
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, t.smallA.fbo);
|
||
gl.viewport(0, 0, t.smallA.w, t.smallA.h);
|
||
gl.useProgram(this.blur.program);
|
||
this.blur.tex('u_tex', t.graded.tex, 0);
|
||
this.blur.v2('u_dir', (edits.sharpen.radius / t.smallA.w) * 0.75 * detailScale, 0);
|
||
this.drawQuad();
|
||
blurPass(
|
||
t.smallA,
|
||
t.smallB,
|
||
0,
|
||
(edits.sharpen.radius / t.smallB.h) * 0.75 * detailScale,
|
||
t.smallA.tex,
|
||
);
|
||
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, t.bigA.fbo);
|
||
gl.viewport(0, 0, t.bigA.w, t.bigA.h);
|
||
gl.useProgram(this.blur.program);
|
||
this.blur.tex('u_tex', t.graded.tex, 0);
|
||
this.blur.v2('u_dir', (2.0 / t.bigA.w) * detailScale, 0);
|
||
this.drawQuad();
|
||
blurPass(t.bigA, t.bigB, 0, (2.0 / t.bigB.h) * detailScale, t.bigA.tex);
|
||
|
||
// Grain cells are counted across the crop's long edge: the same slider value
|
||
// covers the same share of the picture at every resolution and crop. While a
|
||
// handle is being dragged the reference is held, so the noise stands still.
|
||
const GRAIN_UNITS = 1200;
|
||
// Scaled from the un-straightened frame: straightening grows the rotating
|
||
// bounding box, which would otherwise resize the grain along with it.
|
||
const base = rotatedBounds(this.srcW, this.srcH, 0, edits.crop.quarter);
|
||
const cropW = Math.max(1, base.w * valid.w);
|
||
const cropH = Math.max(1, base.h * valid.h);
|
||
const grainUnits = GRAIN_UNITS / Math.max(cropW, cropH);
|
||
if (!opts.freezeGrain || !this.grainRef) {
|
||
this.grainRef = {
|
||
x: valid.x,
|
||
y: valid.y,
|
||
w: valid.w,
|
||
h: valid.h,
|
||
sx: cropW * grainUnits,
|
||
sy: cropH * grainUnits,
|
||
units: grainUnits,
|
||
};
|
||
}
|
||
const grain = this.grainRef;
|
||
const grainRot = -((edits.crop.angle * Math.PI) / 180 + (edits.crop.quarter * Math.PI) / 2);
|
||
|
||
// Pass 4: detail, effects, grain -> canvas
|
||
const finishDraw = (target: Target | null, clip = 0) => {
|
||
const gl2 = this.gl;
|
||
if (target) {
|
||
gl2.bindFramebuffer(gl2.FRAMEBUFFER, target.fbo);
|
||
gl2.viewport(0, 0, target.w, target.h);
|
||
} else {
|
||
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
|
||
gl2.viewport(0, 0, w, h);
|
||
}
|
||
gl2.useProgram(this.finish.program);
|
||
this.finish.tex('u_graded', t.graded!.tex, 0);
|
||
this.finish.tex('u_blurSmall', t.smallB!.tex, 1);
|
||
this.finish.tex('u_blurBig', t.bigB!.tex, 2);
|
||
this.finish.f('u_texture', edits.texture);
|
||
this.finish.f('u_clarity', edits.clarity);
|
||
this.finish.f('u_dehaze', edits.dehaze);
|
||
this.finish.f('u_sharpen', edits.sharpen.amount);
|
||
this.finish.f('u_sharpenMask', edits.sharpen.mask);
|
||
this.finish.f('u_detailScale', detailScale);
|
||
this.finish.f('u_lensSoft', edits.sharpen.lensSoftness);
|
||
this.finish.f('u_proofEnable', edits.proof.enabled ? 1 : 0);
|
||
const paper = edits.proof.paper === 'gloss'
|
||
? [0.99, 0.995, 0.985]
|
||
: edits.proof.paper === 'newsprint'
|
||
? [0.9, 0.89, 0.83]
|
||
: [0.96, 0.95, 0.91];
|
||
this.finish.v3('u_proofPaper', paper[0], paper[1], paper[2]);
|
||
this.finish.f('u_proofBlack', edits.proof.blackPoint);
|
||
this.finish.f('u_gamut', edits.proof.gamut ? 1 : 0);
|
||
this.finish.f('u_nr', edits.noise.luminance);
|
||
this.finish.f('u_chroma', edits.noise.chroma);
|
||
this.finish.f('u_chromaDetail', edits.noise.chromaDetail);
|
||
this.finish.f('u_fringePurple', edits.defringe.purple);
|
||
this.finish.f('u_fringeGreen', edits.defringe.green);
|
||
this.finish.f('u_vigAmt', edits.vignette.amount);
|
||
this.finish.f('u_vigMid', edits.vignette.midpoint);
|
||
this.finish.f('u_vigFeather', edits.vignette.feather);
|
||
this.finish.f('u_grainAmt', edits.grain.amount);
|
||
this.finish.f('u_grainSize', edits.grain.size);
|
||
this.finish.f('u_grainRough', edits.grain.roughness);
|
||
this.finish.f('u_clip', clip);
|
||
this.finish.v4('u_crop', crop.x, crop.y, crop.w, crop.h);
|
||
this.finish.v4('u_grainFrame', grain.x, grain.y, grain.w, grain.h);
|
||
this.finish.v2('u_grainSpace', grain.sx, grain.sy);
|
||
this.finish.f('u_grainUnits', grain.units);
|
||
this.finish.v2('u_frameSize', bounds.w, bounds.h);
|
||
this.finish.f('u_grainRot', grainRot);
|
||
this.finish.v2('u_grainFlip', edits.crop.flipH ? -1 : 1, edits.crop.flipV ? -1 : 1);
|
||
this.finish.v2('u_outSize', target ? target.w : w, target ? target.h : h);
|
||
this.finish.f('u_aspect', w / h);
|
||
this.drawQuad();
|
||
};
|
||
|
||
const clipMode = opts.clipPreview
|
||
? 1
|
||
: opts.clipping === 'shadows'
|
||
? 2
|
||
: opts.clipping === 'highlights'
|
||
? 1
|
||
: 0;
|
||
|
||
if (opts.floatOut) {
|
||
if (!this.floatOk) throw new Error('16-bit export needs half-float render targets');
|
||
if (
|
||
!this.exportTarget ||
|
||
this.exportTarget.w !== w ||
|
||
this.exportTarget.h !== h
|
||
) {
|
||
this.freeTarget(this.exportTarget ?? undefined);
|
||
this.exportTarget = this.makeTarget(w, h, true);
|
||
}
|
||
finishDraw(this.exportTarget, clipMode);
|
||
const data = new Float32Array(w * h * 4);
|
||
gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, data);
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||
return data;
|
||
}
|
||
|
||
finishDraw(null, clipMode);
|
||
|
||
if (opts.histogram) {
|
||
if (!this.histTarget) this.histTarget = this.makeTarget(this.histW, this.histH, false);
|
||
finishDraw(this.histTarget);
|
||
const pixels = new Uint8Array(this.histW * this.histH * 4);
|
||
gl.readPixels(0, 0, this.histW, this.histH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
|
||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||
const hist = this.histogram;
|
||
hist.r.fill(0);
|
||
hist.g.fill(0);
|
||
hist.b.fill(0);
|
||
hist.l.fill(0);
|
||
for (let i = 0; i < pixels.length; i += 4) {
|
||
const r = pixels[i];
|
||
const gg = pixels[i + 1];
|
||
const b = pixels[i + 2];
|
||
hist.r[r]++;
|
||
hist.g[gg]++;
|
||
hist.b[b]++;
|
||
hist.l[Math.round(0.2126 * r + 0.7152 * gg + 0.0722 * b)]++;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/** Wait for queued GPU work, e.g. before the canvas is encoded to a file. */
|
||
finishGpu() {
|
||
this.gl.finish();
|
||
}
|
||
|
||
dispose() {
|
||
const gl = this.gl;
|
||
this.freeTarget(this.targets.graded);
|
||
this.freeTarget(this.targets.smallA);
|
||
this.freeTarget(this.targets.smallB);
|
||
this.freeTarget(this.targets.bigA);
|
||
this.freeTarget(this.targets.bigB);
|
||
this.freeTarget(this.histTarget ?? undefined);
|
||
this.freeTarget(this.pickTarget ?? undefined);
|
||
this.freeTarget(this.exportTarget ?? undefined);
|
||
gl.deleteTexture(this.srcTex);
|
||
gl.deleteTexture(this.maskTex);
|
||
gl.deleteTexture(this.curveTex);
|
||
gl.deleteTexture(this.lensGeomTex);
|
||
gl.deleteTexture(this.lensTcaTex);
|
||
gl.deleteTexture(this.lensVigTex);
|
||
gl.deleteBuffer(this.quad);
|
||
gl.deleteVertexArray(this.vao);
|
||
gl.deleteProgram(this.grade.program);
|
||
gl.deleteProgram(this.blur.program);
|
||
gl.deleteProgram(this.finish.program);
|
||
// Release the context slot so switching between library and develop does not
|
||
// exhaust the browser's WebGL context limit.
|
||
const ext = gl.getExtension('WEBGL_lose_context');
|
||
ext?.loseContext();
|
||
}
|
||
}
|
||
|