56d4b9df67
The LIGHT rail was sliders only, so the one control that describes a tone
mapping rather than a scalar had nowhere to live. It now has a TONE CURVE chip;
pressing it puts a curve graph on the photo itself — four channels, RGB plus R,
G and B, exactly the shape Lightroom's point curve has — and dragging a point
bends the picture under it while you drag.
A recipe carries the curve as `adjustments.toneCurve`, an optional map from
channel to point list, `Partial<Record<'rgb'|'r'|'g'|'b', [number, number][]>>`.
The field is optional and the API stores the recipe JSON opaquely, so every
recipe and session written before this commit loads unchanged and simply has no
curve; nothing on the API or in the database moved.
The renderer never sees the points. `shared/utils/toneCurve.ts` turns them into
a 256-entry table per channel and the shader looks the table up in a 256x1
texture: SkSL indexes uniform arrays by constant only, so a per-pixel lookup
has to come from a texture, and a table is the cheaper shape anyway — one
`lut.eval(vec2(v * 255 + 0.5, 0.5))` per channel. The interpolation between
points is a monotone cubic (Fritsch–Carlson) rather than a natural spline,
because a spline overshoots between two close points and that overshoot is the
classic tone-curve tell, a bright halo beside a lifted shadow; a monotone cubic
through the points bends through them and never turns back on itself. The table
is built per channel and then composited through the master, the order the graph
draws it in, so an R point in the shadows survives an RGB contrast S and both
land where the lines say.
Render passes: the curve rides the existing `renderPhoto`, as pass 3e, last —
after the stock, the matrix, the mixer and the seasonal grade, so a point placed
on the graph is the last word on that pixel. Preview and export both call
`renderPhoto`, so the two agree by construction rather than by two matching
implementations. The pass wraps whatever shader the pipeline had built
(`paintShader ?? imageShaderOf()`) as a child of the curve shader, and counts
towards `graded` for the same reason the tone shader does: the curve reads the
matrix's output, so when there is a matrix it has to be in the pixels the curve
samples. Turning the curve on costs one extra render pass and nothing else; off,
`curveIsActive` is false and the pass is not built at all.
That pass is also where this spent its time being invisible. The curve data
reached the recipe and the pixels did not move: `Skia.Image.MakeImage` does not
exist in the shim, so the call threw a TypeError inside the render, the preview
effect's catch swallowed it into `setError('err.generic')`, and the chip, the
graph and the recipe all looked healthy while the canvas kept the old frame. The
fix is in `skiaShim.ts`: CanvasKit keeps that factory top-level (`Skia.MakeImage`)
and only puts the encoded and lazy ones under `Image.`, and its ImageInfo insists
on an explicit `colorSpace` where RN Skia's does not — everything this pipeline
builds is sRGB, so the shim fills it in and the call site keeps RN Skia's shape.
Reproduced in Node first (`curve-skia-lab.cjs`, scratchpad): the shim's call
throws, the translated one returns a 256x1 image.
`ToneCurvePanel.tsx` is the graph: a 224px SVG over the photo's layout box, no
zoom transform, grid plus a dashed diagonal, the composite drawn as a ghost
behind a channel line so a channel edit is still visible against the other
three. Ends are pinned to x 0 and 1, a point cannot be dragged past its
neighbours (2% of the axis is the closest they may sit) and cannot be dragged
out of the square, so the graph can never describe a curve the renderer cannot
apply. One pointerdown grabs the nearest point inside 11px or adds one on the
line under the cursor and keeps dragging, so a click is a point and a drag is a
bend. Deleting a point is the graph's own double-click, not the circle's, and it
has to be: grabbing a point takes pointer capture, so the click that follows is
delivered to the SVG rather than the circle under the cursor.
RESET clears the whole graph, all four channels, and hands back an empty object
that `App.tsx` maps to `undefined` so the recipe drops the field rather than
keeping a `toneCurve: {}` — the field's presence is what "this picture has a
curve" means, and an empty map that means the same as no map is a state two
pieces of code would eventually disagree about. One undo step per visit to the
graph, the rule the ruler and the watermark box already ride: a drag is one
edit, not one per pointer move.
No new i18n keys: the chip and the panel labels are literal uppercase, the same
as EXPOSURE and STRAIGHTEN beside them. Not PRO-gated — the curve is a LIGHT
control like the rest of the tab.
Verified:
tone-curve-probe.cjs (new, scratchpad) — a 256x256 greyscale ramp uploaded to
http://localhost:8090, pixels read back off the built app. 33 PASS, 0 FAIL,
no page errors. The ramp is a ramp before (9..246), a flat curve is two
points and no pass, the graph is drawn on the photo (graph 729,280 240x291
against photo 719,325 256x256), every stop of the ramp lands on the drawn
curve (worst deviation 1), black lifts to 132 while white holds 246 -> 252,
a point dragged up bends the line itself (M0.00 112.00 L3.50 110.2...), the
R tab takes the graph over while the composite stays visible behind it and R
drives red at black to 255 with G and B still on the composite (133,132
against 132), the recipe carries toneCurve, it survives a reload (254 -> 254,
chip still amber), a click adds a point and a double-click removes it again,
RESET returns the ramp to its start (worst 0) and drops the field, and close
takes the graph off the photo.
tone-curve-math.cjs (new, scratchpad) — the panel's and the table's own
arithmetic, 11/11: the ends pin and sort, a dragged point lifts where the
graph says, a steeper segment never turns back on itself, a channel curve
runs before the composite, a click lands on the line, two points cannot
share a spot, an end cannot leave the axis, and the two ends survive a
delete where a middle point does not.
Regressions against the rebuilt app, 0 fail: landing-test.cjs 172,
pro-gate-test.cjs 27, award-column-probe.cjs 18, otp-code-probe.cjs 10.
web tsc --noEmit clean.
ponytail: the graph is anchored over the photo, not draggable — it sits at the
photo's own layout box the way the crop frame and the straighten ruler do, and
the one time it would want to move it is when the photo under it is small, at
which point a token drag offset is cheaper than the second positioning system.
Parametric curves (Lightroom's shadows/highlights/darks/lights) are not here:
the point curve is the one the request asked for, and a parametric curve is a
second graph, not a second line on this one — add it as another channel row when
someone asks. The LUT is a texture rather than Skia's table colour filter
because CanvasKit 0.42 has no ColorFilter.MakeTable. The panel's graph size and
hit radius are literals, since exactly one graph exists.
204 lines
8.2 KiB
TypeScript
204 lines
8.2 KiB
TypeScript
import type { ToneCurve, ToneCurveChannel, ToneCurvePoint } from '../types';
|
||
|
||
// LIGHT tab > TONE CURVE — the graph on the photo, and the table the renderer
|
||
// reads it as.
|
||
//
|
||
// One curve per channel, each a list of control points. The graph hands the
|
||
// renderer 256 numbers per channel rather than the points themselves: a point
|
||
// list would have to be interpolated per pixel inside SkSL, and SkSL indexes
|
||
// uniform arrays by constant only (see TONE_SKSL's unrolled mixer), so a table
|
||
// looked up in a texture is both the cheaper and the only workable shape.
|
||
//
|
||
// The interpolation is a monotone cubic (Fritsch–Carlson). A plain cubic spline
|
||
// overshoots between two close points — the classic tone-curve tell, a bright
|
||
// halo next to a lifted shadow — and Lightroom's curves do not do it: drag a
|
||
// point and the line bends through it without ever turning back on itself.
|
||
const EPS = 1e-6;
|
||
const FLAT = 0.002; // how far off the diagonal a point must sit to count as a move
|
||
|
||
export const CURVE_CHANNELS: ToneCurveChannel[] = ['rgb', 'r', 'g', 'b'];
|
||
export const CURVE_LUT_SIZE = 256;
|
||
// What each channel's line is drawn in, and what it does to the pixels.
|
||
export const CURVE_CHANNEL_COLOR: Record<ToneCurveChannel, string> = {
|
||
rgb: '#f2f2f2',
|
||
r: '#ff5a52',
|
||
g: '#4fd06a',
|
||
b: '#4f8dff',
|
||
};
|
||
export const IDENTITY_CURVE: ToneCurvePoint[] = [
|
||
[0, 0],
|
||
[1, 1],
|
||
];
|
||
// The closest two points may sit on the input axis — nearer than this and they
|
||
// would drag each other around instead of moving one bend.
|
||
export const CURVE_MIN_GAP = 0.02;
|
||
|
||
const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);
|
||
const num = (v: unknown, fallback: number) => {
|
||
const n = Number(v);
|
||
return Number.isFinite(n) ? n : fallback;
|
||
};
|
||
|
||
// The stored points, made readable: numbers, inside the square, ordered along
|
||
// the input axis, and pinned to the two ends. Everything below reads a curve
|
||
// through this, so a hand-written recipe file cannot produce a curve the graph
|
||
// and the renderer disagree about.
|
||
export function curvePoints(curve: ToneCurve | undefined, ch: ToneCurveChannel): ToneCurvePoint[] {
|
||
const raw = curve?.[ch];
|
||
if (!Array.isArray(raw) || raw.length < 2) return IDENTITY_CURVE.map((p) => [...p] as ToneCurvePoint);
|
||
const pts = raw
|
||
.map((p) => [clamp01(num(p?.[0], 0)), clamp01(num(p?.[1], 0))] as ToneCurvePoint)
|
||
.sort((a, b) => a[0] - b[0]);
|
||
pts[0][0] = 0;
|
||
pts[pts.length - 1][0] = 1;
|
||
return pts;
|
||
}
|
||
|
||
// True when the curve would move a pixel — the chip's amber dot, and whether the
|
||
// renderer bothers with the pass at all. A point off the diagonal is what makes
|
||
// a curve non-flat: a monotone cubic through points all ON the diagonal is the
|
||
// diagonal.
|
||
export function curveIsActive(curve: ToneCurve | undefined): boolean {
|
||
if (!curve) return false;
|
||
return CURVE_CHANNELS.some((ch) => curvePoints(curve, ch).some((p) => Math.abs(p[1] - p[0]) > FLAT));
|
||
}
|
||
|
||
// Fritsch–Carlson tangents: the slopes that keep the interpolant monotone
|
||
// between the points, and vanish at a flat segment instead of bulging past it.
|
||
function tangents(pts: ToneCurvePoint[]): number[] {
|
||
const n = pts.length;
|
||
const d: number[] = [];
|
||
for (let i = 0; i < n - 1; i++) d.push((pts[i + 1][1] - pts[i][1]) / Math.max(EPS, pts[i + 1][0] - pts[i][0]));
|
||
const m: number[] = new Array(n).fill(0);
|
||
m[0] = d[0];
|
||
m[n - 1] = d[n - 2];
|
||
for (let i = 1; i < n - 1; i++) m[i] = (d[i - 1] + d[i]) / 2;
|
||
for (let i = 0; i < n - 1; i++) {
|
||
if (Math.abs(d[i]) < EPS) {
|
||
m[i] = 0;
|
||
m[i + 1] = 0;
|
||
continue;
|
||
}
|
||
const a = m[i] / d[i];
|
||
const b = m[i + 1] / d[i];
|
||
const s = a * a + b * b;
|
||
if (s > 9) {
|
||
const t = 3 / Math.sqrt(s);
|
||
m[i] = t * a * d[i];
|
||
m[i + 1] = t * b * d[i];
|
||
}
|
||
}
|
||
return m;
|
||
}
|
||
|
||
// The curve's output for one input, clamped into the square: the graph has no
|
||
// room above white or below black, so neither has the curve.
|
||
export function sampleCurve(pts: ToneCurvePoint[], x: number): number {
|
||
const p = Array.isArray(pts) && pts.length >= 2 ? pts : IDENTITY_CURVE;
|
||
const m = tangents(p);
|
||
const t = clamp01(x);
|
||
if (t <= p[0][0]) return clamp01(p[0][1]);
|
||
for (let i = 0; i < p.length - 1; i++) {
|
||
if (t <= p[i + 1][0]) {
|
||
const h = Math.max(EPS, p[i + 1][0] - p[i][0]);
|
||
const s = (t - p[i][0]) / h;
|
||
const s2 = s * s;
|
||
const s3 = s2 * s;
|
||
const y =
|
||
(2 * s3 - 3 * s2 + 1) * p[i][1] +
|
||
(s3 - 2 * s2 + s) * h * m[i] +
|
||
(-2 * s3 + 3 * s2) * p[i + 1][1] +
|
||
(s3 - s2) * h * m[i + 1];
|
||
return clamp01(y);
|
||
}
|
||
}
|
||
return clamp01(p[p.length - 1][1]);
|
||
}
|
||
|
||
// The curve as the renderer reads it: 256 entries per output channel, in one
|
||
// RGBA row — R, G, B are the three channels' own curves and A is unused (kept at
|
||
// 255 so the image is unambiguous). Each channel's curve runs first and the
|
||
// composite after it, so a point moved on R means "R, as the composite curve
|
||
// then leaves it".
|
||
export function curveLut(curve: ToneCurve | undefined): Uint8Array {
|
||
const master = curvePoints(curve, 'rgb');
|
||
const chans = (['r', 'g', 'b'] as const).map((ch) => curvePoints(curve, ch));
|
||
const out = new Uint8Array(CURVE_LUT_SIZE * 4);
|
||
for (let i = 0; i < CURVE_LUT_SIZE; i++) {
|
||
const v = i / (CURVE_LUT_SIZE - 1);
|
||
for (let c = 0; c < 3; c++) out[i * 4 + c] = Math.round(sampleCurve(master, sampleCurve(chans[c], v)) * 255);
|
||
out[i * 4 + 3] = 255;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// The curve pass: the graded pixels in, the table's answer out. The LUT is
|
||
// sampled at texel centres (`v * 255 + 0.5`), which is where the 256 values
|
||
// actually sit, so entry i returns entry i and the ends clamp to the end values.
|
||
export const CURVE_SKSL = `
|
||
uniform shader src;
|
||
uniform shader lut;
|
||
vec4 main(vec2 xy) {
|
||
vec4 c = src.eval(xy);
|
||
vec3 v = clamp(c.rgb, 0.0, 1.0) * 255.0 + 0.5;
|
||
return vec4(
|
||
lut.eval(vec2(v.r, 0.5)).r,
|
||
lut.eval(vec2(v.g, 0.5)).g,
|
||
lut.eval(vec2(v.b, 0.5)).b,
|
||
c.a
|
||
);
|
||
}
|
||
`;
|
||
|
||
// --- what the graph itself does to a point list ----------------------------
|
||
// Kept here rather than in the panel: the rules (which point may move where,
|
||
// what a click adds, what survives a delete) are about the curve, not the SVG.
|
||
|
||
export function addCurvePoint(pts: ToneCurvePoint[], x: number, y: number): ToneCurvePoint[] {
|
||
const px = clamp01(x);
|
||
const py = clamp01(y);
|
||
let at = pts.length;
|
||
for (let i = 0; i < pts.length; i++) {
|
||
if (pts[i][0] >= px) {
|
||
at = i;
|
||
break;
|
||
}
|
||
}
|
||
const before = at > 0 ? pts[at - 1] : null;
|
||
const after = at < pts.length ? pts[at] : null;
|
||
if (before && px - before[0] < CURVE_MIN_GAP) return pts;
|
||
if (after && after[0] - px < CURVE_MIN_GAP) return pts;
|
||
// A click adds the point ON the line under it, not where the pointer was: the
|
||
// promise is "grab the curve here", and a click that moved the picture by
|
||
// itself would make the graph dangerous. A click that does not lift is a point
|
||
// added and left on the line — no pixel moves until one is dragged.
|
||
return [...pts.slice(0, at), [px, sampleCurve(pts, px)] as ToneCurvePoint, ...pts.slice(at)];
|
||
}
|
||
|
||
// `at` is the point's index in the list; the two ends keep their place on the
|
||
// input axis (they are black and white) and slide freely on the output axis.
|
||
export function moveCurvePoint(pts: ToneCurvePoint[], at: number, x: number, y: number): ToneCurvePoint[] {
|
||
if (at < 0 || at >= pts.length) return pts;
|
||
const next = pts.map((p) => [...p] as ToneCurvePoint);
|
||
const first = at === 0;
|
||
const last = at === pts.length - 1;
|
||
const lo = first ? 0 : Math.min(pts[at - 1][0] + CURVE_MIN_GAP, 1 - CURVE_MIN_GAP);
|
||
const hi = last ? 1 : Math.max(pts[at + 1][0] - CURVE_MIN_GAP, CURVE_MIN_GAP);
|
||
next[at][0] = first ? 0 : last ? 1 : Math.max(lo, Math.min(hi, clamp01(x)));
|
||
next[at][1] = clamp01(y);
|
||
return next;
|
||
}
|
||
|
||
export function removeCurvePoint(pts: ToneCurvePoint[], at: number): ToneCurvePoint[] {
|
||
if (at <= 0 || at >= pts.length - 1) return pts;
|
||
const next = pts.filter((_, i) => i !== at);
|
||
return next.length >= 2 ? next : IDENTITY_CURVE.map((p) => [...p] as ToneCurvePoint);
|
||
}
|
||
|
||
// Where a curve sits at the ends, for a caller that wants to say "R: +12 at the
|
||
// top" — the panel prints nothing today, but the reset button and the chip need
|
||
// the same "is it flat" answer.
|
||
export function isFlatCurve(pts: ToneCurvePoint[]): boolean {
|
||
return pts.every((p) => Math.abs(p[1] - p[0]) <= FLAT);
|
||
}
|