Skip to content

Free open-source image editor for the browser

Add image-centered vignette controls to Adjust (#25)

Rodrigo Belfiore9fbcdb5c8300
diff --git a/API.md b/API.md
index 3bd952e..154ebb5 100644
--- a/API.md
+++ b/API.md
@@ -49,6 +49,8 @@ Loading calls are queued. XMP import is skipped if no document is ready; an inva
`setColorMixer(color, change)` updates one of `red`, `orange`, `yellow`, `green`, `aqua`, `blue`, `purple`, or `magenta`. Supply any of `hue`, `saturation`, and `luminance`, each a finite number from -100 to 100. Other colors and unspecified channels keep their values. `resetColorMixer()` resets every color as one undoable edit. A full shift of 100 rotates hue by 30°, scales saturation from zero to double, or moves luminance by one stop, weighted by each pixel's distance to the color's Oklab hue. Hue and saturation edits preserve luminance, and neutrals are unaffected.
+`setVignette({ intensity, softness })` updates either or both values, each a finite number from 0 to 100. Defaults are intensity 0 and softness 50. Intensity 0 bypasses the effect; increasing softness spreads the transition toward the center. The elliptical falloff is centered on the source image, before crop/rotation, independent of viewport zoom and pan. It multiplies linear RGB equally, preserves alpha and HDR headroom, and uses the same processing for preview and export. Double-click either slider to restore its default.
+
For RAW sources, `setWhiteBalance({ temperature, tint })` sets absolute Kelvin and DNG tint, preserving unspecified values. Temperature accepts 2000–25000 K and tint accepts -150–150, extending either range to include the file's As Shot value. `setWhiteBalance()` restores that value (the decoder's daylight fallback if camera multipliers are unavailable). Non-RAW sources and invalid values throw. Incremental temperature/tint remain separate RGB adjustments.
Edits update the scene and history synchronously. Rendering may finish later, particularly RAW development. Tests should wait for visible results; `exportImage()` renders and waits for its captured scene independently of the preview.
@@ -106,6 +108,6 @@ The image renders at the document dimensions and downsamples to `longEdge` with
## State
-`getState()` returns a detached snapshot containing `file`, `documentId`, `size`, `frame`, `adjustments`, `whiteBalance`, `toneCurve`, `colorMixer`, `preview`, and `history`. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the filename, and `history` contains `undoCount` and `redoCount`.
+`getState()` returns a detached snapshot containing `file`, `documentId`, `size`, `frame`, `adjustments`, `whiteBalance`, `toneCurve`, `colorMixer`, `vignette`, `preview`, and `history`. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the filename, and `history` contains `undoCount` and `redoCount`.
Without a document, `documentId`, `size`, `frame`, and `preview` are undefined. Adjustments and the tone curve use their defaults, and history counts are zero. Mutating the snapshot does not edit the document.
diff --git a/README.md b/README.md
index 60a86a5..1b1c8a7 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@ Image processing runs locally with WebGPU. Built with TypeScript and React; requ
## Features
-- Light and color adjustments, tone curves, clarity, and sharpening.
+- Light and color adjustments, tone curves, clarity, sharpening, and vignette.
- Color Mixer with eight hue, saturation, and luminance ranges.
- Crop, rotate, straighten, flip, pan, and zoom.
- Undo/redo, before/after comparison, RGB histogram, and clipping overlays.
@@ -64,6 +64,8 @@ After [browser setup](#browser-setup), run `bun run test:browser --config playwr
Results and rendered PNGs are written under `test-results/benchmarks`. JSON includes environment details, individual samples, median/p95, renderer setup, first render, completed-render latency, and isolated mixer GPU timestamps when supported. Display, readback, and image encoding run outside the measured rendering loop. Software-adapter results describe that backend only. A hardware measurement requires a browser configuration that does not force SwiftShader; record the adapter actually used.
+For vignette measurements, select `--grep "rendering vignette-"`: the editor renderer runs with intensity 0 or 80 and softness 60, with neutral color mixing. The active workload also measures the isolated vignette pass.
+
For revision comparisons, run the same benchmark files and browser configuration in both checkouts. Revisions predating the mixer can run `--grep 'rendering baseline'`. The benchmark is opt-in and excluded from the regular test suite; correctness remains covered by the GPU pixel test and editing session. See [PERFORMANCE.md](PERFORMANCE.md) for measurement scope and interpretation.
## Scripting
diff --git a/src/app/controls.ts b/src/app/controls.ts
index d06579e..e038eb0 100644
--- a/src/app/controls.ts
+++ b/src/app/controls.ts
@@ -13,6 +13,8 @@ import {
type MixerChange,
type MixerColor,
} from "@/features/color-mixer/model";
+import { setVignette } from "@/features/vignette/edits";
+import { defaultVignette } from "@/features/vignette/model";
import { setWhiteBalance } from "@/features/white-balance/edits";
import type { Preview } from "@/lib/editor/document";
import { setAdjustments, setToneCurve } from "@/lib/editor/document/edits";
@@ -20,6 +22,7 @@ import {
type Adjustments,
defaultAdjustments,
type Scene,
+ type Vignette,
} from "@/lib/editor/scene";
import type { WhiteBalance } from "@/lib/image-source";
import { defaultCurve, type ToneCurve } from "@/lib/tone-curves/curve";
@@ -47,6 +50,8 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
setColorMixer: (color: MixerColor, change: MixerChange) =>
setColorMixer(workspace.getDocument(), color, change),
resetColorMixer: () => resetColorMixer(workspace.getDocument()),
+ setVignette: (change: Partial<Vignette>) =>
+ setVignette(workspace.getDocument(), change),
editScene(change: Partial<Scene>) {
const document = workspace.getDocument();
document.edit({ ...document.scene.getState(), ...change });
@@ -73,6 +78,7 @@ export function createControls(gpu: Gpu, workspace: Workspace) {
whiteBalance: scene?.whiteBalance,
toneCurve: scene?.toneCurve ?? defaultCurve,
colorMixer: scene?.colorMixer ?? defaultMixer,
+ vignette: scene?.vignette ?? defaultVignette,
history: document?.history.status.getState() ?? {
undoCount: 0,
redoCount: 0,
diff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsx
index afa0ffd..d742c10 100644
--- a/src/app/editor/adjust/index.tsx
+++ b/src/app/editor/adjust/index.tsx
@@ -11,6 +11,7 @@ import { ColorMixerControls } from "@/features/color-mixer/controls";
import { Histogram } from "@/features/histogram";
import { createHistogram } from "@/features/histogram/histogram";
import { ToneCurves } from "@/features/tone-curves/tone-curves";
+import { VignetteControls } from "@/features/vignette/controls";
import { useEditGesture } from "@/hooks/use-edit-gesture";
import { setToneCurve } from "@/lib/editor/document/edits";
import AdjustmentControls from "./adjustment-controls";
@@ -76,6 +77,7 @@ export function AdjustPanel() {
curves={<ToneCurvesPanel histogram={histogram} />}
colorMixer={<ColorMixerControls />}
/>
+ <VignetteControls />
</div>
<EditorActions />
</div>
diff --git a/src/app/editor/renderer.ts b/src/app/editor/renderer.ts
index c8a84d6..4fa2d38 100644
--- a/src/app/editor/renderer.ts
+++ b/src/app/editor/renderer.ts
@@ -1,9 +1,25 @@
-import type { Gpu } from "vgpu";
+import type { Gpu, Target } from "vgpu";
import { createColorMixer } from "@/features/color-mixer/pass";
-import { createRenderer } from "@/lib/editor/renderer";
+import { createVignette } from "@/features/vignette/pass";
+import { createRenderer, type SceneEffect } from "@/lib/editor/renderer";
import type { ImageSource } from "@/lib/image-source";
+function createEffects(gpu: Gpu, source: Target): SceneEffect {
+ const mixer = createColorMixer(gpu, source);
+ const vignette = createVignette(gpu, source);
+ return {
+ render(frame, input, scene) {
+ const colored = mixer.render(frame, input, scene);
+ return vignette.render(frame, colored, scene);
+ },
+ dispose() {
+ mixer.dispose();
+ vignette.dispose();
+ },
+ };
+}
+
/** The same feature composition powers the editing preview and export. */
export function createEditorRenderer(gpu: Gpu, source: ImageSource) {
- return createRenderer(gpu, source, createColorMixer);
+ return createRenderer(gpu, source, createEffects);
}
diff --git a/src/features/vignette/controls.tsx b/src/features/vignette/controls.tsx
new file mode 100644
index 0000000..dc92ead
--- /dev/null
+++ b/src/features/vignette/controls.tsx
@@ -0,0 +1,32 @@
+import { useDocument, useScene } from "@/components/editor/session";
+import { Collapsible } from "@/components/ui/collapsible";
+import { Slider } from "@/components/ui/slider";
+import { setVignette } from "./edits";
+import { defaultVignette } from "./model";
+
+export function VignetteControls() {
+ const document = useDocument();
+ const vignette = useScene((scene) => scene.vignette ?? defaultVignette);
+ return (
+ <Collapsible title="Vignette">
+ <div className="flex flex-col gap-2">
+ <Slider
+ label="Intensity"
+ value={vignette.intensity}
+ onChange={(intensity) => setVignette(document, { intensity })}
+ min={0}
+ max={100}
+ defaultValue={defaultVignette.intensity}
+ />
+ <Slider
+ label="Softness"
+ value={vignette.softness}
+ onChange={(softness) => setVignette(document, { softness })}
+ min={0}
+ max={100}
+ defaultValue={defaultVignette.softness}
+ />
+ </div>
+ </Collapsible>
+ );
+}
diff --git a/src/features/vignette/edits.ts b/src/features/vignette/edits.ts
new file mode 100644
index 0000000..b0fc4c1
--- /dev/null
+++ b/src/features/vignette/edits.ts
@@ -0,0 +1,30 @@
+import type { EditorDocument } from "@/lib/editor/document";
+import type { Vignette } from "@/lib/editor/scene";
+import { defaultVignette } from "./model";
+
+export function setVignette(
+ document: EditorDocument,
+ change: Partial<Vignette>,
+) {
+ for (const [name, value] of Object.entries(change)) {
+ if (
+ (name !== "intensity" && name !== "softness") ||
+ typeof value !== "number" ||
+ !Number.isFinite(value) ||
+ value < 0 ||
+ value > 100
+ ) {
+ throw new Error(`Invalid vignette adjustment: ${name}.`);
+ }
+ }
+ const scene = document.scene.getState();
+ const current = scene.vignette ?? defaultVignette;
+ const next = { ...current, ...change };
+ if (
+ next.intensity === current.intensity &&
+ next.softness === current.softness
+ ) {
+ return;
+ }
+ document.edit({ ...scene, vignette: next });
+}
diff --git a/src/features/vignette/model.ts b/src/features/vignette/model.ts
new file mode 100644
index 0000000..841d4c0
--- /dev/null
+++ b/src/features/vignette/model.ts
@@ -0,0 +1,6 @@
+import type { Vignette } from "@/lib/editor/scene";
+
+export const defaultVignette: Readonly<Vignette> = {
+ intensity: 0,
+ softness: 50,
+};
diff --git a/src/features/vignette/pass.ts b/src/features/vignette/pass.ts
new file mode 100644
index 0000000..bda44c5
--- /dev/null
+++ b/src/features/vignette/pass.ts
@@ -0,0 +1,22 @@
+import { effect, type Gpu, type Target, target } from "vgpu";
+import type { SceneEffect } from "@/lib/editor/renderer";
+import shader from "./vignette.wgsl";
+
+export function createVignette(gpu: Gpu, source: Target): SceneEffect {
+ const apply = effect(gpu, shader);
+ let output: Target | undefined;
+ return {
+ render(frame, input, scene) {
+ const vignette = scene.vignette;
+ if (!vignette || vignette.intensity === 0) {
+ return input;
+ }
+ output ??= target(gpu, { size: source.size, format: source.format });
+ frame.pass(output, apply.set({ source: input.color, params: vignette }));
+ return output;
+ },
+ dispose() {
+ output?.color.dispose();
+ },
+ };
+}
diff --git a/src/features/vignette/vignette.wgsl b/src/features/vignette/vignette.wgsl
new file mode 100644
index 0000000..673d230
--- /dev/null
+++ b/src/features/vignette/vignette.wgsl
@@ -0,0 +1,17 @@
+struct Params {
+ intensity: f32,
+ softness: f32,
+}
+
+@group(0) @binding(0) var source: texture_2d<f32>;
+@group(0) @binding(1) var<uniform> params: Params;
+
+@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
+ let input = textureLoad(source, vec2i(position.xy), 0);
+ // Source-relative elliptical distance: zero at the image center, one at its corners.
+ let offset = position.xy / vec2f(textureDimensions(source)) - 0.5;
+ let radius = length(offset) * sqrt(2.0);
+ let start = 0.75 * (1.0 - params.softness / 100.0);
+ let gain = 1.0 - params.intensity / 100.0 * smoothstep(start, 1.0, radius);
+ return vec4f(input.rgb * gain, input.a);
+}
diff --git a/src/lib/editor/document/index.ts b/src/lib/editor/document/index.ts
index 3a6dedb..343e273 100644
--- a/src/lib/editor/document/index.ts
+++ b/src/lib/editor/document/index.ts
@@ -18,6 +18,7 @@ function equal(a: Scene, b: Scene) {
shallow(frameValues(a.frame), frameValues(b.frame)) &&
shallow(a.adjustments, b.adjustments) &&
shallow(a.whiteBalance, b.whiteBalance) &&
+ shallow(a.vignette, b.vignette) &&
shallow(a.colorMixer?.hue, b.colorMixer?.hue) &&
shallow(a.colorMixer?.saturation, b.colorMixer?.saturation) &&
shallow(a.colorMixer?.luminance, b.colorMixer?.luminance) &&
diff --git a/src/lib/editor/scene.ts b/src/lib/editor/scene.ts
index 7da65fd..1312eda 100644
--- a/src/lib/editor/scene.ts
+++ b/src/lib/editor/scene.ts
@@ -53,6 +53,12 @@ export type ColorMixer = {
readonly luminance: readonly number[];
};
+/** Source-centered darkening in 0..100 UI units. */
+export type Vignette = {
+ readonly intensity: number;
+ readonly softness: number;
+};
+
/** Serializable document content. Image bytes and GPU resources live elsewhere. */
export type Scene = {
readonly frame: ImageFrame;
@@ -61,4 +67,5 @@ export type Scene = {
readonly adjustments: Readonly<Adjustments>;
readonly toneCurve: ToneCurve;
readonly colorMixer?: ColorMixer;
+ readonly vignette?: Vignette;
};
diff --git a/tests/rendering-benchmark.ts b/tests/rendering-benchmark.ts
index b733de2..8b747e7 100644
--- a/tests/rendering-benchmark.ts
+++ b/tests/rendering-benchmark.ts
@@ -6,7 +6,12 @@ import { imageFrame } from "@/lib/image-frame/geometry";
import { createImageSource } from "@/lib/image-source";
import { defaultCurve } from "@/lib/tone-curves/curve";
-export type Workload = "baseline" | "neutral" | "active";
+export type Workload =
+ | "baseline"
+ | "neutral"
+ | "active"
+ | "vignette-neutral"
+ | "vignette-active";
function summarize(values: number[]) {
const sorted = values.toSorted((a, b) => a - b);
@@ -33,6 +38,9 @@ export async function benchmarkRendering(
"No WebGPU adapter. Use the project's Playwright configuration.",
);
}
+ const isVignette = workload.startsWith("vignette-");
+ const active = workload === "active" || workload === "vignette-active";
+ const passName = isVignette ? "vignette" : "color-mixer";
const timestamps = adapter.features.has("timestamp-query");
const gpu = await init({
requiredFeatures: timestamps ? ["timestamp-query"] : [],
@@ -44,13 +52,15 @@ export async function benchmarkRendering(
const clock = timestamps ? timer(gpu) : undefined;
let passMs: number | undefined;
clock?.onResults((spans) => {
- passMs = spans["color-mixer"];
+ passMs = spans[passName];
});
+ const intensity = active ? 80 : 0;
const scene: Scene = {
source: "benchmark",
frame: imageFrame(size),
adjustments: { ...defaultAdjustments, exposure: 0.25, contrast: 10 },
toneCurve: defaultCurve,
+ vignette: isVignette ? { intensity, softness: 60 } : undefined,
colorMixer:
workload === "active"
? {
@@ -70,10 +80,28 @@ export async function benchmarkRendering(
/* @vite-ignore */ path
)) as typeof import("@/features/color-mixer/pass")
).createColorMixer;
+ const vignettePath = "/src/features/vignette/pass.ts";
+ const createVignette = isVignette
+ ? (
+ (await import(
+ /* @vite-ignore */ vignettePath
+ )) as typeof import("@/features/vignette/pass")
+ ).createVignette
+ : undefined;
+ const editorPath = "/src/app/editor/renderer.ts";
+ const createEditorRenderer = isVignette
+ ? (
+ (await import(
+ /* @vite-ignore */ editorPath
+ )) as typeof import("@/app/editor/renderer")
+ ).createEditorRenderer
+ : undefined;
const setupStart = performance.now();
- const renderer = createRenderer(gpu, source, createMixer);
+ const renderer = createEditorRenderer
+ ? createEditorRenderer(gpu, source)
+ : createRenderer(gpu, source, createMixer);
const rendererSetupMs = performance.now() - setupStart;
- const mixer = createMixer?.(gpu, input);
+ const isolatedEffect = (createVignette ?? createMixer)?.(gpu, input);
async function measure(render: () => void | Promise<void>, timed: boolean) {
const encoding: number[] = [];
const completed: number[] = [];
@@ -124,23 +152,23 @@ export async function benchmarkRendering(
await gpu.settled();
const firstRenderMs = performance.now() - start;
const rendering = await measure(() => renderer.update(scene), false);
- const renderMixer = (f: Frame) => {
+ const renderEffect = (f: Frame) => {
// Instrument this owned frame only; execute the feature's actual pass unchanged.
const pass = f.pass.bind(f);
f.pass = (options, body) =>
pass(
{
...("target" in options ? options : { target: options }),
- timer: clock?.span("color-mixer"),
+ timer: clock?.span(passName),
},
body,
);
- mixer?.render(f, input, scene);
+ isolatedEffect?.render(f, input, scene);
};
- const isolated = mixer
+ const isolated = isolatedEffect
? await measure(() => {
- frame(gpu, renderMixer);
- }, workload === "active")
+ frame(gpu, renderEffect);
+ }, active)
: null;
const pixels = await renderer.outputImage().readFloats();
if (!pixels.every(Number.isFinite)) {
@@ -165,11 +193,11 @@ export async function benchmarkRendering(
firstRenderMs,
rendering,
isolated,
- outputBytes: workload === "active" ? size[0] * size[1] * 8 : 0,
+ outputBytes: active ? size[0] * size[1] * 8 : 0,
image: [...new Uint8Array(await blob.arrayBuffer())],
};
} finally {
- mixer?.dispose();
+ isolatedEffect?.dispose();
renderer.dispose();
source.dispose();
clock?.dispose();
diff --git a/tests/rendering.bench.ts b/tests/rendering.bench.ts
index 0eb3213..6e2cefd 100644
--- a/tests/rendering.bench.ts
+++ b/tests/rendering.bench.ts
@@ -4,7 +4,13 @@ import { cpus, release } from "node:os";
import { expect, test } from "./fixtures";
import type { Workload } from "./rendering-benchmark";
-for (const workload of ["baseline", "neutral", "active"] as const) {
+for (const workload of [
+ "baseline",
+ "neutral",
+ "active",
+ "vignette-neutral",
+ "vignette-active",
+] as const) {
test(`rendering ${workload}`, async ({ page, browser }, info) => {
await page.goto("/tests/gpu.html");
const result = await page.evaluate(async (workload: Workload) => {
@@ -32,7 +38,10 @@ for (const workload of ["baseline", "neutral", "active"] as const) {
...timings,
};
expect(report.rendering.completedMs.samples).toHaveLength(report.samples);
- if (workload === "active" && report.timestamps) {
+ if (
+ (workload === "active" || workload === "vignette-active") &&
+ report.timestamps
+ ) {
expect(report.isolated?.missingGpuSamples).toBe(0);
}
await writeFile(
@@ -49,7 +58,7 @@ for (const workload of ["baseline", "neutral", "active"] as const) {
workload,
firstRenderMs: report.firstRenderMs,
completedMs: report.rendering.completedMs.median,
- mixerGpuMs: report.isolated?.gpuMs?.median ?? null,
+ isolatedGpuMs: report.isolated?.gpuMs?.median ?? null,
}),
);
});
diff --git a/tests/vignette.e2e.ts b/tests/vignette.e2e.ts
new file mode 100644
index 0000000..47e4315
--- /dev/null
+++ b/tests/vignette.e2e.ts
@@ -0,0 +1,47 @@
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
+
+test("vignette darkens a white image's edges, softens, undoes and disables", async ({
+ page,
+}) => {
+ await page.goto("/");
+ await page.locator('input[type="file"]').setInputFiles({
+ name: "white.svg",
+ mimeType: "image/svg+xml",
+ buffer: Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="128" height="128" fill="white"/></svg>',
+ ),
+ });
+ const intensity = page.getByRole("textbox", {
+ name: "Intensity",
+ exact: true,
+ });
+ await expect(intensity).toHaveValue("0");
+ const exportBytes = () =>
+ page.evaluate(async () => [
+ ...new Uint8Array(
+ await (await window.openlight.exportImage()).arrayBuffer(),
+ ),
+ ]);
+ const original = await exportBytes();
+
+ await intensity.fill("80");
+ await intensity.press("Enter");
+ const vignetted = await readImage(page);
+ expect(vignetted.center).toEqual([255, 255, 255, 255]);
+ expect(vignetted.corner[0]).toBeLessThan(255);
+
+ const softness = page.getByRole("textbox", { name: "Softness", exact: true });
+ await softness.fill("100");
+ await softness.press("Enter");
+ const softer = await readImage(page);
+ expect(softer.center).toEqual(vignetted.center);
+ expect(softer.corner[0]).toBeLessThan(vignetted.corner[0]);
+
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ expect(await readImage(page)).toEqual(vignetted);
+
+ await intensity.fill("0");
+ await intensity.press("Enter");
+ expect(await exportBytes()).toEqual(original);
+});