Grade preset previews over the current edit and print the look's cast

Preset tiles were rendered from a reset grade, so correcting a frame and then
browsing looks showed thumbnails that no longer matched the canvas, and the
settle timer was keyed on object identity so the rail rarely caught up at all.
Tiles now render the whole grade a moment after it settles, keep their previous
images while the batch re-renders, and the Light panel shows the applied look's
cast and the final white balance under Temp and Tint.
This commit is contained in:
2026-12-02 05:27:12 +00:00
parent 4d7a123d49
commit 5b4b49200c
14 changed files with 397 additions and 31 deletions
+10 -4
View File
@@ -7,10 +7,16 @@ page; this file is the complete list.
Finished in the tree, not part of any build yet. Finished in the tree, not part of any build yet.
- **An audited offline guarantee.** A content security policy restricts connections to - **Film looks and presets grade over your white balance.** Applying a look used
the app's own origin, `npm run check:offline` fails the build if any shipped file to overwrite Temp and Tint with the stock's own numbers, so a frame that had
reaches for another host, and [docs/OFFLINE-GUARANTEE.md](docs/OFFLINE-GUARANTEE.md) been corrected came back with the look's cast on an uncorrected image. The
states what the app does and does not contact. cast is now kept apart from the sliders and applied after your correction; it
layers on instead of replacing it, and switching looks swaps the cast rather
than stacking them. Every preset tile now renders over the photo's whole
current grade — exposure, tone, colour, crop and white balance — so a
thumbnail is what the click produces, and the rail keeps its images while the
tiles catch up. The Light panel reports the applied look's cast and the final
balance the photo is graded at, under Temp and Tint.
- **Object removal on the server** (`POST /api/photos/:id/inpaint`, LaMa, Apache-2.0, - **Object removal on the server** (`POST /api/photos/:id/inpaint`, LaMa, Apache-2.0,
bundled weights, no network). The routes and the cached-render store are in place; bundled weights, no network). The routes and the cached-render store are in place;
there is no editor control for it yet, so nothing changes for a user. there is no editor control for it yet, so nothing changes for a user.
+2 -2
View File
@@ -855,11 +855,11 @@
<figure> <figure>
<img src="img/08-presets.jpg" alt="The preset rail"> <img src="img/08-presets.jpg" alt="The preset rail">
<figcaption><b>Figure 14.</b> The preset rail with search, category filter, the look variants (Stock, Push +1, Pull −1, Warm split, Cool split) and tiles rendered from your own photo at your current crop.</figcaption> <figcaption><b>Figure 14.</b> The preset rail with search, category filter, the look variants (Stock, Push +1, Pull −1, Warm split, Cool split) and tiles rendered from your own photo at your current crop, tone, colour and white balance.</figcaption>
</figure> </figure>
<h2>Presets</h2> <h2>Presets</h2>
<p>Groups include Essentials, Film, Warm and Cinematic. The variant row re-renders the whole rail a stop brighter or darker, or with the split-tone reversed. Click a tile to apply: it replaces the develop parameters but leaves crop and rotation alone, because those belong to the frame. <b>+</b> saves the current look as your own preset with a rendered preview.</p> <p>Groups include Essentials, Film, Warm and Cinematic. The variant row re-renders the whole rail a stop brighter or darker, or with the split-tone reversed. Click a tile to apply: the look's tone and colour replace the develop parameters, while crop and rotation stay, because those belong to the frame. The white balance you set is kept as the base the look is graded over — the stock's own warmth or coolness is added on top of it, so correct a difficult frame first and the film still sits over that correction. Switching looks swaps that cast instead of stacking one stock's cast on the last one's. Because the look adds its cast to your correction, the Light panel prints both: the look's own cast and the final balance the photo is graded at, right under Temp and Tint. Every tile is rendered over the grade the photo has now, so the thumbnail is what the click produces. <b>+</b> saves the current look as your own preset with a rendered preview.</p>
<h2>History, undo and redo</h2> <h2>History, undo and redo</h2>
<p>Every adjustment is recorded with a label. <b>History</b> in the left rail restores any step; <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back, <kbd>⇧</kbd> + <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps forward. History is per photo and saved with the catalogue.</p> <p>Every adjustment is recorded with a label. <b>History</b> in the left rail restores any step; <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps back, <kbd>⇧</kbd> + <kbd>⌘ / Ctrl</kbd> + <kbd>Z</kbd> steps forward. History is per photo and saved with the catalogue.</p>
+4 -12
View File
@@ -16,6 +16,7 @@ import type { Preview16 } from '../lib/preview16';
import { useMediaQuery } from '../lib/useMediaQuery'; import { useMediaQuery } from '../lib/useMediaQuery';
import { usePersistentState } from '../lib/usePersistentState'; import { usePersistentState } from '../lib/usePersistentState';
import { solveWhiteBalance } from '../lib/whiteBalance'; import { solveWhiteBalance } from '../lib/whiteBalance';
import { applyPresetEdits } from '../lib/presets';
import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask'; import { buildAutoMask, type AutoMaskKind } from '../lib/autoMask';
import { import {
buildLensCorrection, buildLensCorrection,
@@ -1647,18 +1648,9 @@ export default function Develop({
const applyPreset = useCallback( const applyPreset = useCallback(
(preset: Preset) => { (preset: Preset) => {
const next: Edits = // The look grades over the photo's current white balance, so a correction
preset.id === 'original' // made first is the base it is applied against.
? { ...defaultEdits(), crop: photo.edits.crop } const next = applyPresetEdits(photo.edits, preset);
: {
...photo.edits,
...preset.edits,
crop: photo.edits.crop,
// The camera profile belongs to the body that produced the raw.
cameraProfile: photo.edits.cameraProfile,
// A strong film response must not leak into the next look.
redscale: preset.edits.redscale ?? 0,
};
onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`); onUpdate(photo.id, { edits: next }, `Preset: ${preset.name}`);
}, },
[onUpdate, photo.id, photo.edits], [onUpdate, photo.id, photo.edits],
+24
View File
@@ -11,6 +11,7 @@ import {
} from '../lib/denoiseModels'; } from '../lib/denoiseModels';
import type { DenoiseProgress } from '../lib/api'; import type { DenoiseProgress } from '../lib/api';
import { clamp } from '../lib/curves'; import { clamp } from '../lib/curves';
import { estimateKelvin, expressWhiteBalance, wbGainWithLook } from '../lib/whiteBalance';
import { addKeywordPath, removeKeywordPath } from '../lib/keywords'; import { addKeywordPath, removeKeywordPath } from '../lib/keywords';
import type { import type {
CurveChannel, CurveChannel,
@@ -108,6 +109,12 @@ export function BasicPanel({
// come back with neutral values, so Auto WB matched As shot exactly. // come back with neutral values, so Auto WB matched As shot exactly.
const thumbSrc = photo.thumbUrl ?? photo.thumb; const thumbSrc = photo.thumbUrl ?? photo.thumb;
// A look adds its cast to the correction already in the sliders; this shows what
// that leaves the white balance at, so the final balance stays visible.
const lookCast = edits.presetLook && (edits.presetLook.temp || edits.presetLook.tint) ? edits.presetLook : null;
const finalWb = lookCast ? expressWhiteBalance(wbGainWithLook(edits.temp, edits.tint, edits.kelvin, lookCast)) : null;
const signed = (v: number) => (v > 0 ? `+${v}` : String(v));
const auto = async () => { const auto = async () => {
setAutoBusy(true); setAutoBusy(true);
try { try {
@@ -181,6 +188,23 @@ export function BasicPanel({
onChange={(v) => set({ tint: v }, 'Tint')} onChange={(v) => set({ tint: v }, 'Tint')}
track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)" track="linear-gradient(90deg,#54b364,#a8b6c6,#c56ad2)"
/> />
{lookCast && finalWb && (
<div
className="wb-look"
title="The look grades over your white balance, so it adds its own temperature and tint on top. These are the numbers the photo is actually graded at."
>
<span>
Look cast <b>{signed(lookCast.temp)} / {signed(lookCast.tint)}</b>
</span>
<span className="wb-look-final">
Final{' '}
{edits.kelvin != null
? `≈ ${Math.round(estimateKelvin(wbGainWithLook(edits.temp, edits.tint, edits.kelvin, lookCast)) / 10) * 10} K`
: `temp ${signed(finalWb.temp)}`}{' '}
· tint {signed(finalWb.tint)}
</span>
</div>
)}
<div className="subhead"> <div className="subhead">
<span>Tone</span> <span>Tone</span>
+69 -8
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { normalizeEdits } from '../lib/edits'; import { applyPresetEdits } from '../lib/presets';
import { get16BitSource, getBitmap } from '../lib/images'; import { get16BitSource, getBitmap } from '../lib/images';
import { Renderer, rotatedBounds } from '../gl/renderer'; import { Renderer, rotatedBounds } from '../gl/renderer';
import type { PhotoRecord, Preset } from '../types'; import type { PhotoRecord, Preset } from '../types';
@@ -17,17 +17,66 @@ const THUMB_EDGE = 200;
const keyOf = (photoId: string, presetId: string, crop: string, source: string) => const keyOf = (photoId: string, presetId: string, crop: string, source: string) =>
`${photoId}|${presetId}|${crop}|${source}`; `${photoId}|${presetId}|${crop}|${source}`;
/** Stringified grades, cached per edits object so a render loop cannot make this
* cost more than one serialisation. */
const signatures = new WeakMap<object, string>();
function gradeSignature(edits: object): string {
let sig = signatures.get(edits);
if (sig === undefined) {
sig = JSON.stringify(edits);
signatures.set(edits, sig);
}
return sig;
}
/**
* A slider drag produces a new grade every frame. Re-rendering the whole rail
* that often would make the canvas stutter, so the tiles follow the grade a
* moment after it settles.
*
* The timer is keyed on the grade's signature, not on the object: the editor can
* hand down a fresh edits object on every render, and an identity-keyed timer
* would then be reset forever and the rail would never catch up.
*/
function useSettledEdits<T extends object>(edits: T, sig: string, delay: number): T {
const [settled, setSettled] = useState(() => ({ sig, edits }));
useEffect(() => {
if (sig === settled.sig) return;
const timer = window.setTimeout(() => setSettled({ sig, edits }), delay);
return () => window.clearTimeout(timer);
// `edits` is read from the render that changed the signature; restarting on
// a new object with the same grade is exactly what this avoids.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sig, delay, settled.sig]);
return settled.edits;
}
export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> { export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<string, string> {
const [thumbs, setThumbs] = useState<Record<string, string>>({}); const [thumbs, setThumbs] = useState<Record<string, string>>({});
// Which photo the thumbnails in state belong to; a new photo may not reuse them.
const shownPhoto = useRef(photo.id);
// Preset edits never change after creation, so a stable id list is enough to // Preset edits never change after creation, so a stable id list is enough to
// avoid re-running for every parent render. // avoid re-running for every parent render.
const presetKey = presets.map((p) => p.id).join('|'); const presetKey = presets.map((p) => p.id).join('|');
const crop = photo.edits.crop; // Tiles show the look over the grade the photo has right now, so clicking one
// is what the thumbnail promised. The grade is read once it settles instead of
// on every frame of a slider drag.
const settled = useSettledEdits(photo.edits, gradeSignature(photo.edits), 280);
// Applying a look replaces any cast the last one added, so the current look is
// dropped from the base: tiles keep their images while the photographer clicks
// through looks, and each tile still shows what that click would produce.
const base =
settled.presetLook && (settled.presetLook.temp || settled.presetLook.tint)
? { ...settled, presetLook: { temp: 0, tint: 0 } }
: settled;
const crop = base.crop;
const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(','); const cropKey = [crop.x, crop.y, crop.w, crop.h, crop.angle, crop.quarter, crop.flipH, crop.flipV].join(',');
// The preset previews keep the photo's camera profile, so a reprocess or a // The preset previews keep the photo's camera profile, so a reprocess or a
// different profile has to invalidate tiles the same way a crop does. // different profile has to invalidate the tiles the same way the grade does.
const profile = photo.edits.cameraProfile; const profile = base.cameraProfile;
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}`; const gradeKey = JSON.stringify({ ...base, crop: undefined, cameraProfile: undefined });
const sourceKey = `${photo.previewVersion ?? 0}|${profile ? profile.matrix.join(',') : ''}|${gradeKey}`;
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -39,7 +88,19 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey)); const hit = cache.get(keyOf(photo.id, preset.id, cropKey, sourceKey));
if (hit) known[preset.id] = hit; if (hit) known[preset.id] = hit;
} }
setThumbs(known); // Keep the previous tiles of this photo on screen until their replacements
// render: a grade change must not empty the rail for the five seconds a full
// batch takes.
const samePhoto = shownPhoto.current === photo.id;
shownPhoto.current = photo.id;
setThumbs((prev) => {
const next: Record<string, string> = {};
for (const preset of presets) {
const url = known[preset.id] ?? (samePhoto ? prev[preset.id] : undefined);
if (url) next[preset.id] = url;
}
return next;
});
const pending = presets.filter((p) => !known[p.id]); const pending = presets.filter((p) => !known[p.id]);
if (!pending.length) return; if (!pending.length) return;
@@ -63,7 +124,7 @@ export function usePresetThumbs(photo: PhotoRecord, presets: Preset[]): Record<s
for (const preset of pending) { for (const preset of pending) {
if (!alive) break; if (!alive) break;
try { try {
renderer.render({ ...normalizeEdits(preset.edits), crop, cameraProfile: profile }, { renderer.render(applyPresetEdits(base, preset), {
width, width,
height, height,
upscale: Math.max(width / cropW, height / cropH) > 1.05, upscale: Math.max(width / cropW, height / cropH) > 1.05,
+4 -2
View File
@@ -3,7 +3,7 @@ import type { Preview16 } from '../lib/preview16';
import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types'; import type { CurvePoint, Edits, GeometryEdits, LocalLayer } from '../types';
import { buildSampler, clamp01 } from '../lib/curves'; import { buildSampler, clamp01 } from '../lib/curves';
import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits'; import { bwFilterRgb, MAX_HEAL_SPOTS, MAX_LOCAL_LAYERS } from '../lib/edits';
import { wbGainFor } from '../lib/whiteBalance'; import { wbGainWithLook } from '../lib/whiteBalance';
import { buildLocalMasks, maskSignature } from './masks'; import { buildLocalMasks, maskSignature } from './masks';
import { getActiveProofCube, type SoftProofCube } from '../lib/softProof'; import { getActiveProofCube, type SoftProofCube } from '../lib/softProof';
@@ -1875,7 +1875,9 @@ export class Renderer {
g.f('u_srcLod', Math.max(0, Math.min(12, srcLod))); g.f('u_srcLod', Math.max(0, Math.min(12, srcLod)));
g.f('u_pick', -1); g.f('u_pick', -1);
g.v2('u_pickUv', 0, 0); g.v2('u_pickUv', 0, 0);
const wb = wbGainFor(edits.temp, edits.tint, edits.kelvin); // The photographer's correction is the base; an applied look only adds its
// cast on top of it (see applyPresetEdits).
const wb = wbGainWithLook(edits.temp, edits.tint, edits.kelvin, edits.presetLook);
g.v3('u_wbGain', wb[0], wb[1], wb[2]); g.v3('u_wbGain', wb[0], wb[1], wb[2]);
g.f('u_exposure', edits.exposure); g.f('u_exposure', edits.exposure);
g.f('u_recovery', edits.recovery); g.f('u_recovery', edits.recovery);
+1
View File
@@ -82,6 +82,7 @@ const GROUPS: Record<EditSectionId, (keyof Edits)[]> = {
'temp', 'temp',
'tint', 'tint',
'kelvin', 'kelvin',
'presetLook',
'exposure', 'exposure',
'recovery', 'recovery',
'contrast', 'contrast',
+5
View File
@@ -178,6 +178,7 @@ export function defaultEdits(): Edits {
temp: 0, temp: 0,
tint: 0, tint: 0,
kelvin: null, kelvin: null,
presetLook: { temp: 0, tint: 0 },
exposure: 0, exposure: 0,
recovery: 0, recovery: 0,
contrast: 0, contrast: 0,
@@ -512,6 +513,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
typeof input.kelvin === 'number' && Number.isFinite(input.kelvin) typeof input.kelvin === 'number' && Number.isFinite(input.kelvin)
? clamp(input.kelvin, 1500, 15000) ? clamp(input.kelvin, 1500, 15000)
: null, : null,
presetLook: {
temp: num(input.presetLook?.temp, 0, -100, 100),
tint: num(input.presetLook?.tint, 0, -100, 100),
},
exposure: num(input.exposure, 0, -5, 5), exposure: num(input.exposure, 0, -5, 5),
recovery: num(input.recovery, 0, 0, 100), recovery: num(input.recovery, 0, 0, 100),
contrast: num(input.contrast, 0, -100, 100), contrast: num(input.contrast, 0, -100, 100),
+77 -2
View File
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { applyFilmVariant, FILM_PRESETS, PRESETS, PRESET_CATEGORIES } from './presets'; import {
import { normalizeEdits } from './edits'; applyFilmVariant,
applyPresetEdits,
FILM_PRESETS,
PRESETS,
PRESET_CATEGORIES,
} from './presets';
import { defaultEdits, normalizeEdits } from './edits';
describe('preset library', () => { describe('preset library', () => {
it('ships an extensive, uniquely identified catalogue', () => { it('ships an extensive, uniquely identified catalogue', () => {
@@ -44,6 +50,21 @@ describe('preset library', () => {
expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true); expect(redscale.some((preset) => preset.film?.process === 'E-6')).toBe(true);
}); });
it('keeps a user preset a full recipe rather than a cast', () => {
const base = { ...defaultEdits(), temp: -24, tint: 9 };
const custom = {
id: 'my-look',
name: 'My look',
group: 'User presets',
custom: true,
edits: { temp: 30, contrast: 12 },
};
const next = applyPresetEdits(base, custom);
expect(next.temp).toBe(30);
expect(next.presetLook).toEqual({ temp: 0, tint: 0 });
expect(next.contrast).toBe(12);
});
it('derives push/pull variants for film stocks only', () => { it('derives push/pull variants for film stocks only', () => {
const stock = FILM_PRESETS[0]; const stock = FILM_PRESETS[0];
expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`); expect(applyFilmVariant(stock, 'push').id).toBe(`${stock.id}::push`);
@@ -52,3 +73,57 @@ describe('preset library', () => {
expect(applyFilmVariant(look!, 'push')).toBe(look); expect(applyFilmVariant(look!, 'push')).toBe(look);
}); });
}); });
describe('looks over the photo’s own grade', () => {
const graded = () => ({ ...defaultEdits(), temp: -24, tint: 9 });
it('keeps the white balance already set and layers the look’s cast on it', () => {
const stock = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) !== 0)!;
const next = applyPresetEdits(graded(), stock);
expect(next.temp).toBe(-24);
expect(next.tint).toBe(9);
expect(next.presetLook).toEqual({
temp: stock.edits.temp ?? 0,
tint: stock.edits.tint ?? 0,
});
// The look still sets its own tone and colour.
expect(next.contrast).toBe(stock.edits.contrast);
});
it('replaces the previous look’s cast instead of stacking it', () => {
const warm = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) > 10)!;
const cool = FILM_PRESETS.find((preset) => (preset.edits.temp ?? 0) < -10)!;
const once = applyPresetEdits(graded(), warm);
const twice = applyPresetEdits(once, cool);
expect(twice.temp).toBe(-24);
expect(twice.tint).toBe(9);
expect(twice.presetLook).toEqual({ temp: cool.edits.temp ?? 0, tint: cool.edits.tint ?? 0 });
});
it('leaves the white balance alone for a preset with no cast of its own', () => {
const plain = PRESETS.find(
(preset) =>
preset.id !== 'original' &&
!preset.film &&
preset.edits.temp === undefined &&
preset.edits.tint === undefined,
)!;
const next = applyPresetEdits(graded(), plain);
expect(next.temp).toBe(-24);
expect(next.tint).toBe(9);
expect(next.presetLook).toEqual({ temp: 0, tint: 0 });
});
it('clears the grade and the cast with the original', () => {
const applied = applyPresetEdits(graded(), FILM_PRESETS[0]);
const original = applyPresetEdits(applied, {
id: 'original',
name: 'Original',
group: 'Essentials',
edits: {},
});
expect(original.temp).toBe(0);
expect(original.tint).toBe(0);
expect(original.presetLook).toEqual({ temp: 0, tint: 0 });
});
});
+39
View File
@@ -1,4 +1,5 @@
import type { BwFilter, Edits, Preset } from '../types'; import type { BwFilter, Edits, Preset } from '../types';
import { defaultEdits, normalizeEdits } from './edits';
const identity = () => [ const identity = () => [
{ x: 0, y: 0 }, { x: 0, y: 0 },
@@ -2925,6 +2926,44 @@ export const PRESETS: Preset[] = ([
: preset; : preset;
}); });
/**
* Applies a look over the grade the photo already has.
*
* White balance is the base the look is graded against: the look's own Temp and
* Tint become a cast in `presetLook` on top of the correction already made,
* instead of overwriting it. Storing the cast apart also means switching looks
* replaces it rather than stacking one stock's warmth on the last one's, and
* the preview tiles can show exactly what the click will produce. A user preset
* is a recipe copied from a photo, so it still replaces the whole grade, and
* "original" clears it.
*/
export function applyPresetEdits(base: Edits, preset: Preset): Edits {
if (preset.id === 'original') {
return { ...defaultEdits(), crop: base.crop, cameraProfile: base.cameraProfile };
}
const { temp = 0, tint = 0, ...look } = preset.edits;
const next: Edits = {
...base,
...look,
crop: base.crop,
// The camera profile belongs to the body that produced the raw.
cameraProfile: base.cameraProfile,
// A strong film response must not leak into the next look.
redscale: look.redscale ?? 0,
};
if (preset.custom) {
// A recipe keeps the white balance it was saved with.
next.temp = temp;
next.tint = tint;
} else {
next.temp = base.temp;
next.tint = base.tint;
next.kelvin = base.kelvin;
next.presetLook = { temp, tint };
}
return normalizeEdits(next);
}
/* ------------------------------------------------------------- film variants */ /* ------------------------------------------------------------- film variants */
export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool'; export type FilmVariant = 'base' | 'push' | 'pull' | 'warm' | 'cool';
+66 -1
View File
@@ -1,5 +1,48 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { kelvinGains, wbGainFor, WB_REFERENCE_KELVIN } from './whiteBalance'; import {
estimateKelvin,
expressWhiteBalance,
kelvinGains,
wbGainFor,
wbGainWithLook,
WB_REFERENCE_KELVIN,
} from './whiteBalance';
describe('expressWhiteBalance', () => {
it('recovers the sliders that produced a correction', () => {
for (const [temp, tint] of [
[30, -12],
[-55, 40],
[0, 0],
[80, 60],
]) {
const back = expressWhiteBalance(wbGainFor(temp, tint, null));
expect(back.temp).toBeCloseTo(temp, 0);
expect(back.tint).toBeCloseTo(tint, 0);
}
});
it('reads a look cast as the balance it leaves behind', () => {
const look = { temp: 35, tint: -8 };
const gain = wbGainWithLook(-20, 10, null, look);
const back = expressWhiteBalance(gain);
// The recovered pair reproduces the same gain the look left on the photo, to
// within what whole-number sliders can express.
const again = wbGainFor(back.temp, back.tint, null);
expect(again[0]).toBeCloseTo(gain[0], 2);
expect(again[1]).toBeCloseTo(gain[1], 2);
expect(again[2]).toBeCloseTo(gain[2], 2);
// Warm cast over a cool correction lands near the sum of the two.
expect(back.temp).toBeGreaterThan(11);
expect(back.temp).toBeLessThan(19);
});
it('estimates the Kelvin of an absolute balance', () => {
expect(estimateKelvin(kelvinGains(3200))).toBeGreaterThan(3100);
expect(estimateKelvin(kelvinGains(3200))).toBeLessThan(3300);
expect(estimateKelvin(kelvinGains(WB_REFERENCE_KELVIN))).toBeCloseTo(WB_REFERENCE_KELVIN, -2);
});
});
describe('absolute white balance', () => { describe('absolute white balance', () => {
it('is neutral at the daylight reference', () => { it('is neutral at the daylight reference', () => {
@@ -32,4 +75,26 @@ describe('absolute white balance', () => {
expect(luma).toBeCloseTo(1, 4); expect(luma).toBeCloseTo(1, 4);
} }
}); });
it('grades a look’s cast over the correction already made', () => {
const corrected = wbGainFor(-30, 0, null);
const withLook = wbGainWithLook(-30, 0, null, { temp: 20, tint: 0 });
// The look warms the corrected frame without throwing the correction away.
expect(withLook[0]).toBeGreaterThan(corrected[0]);
expect(withLook[2]).toBeLessThan(corrected[2]);
// Adding the two offsets is what the sliders would do by hand.
const summed = wbGainFor(-10, 0, null);
expect(withLook[0]).toBeCloseTo(summed[0], 2);
expect(withLook[2]).toBeCloseTo(summed[2], 2);
const luma = 0.2126 * withLook[0] + 0.7152 * withLook[1] + 0.0722 * withLook[2];
expect(luma).toBeCloseTo(1, 4);
});
it('leaves the gain untouched when the look has no cast', () => {
expect(wbGainWithLook(0, 0, null, { temp: 0, tint: 0 })).toEqual(wbGainFor(0, 0, null));
// An absolute Kelvin correction is still the base for the cast.
const kelvin = wbGainFor(0, 0, 3200);
const warmed = wbGainWithLook(0, 0, 3200, { temp: 12, tint: 0 });
expect(warmed[0]).toBeGreaterThan(kelvin[0]);
});
}); });
+68
View File
@@ -108,6 +108,74 @@ export function wbGainFor(
return gain.map((v) => v / norm) as [number, number, number]; return gain.map((v) => v / norm) as [number, number, number];
} }
/**
* The white balance with an applied look's cast layered over it.
*
* The correction the photographer already made stays the base: a look's
* Temp/Tint is a cast added on top, not a replacement for it. Keeping the two
* separate (see `Edits['presetLook']`) also lets switching looks swap the cast
* instead of stacking one stock's warmth on the last one's. Normalised again
* so the look changes colour, not exposure.
*/
export function wbGainWithLook(
temp: number,
tint: number,
kelvin: number | null,
look: { temp: number; tint: number } | null | undefined,
): [number, number, number] {
const base = wbGainFor(temp, tint, kelvin);
if (!look || (!look.temp && !look.tint)) return base;
const cast = wbGainFor(look.temp, look.tint, null);
const gain: [number, number, number] = [base[0] * cast[0], base[1] * cast[1], base[2] * cast[2]];
const luma = 0.2126 * gain[0] + 0.7152 * gain[1] + 0.0722 * gain[2];
const norm = Math.max(0.05, luma);
return gain.map((v) => v / norm) as [number, number, number];
}
/**
* The Temp/Tint pair that reproduces a gain vector.
*
* A look layers its cast over the correction, so the two sliders no longer show
* what the photo is graded at. Inverting the gains (ratios only, so the shared
* luma normalisation drops out) gives the pair that would: `r/b` is fixed by
* temperature alone, then green carries the tint.
*/
export function expressWhiteBalance(
gain: readonly number[],
): { temp: number; tint: number } {
const [r, g, b] = gain;
if (![r, g, b].every((v) => Number.isFinite(v) && v > 0)) return { temp: 0, tint: 0 };
// r/b = (1 + 0.3t) / (1 − 0.26t)
const t = (r - b) / (T_R * b + T_B * r);
// g/r = (1 − 0.16i) / ((1 + 0.3t)(1 + 0.06i))
const d = 1 + T_R * t;
const a = g / r;
const i = (1 - a * d) / (TINT_CROSS * a * d + T_TINT);
return {
temp: Math.round(clampRange(t * 100, -100, 100)),
tint: Math.round(clampRange(i * 100, -100, 100)),
};
}
/**
* The Kelvin setting whose black-body balance best matches a gain vector's red
* to blue ratio. Used to report a look's cast on the absolute-Kelvin control.
*/
export function estimateKelvin(gain: readonly number[]): number {
const target = Math.log(Math.max(1e-4, gain[0]) / Math.max(1e-4, gain[2]));
let best = WB_REFERENCE_KELVIN;
let bestErr = Infinity;
for (let k = 1500; k <= 12000; k += 25) {
const [r, , b] = kelvinGains(k);
const err = Math.abs(Math.log(r / b) - target);
if (err < bestErr) {
bestErr = err;
best = k;
}
}
return best;
}
/** /**
* Temperature and tint that make a sampled source colour neutral. * Temperature and tint that make a sampled source colour neutral.
* `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel. * `sample` is the untouched (sRGB-encoded) source pixel, 0–1 per channel.
+21
View File
@@ -1650,6 +1650,27 @@ figcaption {
margin-top: 2px; margin-top: 2px;
} }
/* The look's cast and the balance it leaves the photo at, under Temp/Tint. */
.wb-look {
display: flex;
flex-wrap: wrap;
gap: 2px 10px;
margin: 1px 0 5px;
font-size: 10.5px;
color: var(--muted);
}
.wb-look b {
color: #d9d9e2;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.wb-look-final {
margin-left: auto;
font-variant-numeric: tabular-nums;
}
.row { .row {
display: grid; display: grid;
grid-template-columns: 74px 1fr 44px; grid-template-columns: 74px 1fr 44px;
+7
View File
@@ -167,6 +167,13 @@ export interface Edits {
* the demosaiced proxy is assumed to be balanced for. * the demosaiced proxy is assumed to be balanced for.
*/ */
kelvin: number | null; kelvin: number | null;
/**
* White-balance cast of an applied look (film stock or preset), kept apart
* from `temp`/`tint`. A look grades on top of the correction already made,
* so an adjusted white balance stays the base it is applied against instead
* of being replaced by the look's own cast.
*/
presetLook: { temp: number; tint: number };
exposure: number; exposure: number;
/** pulls clipped highlights back into range without shifting hue */ /** pulls clipped highlights back into range without shifting hue */
recovery: number; recovery: number;