Skip to content

Free open-source image editor for the browser

Keep the LUT in its layer and show its intensity in the panel (#67)

Rodrigo Belfiore82842e952f01
diff --git a/API.md b/API.md
index 85af622..a247316 100644
--- a/API.md
+++ b/API.md
@@ -98,9 +98,9 @@ A brush mask is a list of strokes. Each stroke has `mode` (`"paint"` or `"erase"
## LUTs
-A LUT layer grades the image below it with a 3D lookup table from an Adobe or Resolve `.cube` file. `openFile` with a `.cube` file adds one on top of the stack, named after the file's `TITLE` or, without one, the file; the Add menu asks for a file and places the layer as it places other effects, and the layer's panel replaces its file. A replacement keeps the layer's name unless it still reads the previous LUT's name. The layer's opacity sets its strength. `addLayer` cannot create a LUT layer, since it needs a file.
+A LUT layer grades the image below it with a 3D lookup table, stored in the layer as `lut: { size, domain: [min, max], table }`: `table` holds `size`³ RGB triplets, red varying fastest, then green, then blue, for inputs spread evenly across the domain. The layer's opacity sets its strength.
-The file needs `LUT_3D_SIZE`, a whole number from 2 to 65, before its rows: `LUT_3D_SIZE`³ lines of three numbers, red varying fastest, then green, then blue. `TITLE`, `DOMAIN_MIN` and `DOMAIN_MAX` (default 0 and 1), or Resolve's `LUT_3D_INPUT_RANGE`, are read; comments, blank lines, and other keywords are skipped. 1D LUTs are rejected, and so is a file with too few or too many rows, naming the line where one is wrong.
+`openFile` with an Adobe or Resolve `.cube` file adds one where the Add menu places effects, named after the file's `TITLE` or, without one, the file; the Add menu's LUT entry asks for such a file. The file needs `LUT_3D_SIZE`, a whole number from 2 to 65, before its rows. `TITLE`, `DOMAIN_MIN` and `DOMAIN_MAX` (default 0 and 1), or Resolve's `LUT_3D_INPUT_RANGE`, are read; comments, blank lines, and other keywords are skipped. 1D LUTs are rejected, and so is a file with too few or too many rows, naming the line where one is wrong.
Creative LUTs expect and return display-referred, sRGB-encoded color. The layer converts the working color as display does, into sRGB clipped to its gamut with hue and luminance kept, so headroom above white clips at the LUT; the color, clamped to the LUT's domain, is interpolated tetrahedrally between its entries, and the result, clamped to 0–1, converts back to the working space. The image layer's adjustments still apply after it, on the composite.
@@ -155,7 +155,7 @@ The image renders at the document dimensions and downsamples to `longEdge` with
## Scene files
-`exportScene()` returns `Promise<File>`: the document as an `.openlight` file named after its source image, which **Save scene** in the Export panel downloads. It is a ZIP archive holding the original bytes of the source image and of each LUT the scene uses at `sources/<id>`, and a deflated `scene.json`:
+`exportScene()` returns `Promise<File>`: the document as an `.openlight` file named after its source image, which **Save scene** in the Export panel downloads. It is a ZIP archive holding the source file's original bytes at `sources/<id>` and a deflated `scene.json`:
```json
{
@@ -166,7 +166,7 @@ The image renders at the document dimensions and downsamples to `longEdge` with
}
```
-`scene` is the `getState()` scene; the image layer's `source` and each LUT layer's `lut` name entries in `sources`. Opening the file with `loadScene`, `openFile`, a drop, or the file picker decodes the stored source again and restores the frame and every layer as a new document with empty history. Preview settings and history are not saved.
+`scene` is the `getState()` scene; each image layer's `source` names an entry in `sources`. Opening the file with `loadScene`, `openFile`, a drop, or the file picker decodes the stored source again and restores the frame and every layer as a new document with empty history. Preview settings and history are not saved.
Opening validates every value as the matching command does, and a file that fails leaves the workspace in its error state with a message naming the first invalid field. Fields OpenLight does not know are dropped. A parameter missing from `adjustments`, `details`, `vignette`, `grain`, `fill`, or `colorMixer` takes its default, so older files still open when a group gains a parameter; a RAW image without a white balance uses its As Shot value. `version` increases only when older files can no longer open as written; a newer version is rejected.
@@ -174,7 +174,7 @@ Opening validates every value as the matching command does, and a file that fail
Once a document has an edit, OpenLight keeps it as the draft in the browser's IndexedDB, so closing the tab loses nothing. A save follows 1.5 s after the last scene change and flushes when the tab is hidden or the page unloads; saves run one at a time and never render. Opening an image or scene without editing it keeps the previous draft. Only the latest document is kept.
-A draft stores the same `scene.json` object a [scene file](#scene-files) holds, in a record with its own `version` and the document's name, while each source file, the image and any LUTs, sits in a separate store under its ID. A save keeps source files already stored under their ID and deletes unreferenced ones in the same transaction, so edits never rewrite the photo.
+A draft stores the same `scene.json` object a [scene file](#scene-files) holds, in a record with its own `version` and the document's name, while each source file sits in a separate store under its source ID. A save keeps source files already stored under their ID and deletes unreferenced ones in the same transaction, so edits never rewrite the photo.
On a fresh load the start screen shows a notice in the viewport's corner with **Recover** and **Forget**. `recoverDraft()` opens the draft through the same validation as a scene file, restoring each source under its original ID, with empty history; a newer draft `version` is rejected rather than dropped, and a parameter added to a group since takes its default. `discardDraft()` removes it. Both return `Promise<void>`. When IndexedDB is unavailable or fails, a dismissible notice suggests saving a scene file, and editing continues.
@@ -216,7 +216,7 @@ editor.run({
In browsers with [WebMCP](https://webmachinelearning.github.io/webmcp/), OpenLight registers every command as a tool on `document.modelContext`, so a browser agent can edit the open photo. Chrome offers WebMCP from version 149 through an origin trial or `chrome://flags/#enable-webmcp-testing`. A tool takes its command's fields, with a JSON Schema generated from the same models, and returns `{ layerId }` or `"Done."`; errors come back as text, so the agent can correct its input.
-A read-only `get-state` tool returns the file, source size, frame, layers, comparison, and history, counting brush strokes and healing patches rather than listing them.
+A read-only `get-state` tool returns the file, source size, frame, layers, comparison, and history, counting brush strokes, healing patches, and LUT table values rather than listing them.
WebMCP passes only JSON, so no tool takes or returns a file. `open-image` takes an http(s) `url` instead and opens it like `loadUrl`, in place of the open photo; it returns the new state like `get-state`, or why the image could not open. An agent opens a local file, such as an image attached to its chat, by serving it over HTTP with CORS and passing its URL. From a public origin such as openlight.app, Chrome's [Local Network Access](https://developer.chrome.com/blog/local-network-access) asks the user before the page reaches a local address; an automated browser can grant the `local-network-access` permission instead. When the request itself fails, the error names these causes, since the browser does not say which one it was.
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 454dda1..4d68d40 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -9,7 +9,7 @@ Where the code lives and the rules that keep it in place. Keep this file true: w
| `src/main.tsx` | Mounts the GPU provider and the app. |
| `app/index.tsx` | The app: workspace, file drop, draft notice. |
| `app/workspace` | The open document, its replacement, and loading state. A replacement loads beside the open document and takes its place only once it opens; a failure leaves the open document in place. |
-| `app/loaders` | Image, scene file, Camera Raw XMP, and `.cube` LUT loaders. |
+| `app/loaders` | Image, scene file, Camera Raw XMP, and `.cube` LUT loaders. A loader reads one file format and opens a document or edits the open one through the same edits the UI uses. |
| `app/draft` | The draft autosaved in the browser. |
| `app/controls.ts` | `window.openlight`, documented in [API.md](API.md). |
| `app/commands.ts` | The commands: serializable, validated edits that `run`, WebMCP, and other callers share; see [API.md](API.md#commands). |
@@ -28,7 +28,7 @@ Where the code lives and the rules that keep it in place. Keep this file true: w
| `components/editor` | Editor primitives: layout, panel, dock, parameters, viewport, document and renderer contexts, brush input. |
| `components/ui` | What [`@roprgm/ui`](https://ui.roprgm.com) lacks; see [DESIGN.md](DESIGN.md). |
| `core/document` | Scene contract, layer tree, history, resources. |
-| `core/image` | Image sources, decoding, geometry, color, and the lookup-table type LUTs read into. |
+| `core/image` | Image sources, decoding, geometry, color. |
| `core/renderer` | Render nodes, graph execution, masks, proxy, transform, display. |
| `features/<name>` | One capability: usually `model.ts` (parameters, defaults), `edits.ts`, `pass.ts` with its `.wgsl`, and `controls.tsx`. |
| `lib` | Utilities independent of OpenLight. |
@@ -56,7 +56,7 @@ Dependencies point downward. Features do not import each other; `app/` connects
## Engine and React
- Document edits and rendering run without React, a mounted UI, or an implicit active document: pass workspace, document, and GPU explicitly. Feature processing imports without its panel.
-- Each document owns a vanilla Zustand scene store, history, and resources: its image sources and LUT tables with their files. Scenes hold immutable, serializable content and the IDs of those resources; files, tables, and GPU resources stay outside history, and a resource goes once no state in history uses it.
+- Each document owns a vanilla Zustand scene store, history, and image resources. Scenes hold immutable, serializable content and image-source IDs; files and GPU resources stay outside history.
- UI controls, `window.openlight`, and commands call the same edits. A slider or curve gesture is one edit; cancelling restores the previous scene. Preview settings and navigation stay outside history.
- The engine owns GPU resources, rendering, and derived data such as histogram bins; frame data stays out of React state. Every resource owner disposes what it creates.
@@ -72,7 +72,7 @@ Dependencies point downward. Features do not import each other; `app/` connects
- Use `vgpu` for GPU work and `vgpu-react` for bindings. Create pipelines once per engine and reuse them. Keep `.wgsl` beside its owner.
- The working space is linear Rec.2020 in `rgba16float`. Decoders convert into it and display converts out; passes preserve format and primaries unless they explicitly convert.
- A LUT layer converts explicitly: its table expects display-referred sRGB, so it receives the working color as the display shows it, headroom above white clipped, and its output returns to linear Rec.2020.
-- A node's storage arrays upload when the array changes; one passed again, such as a LUT's table, keeps its buffer, which the graph owns and releases with the layer.
+- A node's storage arrays upload when the array changes; passing the same array, such as a LUT's table, keeps its buffer.
- Layers process in stack order; the image layer's adjustments and tone curve run last, on the composite.
- Preserve HDR headroom through exposure, curves, and vibrance. Exposure clips negatives and applies one luminance gain to all channels.
- The adjustment shader's parameters use UI units; its fitted constants are calibration data.
diff --git a/CONTEXT.md b/CONTEXT.md
index 83e07d5..149c1e3 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -5,15 +5,15 @@ OpenLight edits documents containing image content and adjustments.
| Term | Meaning |
| --- | --- |
| **Document** | An independent editing session with its own canvas, history, and resources. Opening an image creates a document containing that image. |
-| **Scene** | The document's serializable content: canvas geometry, references to image sources and LUTs, and adjustments. Files and GPU resources live outside it. |
+| **Scene** | The document's serializable content: canvas geometry, image-source references, and adjustments. Files and GPU resources live outside it. |
| **Layer** | A source, effect, or mask in the composition. Image layers own basic adjustments; effects process the image below; masks scope their basic adjustments and child effects. Linear, radial, and brush child masks add or subtract coverage. Layers compose render nodes without owning textures. |
| **Stroke** | One brush drag: paint or erase, size, feather, flow, and points with pressure in source pixels. Strokes are content; the renderer rasterizes them into a cached coverage texture. A Healing patch stores a hard stroke and feathers its accumulated shape separately. |
| **Healing patch** | One painted, non-destructive repair in a Healing layer. It copies a nearby donor, found automatically or set by hand, with a bounded boundary color correction. Patches replay in order and each sees the result of the preceding patches. Size belongs to the recorded hard stroke; feather and opacity remain editable on its accumulated shape. |
| **Image source** | An image used as input to the document's composition. It is content within a document. |
-| **LUT** | A 3D color lookup table read from a `.cube` file, such as a creative grade. A LUT layer applies one to the image below it, at the layer's opacity. Like an image source, its file is content within the document, which the scene references by ID. |
+| **LUT** | A 3D color lookup table, such as a creative grade, read from a `.cube` file. A LUT layer holds one and applies it to the image below, at the layer's opacity. |
| **Edit** | One reversible content change. A continuous slider or curve drag is one edit, as is importing a set of adjustments. |
-| **Scene file** | A document saved as an `.openlight` archive: its scene and the original files it uses, the image and any LUTs. Opening it creates a document that continues editing; history and preview settings are not saved. |
-| **Draft** | The latest edited document, kept in the browser as a scene with its files so it survives closing the tab. The start screen offers to recover or forget it; recovering opens a new document with empty history. |
+| **Scene file** | A document saved as an `.openlight` archive: its scene and the original source files. Opening it creates a document that continues editing; history and preview settings are not saved. |
+| **Draft** | The latest edited document, kept in the browser as a scene with its source files so it survives closing the tab. The start screen offers to recover or forget it; recovering opens a new document with empty history. |
| **Workspace** | The open-document session. It currently holds at most one document, replaced when another image or scene file is opened. |
| **Tool** | What a drag on the canvas does: Brush paints, Healing repairs, and Linear and Radial gradient draw masks and edit the selected gradient's guides. Adjust leaves the canvas to pan and zoom. Crop and Export bring their own view. Switching tools never changes the sidebar; Brush and Healing create their layer on entry and remove it again if it leaves untouched. A selected mask is *active*; it is *edited* only while a shape tool is on. |
diff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsx
index a172a03..2fea820 100644
--- a/src/app/editor/adjust/index.tsx
+++ b/src/app/editor/adjust/index.tsx
@@ -3,7 +3,6 @@ import { Slider } from "@roprgm/ui/slider";
import { type ReactNode, useCallback, useState } from "react";
import { useStore } from "zustand";
import { effectKinds } from "@/app/editor/layers";
-import { useReportFailure } from "@/app/editor/open";
import { DockChips, DockControls } from "@/components/editor/dock";
import { PanelBody, PanelHeader } from "@/components/editor/panel";
import type { Parameter } from "@/components/editor/parameter";
@@ -38,8 +37,9 @@ import { FillControls } from "@/features/fill/controls";
import { GrainControls, grainParameters } from "@/features/grain/controls";
import { HealControls } from "@/features/heal/controls";
import { Histogram } from "@/features/histogram";
+import { setLayer } from "@/features/layers/edits";
import { OverlayToggle } from "@/features/layers/overlay-toggle";
-import { LutControls } from "@/features/lut/controls";
+import { LutCurves } from "@/features/lut/curves";
import { defaultCurve } from "@/features/tone-curves/curve";
import { setToneCurve } from "@/features/tone-curves/edits";
import { ToneCurves } from "@/features/tone-curves/tone-curves";
@@ -117,12 +117,20 @@ function exposureParameter(
};
}
-/** A replacement file that can't be read shows beside the document, as a failed open does. */
-function LayerLut({ layer }: { layer: Kind<"lut"> }) {
- const reportFailure = useReportFailure();
- return (
- <LutControls id={layer.id} lut={layer.lut} onFailure={reportFailure} />
- );
+/** A LUT's strength is its layer's opacity. */
+function intensityParameter(
+ document: EditorDocument,
+ layer: Kind<"lut">,
+): Parameter {
+ return {
+ id: "intensity",
+ label: "Intensity",
+ value: layer.opacity * 100,
+ min: 0,
+ max: 100,
+ defaultValue: 100,
+ onChange: (value) => setLayer(document, layer.id, { opacity: value / 100 }),
+ };
}
function SelectedControls({ layer }: { layer: Layer }) {
@@ -152,8 +160,15 @@ function SelectedControls({ layer }: { layer: Layer }) {
return <GrainControls id={layer.id} grain={layer.grain} />;
case "fill":
return <FillControls id={layer.id} fill={layer.fill} />;
- case "lut":
- return <LayerLut layer={layer} />;
+ case "lut": {
+ const { id, ...intensity } = intensityParameter(document, layer);
+ return (
+ <section className="flex flex-col gap-3.5 p-3.5">
+ <Slider {...intensity} />
+ <LutCurves lut={layer.lut} opacity={layer.opacity} />
+ </section>
+ );
+ }
case "heal":
return <HealControls id={layer.id} patches={layer.patches} />;
case "exposure": {
@@ -375,9 +390,10 @@ function SelectedDials({
);
case "lut":
return (
- <DockControls header={<DockTitle layer={layer} />}>
- <LayerLut layer={layer} />
- </DockControls>
+ <DockControls
+ header={<DockTitle layer={layer} />}
+ parameters={[intensityParameter(document, layer)]}
+ />
);
case "heal":
return (
diff --git a/src/app/editor/export/export-image.ts b/src/app/editor/export/export-image.ts
index 236225f..6e0955f 100644
--- a/src/app/editor/export/export-image.ts
+++ b/src/app/editor/export/export-image.ts
@@ -82,7 +82,7 @@ export async function exportImage(
) {
const scene = document.scene.getState();
const source = document.resources.get(scene.layers[0].source);
- const renderer = createEditorRenderer(gpu, source, document.resources.getLut);
+ const renderer = createEditorRenderer(gpu, source);
try {
await renderer.update(scene);
// The renderer retains the source until encoding finishes.
diff --git a/src/app/editor/index.tsx b/src/app/editor/index.tsx
index d113f83..9afc650 100644
--- a/src/app/editor/index.tsx
+++ b/src/app/editor/index.tsx
@@ -33,7 +33,7 @@ import { ImageHistogram } from "./histogram";
import { HistoryControls } from "./history";
import { createMask } from "./layers";
import { MaskOverlaySync } from "./mask-overlay";
-import { FailureContext, OpenButton, OpenStatus } from "./open";
+import { OpenButton, OpenContext, OpenStatus } from "./open";
import { createEditorRenderer } from "./renderer";
import { EditorSidebar } from "./sidebar";
import { ToolRail } from "./tool-rail";
@@ -164,12 +164,10 @@ type ReadyState = Extract<
function DocumentEditor({
state,
onOpen,
- onFailure,
onDismissFailure,
}: {
state: ReadyState;
onOpen: (files: File[]) => void;
- onFailure: (file: string, error: unknown) => void;
onDismissFailure: () => void;
}) {
return (
@@ -189,13 +187,13 @@ function DocumentEditor({
<ComparisonControl />
<ExportButton />
</EditorHeader>
- <FailureContext value={onFailure}>
+ <OpenContext value={onOpen}>
<DockProvider>
<EditorFrame rail={<ToolRail />} tabs={<DockTabs />}>
<ToolView />
</EditorFrame>
</DockProvider>
- </FailureContext>
+ </OpenContext>
<OpenStatus
opening={state.opening}
failure={state.failure}
@@ -211,15 +209,12 @@ function DocumentEditor({
type EditorProps = {
state: ReturnType<Workspace["state"]["getState"]>;
onOpen: (files: File[]) => void;
- /** A file the editor reads into the open document, such as a LUT, failed. */
- onFailure: (file: string, error: unknown) => void;
onDismissFailure: () => void;
draft?: Recovery;
};
function EditorContent({
state,
onOpen,
- onFailure,
onDismissFailure,
draft,
}: EditorProps) {
@@ -232,7 +227,6 @@ function EditorContent({
<DocumentEditor
state={state}
onOpen={onOpen}
- onFailure={onFailure}
onDismissFailure={onDismissFailure}
/>
</RendererProvider>
diff --git a/src/app/editor/layers.ts b/src/app/editor/layers.ts
index 19b008c..1ba759a 100644
--- a/src/app/editor/layers.ts
+++ b/src/app/editor/layers.ts
@@ -5,24 +5,25 @@ import { GrainIcon } from "@/components/icons/grain";
import { HealIcon } from "@/components/icons/heal";
import { LutIcon } from "@/components/icons/lut";
import { VignetteIcon } from "@/components/icons/vignette";
-import type {
- EditorDocument,
- EffectLayer,
- ImageLayer,
- Layer,
- Mask,
- MaskLayer,
- ProcessingLayer,
+import {
+ type EditorDocument,
+ type EffectLayer,
+ findLayer,
+ type ImageLayer,
+ type Layer,
+ type LookupTable,
+ type Mask,
+ type MaskLayer,
+ type ProcessingLayer,
} from "@/core/document";
import type { WhiteBalance } from "@/core/image";
-import type { LookupTable } from "@/core/image/lut";
import { defaultAdjustments } from "@/features/adjustments/model";
import { defaultMixer, isNeutral } from "@/features/color-mixer/model";
import { defaultDetails } from "@/features/details/model";
import { defaultFill } from "@/features/fill/model";
import { defaultGrain } from "@/features/grain/model";
import type { EffectKind } from "@/features/layers/controls";
-import { addLayer, type LayerPlacement } from "@/features/layers/edits";
+import type { LayerPlacement } from "@/features/layers/edits";
import { defaultCurve } from "@/features/tone-curves/curve";
import { defaultVignette } from "@/features/vignette/model";
@@ -91,23 +92,21 @@ export function createLayer(kind: DefaultEffect): EffectLayer {
}
}
-/** Keeps a table read from `file` with the document and adds a layer named after it; returns the layer's ID. */
-export function addLut(
- document: EditorDocument,
- file: File,
- table: LookupTable,
- placement?: LayerPlacement,
-) {
- // An open group commits first: releasing it would drop a table no layer uses yet.
- document.history.commit();
- const lut = document.resources.addLut(file, table);
- const layer: ProcessingLayer = {
- ...baseLayer(),
- kind: "lut",
- name: table.name,
- lut,
- };
- return addLayer(document, layer, placement);
+export function createLutLayer(
+ name: string,
+ lut: LookupTable,
+): Extract<EffectLayer, { kind: "lut" }> {
+ return { ...baseLayer(), kind: "lut", name, lut };
+}
+
+/** Where a new effect goes: inside a selected root mask, or above the selection. */
+export function newLayerPlacement(document: EditorDocument): LayerPlacement {
+ const scene = document.scene.getState();
+ const selected = document.selection.getState().layerId;
+ const layer = findLayer(scene.layers, selected);
+ return layer?.kind === "mask" && scene.layers.includes(layer)
+ ? { inside: selected }
+ : { above: selected };
}
const maskNames: Record<Mask["kind"], string> = {
diff --git a/src/app/editor/open.tsx b/src/app/editor/open.tsx
index fa6cfa2..19290fb 100644
--- a/src/app/editor/open.tsx
+++ b/src/app/editor/open.tsx
@@ -12,29 +12,28 @@ import { useShortcuts } from "@/hooks/use-shortcuts";
type OpenProps = { onOpen: (files: File[]) => void };
-type ReportFailure = (file: string, error: unknown) => void;
+/** Opens files anywhere in the editor through the loaders, as a drop does. */
+export const OpenContext = createContext<OpenProps["onOpen"] | null>(null);
-/** Where the editor reports a file it read itself but couldn't use, such as a LUT, to show like a failed open. */
-export const FailureContext = createContext<ReportFailure | null>(null);
-
-export function useReportFailure() {
- const report = useContext(FailureContext);
- if (!report) {
- throw new Error("useReportFailure requires FailureContext.");
+export function useOpen() {
+ const open = useContext(OpenContext);
+ if (!open) {
+ throw new Error("useOpen requires OpenContext.");
}
- return report;
+ return open;
}
-/** The hidden picker for images and scenes; clearing it after each pick lets the same file open again. */
-function FileInput({
+/** A hidden file picker, images and scenes unless `accept` says otherwise; clearing it after each pick lets the same file open again. */
+export function FileInput({
ref,
onOpen,
-}: OpenProps & { ref: RefObject<HTMLInputElement | null> }) {
+ accept: types = `${accept},${sceneExtension}`,
+}: OpenProps & { ref: RefObject<HTMLInputElement | null>; accept?: string }) {
return (
<input
ref={ref}
type="file"
- accept={`${accept},${sceneExtension}`}
+ accept={types}
multiple
hidden
onChange={(event) => {
diff --git a/src/app/editor/renderer.ts b/src/app/editor/renderer.ts
index e46ab7a..fcb6640 100644
--- a/src/app/editor/renderer.ts
+++ b/src/app/editor/renderer.ts
@@ -1,7 +1,6 @@
import type { Gpu, Timer } from "vgpu";
import { maskModifiers, type ProcessingLayer } from "@/core/document";
import type { ImageSource } from "@/core/image";
-import type { LookupTable } from "@/core/image/lut";
import {
type Composition,
createRenderer,
@@ -28,18 +27,10 @@ type Branch = {
input?: RenderImage;
};
-/** Finds the table a LUT layer names; a document's resources hold them. */
-type Luts = (id: string) => LookupTable;
-
-function noLuts(): never {
- throw Error("LUT is unavailable.");
-}
-
function composeLayer(
below: RenderImage,
layer: ProcessingLayer,
composition: Composition,
- luts: Luts,
): Branch {
const name = `layer/${layer.id}`;
composition.retain(name);
@@ -96,7 +87,7 @@ function composeLayer(
edited = pipeline(below, [fill(layer.fill, `${name}/fill`)]);
break;
case "lut":
- edited = pipeline(below, [lut(luts(layer.lut), `${name}/lut`)]);
+ edited = pipeline(below, [lut(layer.lut, `${name}/lut`)]);
break;
case "heal": {
const result = heal(below, layer.patches, name, composition);
@@ -110,7 +101,7 @@ function composeLayer(
layer.kind === "mask"
? layer.children.filter((child) => child.kind !== "mask")
: layer.children;
- const children = composeLayers(edited, effects, composition, luts);
+ const children = composeLayers(edited, effects, composition);
const image = mixAdjustment(
name,
below,
@@ -127,12 +118,11 @@ function composeLayers(
below: RenderImage,
layers: readonly ProcessingLayer[],
composition: Composition,
- luts: Luts,
): Branch {
let image = below;
let input: RenderImage | undefined;
for (const layer of layers) {
- const branch = composeLayer(image, layer, composition, luts);
+ const branch = composeLayer(image, layer, composition);
image = branch.image;
input ??= branch.input;
}
@@ -147,7 +137,6 @@ function composeLayers(
export function createEditorRenderer(
gpu: Gpu,
source: ImageSource,
- luts: Luts = noLuts,
timer?: Timer,
) {
return createRenderer(
@@ -157,18 +146,8 @@ export function createEditorRenderer(
const [sourceLayer, ...layers] = scene.layers;
const name = `layer/${sourceLayer.id}`;
composition.retain(name);
- const children = composeLayers(
- image,
- sourceLayer.children,
- composition,
- luts,
- );
- const composite = composeLayers(
- children.image,
- layers,
- composition,
- luts,
- );
+ const children = composeLayers(image, sourceLayer.children, composition);
+ const composite = composeLayers(children.image, layers, composition);
const adjusted = pipeline(composite.image, [
adjustments(sourceLayer.adjustments, name),
]);
diff --git a/src/app/editor/sidebar.tsx b/src/app/editor/sidebar.tsx
index 0babcce..d656972 100644
--- a/src/app/editor/sidebar.tsx
+++ b/src/app/editor/sidebar.tsx
@@ -1,47 +1,30 @@
import { useRef } from "react";
import { useDocument } from "@/components/editor/session";
import type { EffectLayer } from "@/core/document";
-import { findLayer } from "@/core/document";
import { LayersControls, LayersSection } from "@/features/layers/controls";
-import { addLayer, type LayerPlacement } from "@/features/layers/edits";
-import { readCubeFile } from "@/features/lut/cube";
-import { LutInput } from "@/features/lut/input";
+import { addLayer } from "@/features/layers/edits";
+import { cubeExtension } from "@/features/lut/cube";
import { AdjustPanel } from "./adjust";
import { ImageHistogram } from "./histogram";
-import { addLut, createLayer, effectKinds } from "./layers";
-import { useReportFailure } from "./open";
+import { createLayer, effectKinds, newLayerPlacement } from "./layers";
+import { FileInput, useOpen } from "./open";
-/** The layer stack with the effects the app offers; a new effect goes inside a selected root mask or above the selection. */
+/** The layer stack with the effects the app offers; a LUT comes from a `.cube` file, opened as a drop would be. */
export function EditorLayers({ fill }: { fill?: boolean }) {
const document = useDocument();
- const reportFailure = useReportFailure();
- const lutInput = useRef<HTMLInputElement>(null);
- function placement(): LayerPlacement {
- const scene = document.scene.getState();
- const selected = document.selection.getState().layerId;
- const layer = findLayer(scene.layers, selected);
- return layer?.kind === "mask" && scene.layers.includes(layer)
- ? { inside: selected }
- : { above: selected };
- }
+ const open = useOpen();
+ const cube = useRef<HTMLInputElement>(null);
function add(kind: EffectLayer["kind"]) {
if (kind === "lut") {
- lutInput.current?.click();
+ cube.current?.click();
return;
}
- addLayer(document, createLayer(kind), placement());
- }
- async function addLutFile(file: File) {
- try {
- addLut(document, file, await readCubeFile(file), placement());
- } catch (error) {
- reportFailure(file.name, error);
- }
+ addLayer(document, createLayer(kind), newLayerPlacement(document));
}
return (
<>
<LayersControls effects={effectKinds} onAdd={add} fill={fill} />
- <LutInput ref={lutInput} onChoose={addLutFile} />
+ <FileInput ref={cube} accept={cubeExtension} onOpen={open} />
</>
);
}
diff --git a/src/app/index.tsx b/src/app/index.tsx
index 3f38aa6..31f5f43 100644
--- a/src/app/index.tsx
+++ b/src/app/index.tsx
@@ -24,7 +24,6 @@ export function App() {
<Editor
state={state}
onOpen={controls.openFiles}
- onFailure={workspace.reportFailure}
onDismissFailure={workspace.dismissFailure}
draft={recovery}
/>
diff --git a/src/app/loaders/lut.ts b/src/app/loaders/lut.ts
index 96ced16..c44df17 100644
--- a/src/app/loaders/lut.ts
+++ b/src/app/loaders/lut.ts
@@ -1,9 +1,10 @@
-import { addLut } from "@/app/editor/layers";
+import { createLutLayer, newLayerPlacement } from "@/app/editor/layers";
import type { Workspace } from "@/app/workspace";
+import { addLayer } from "@/features/layers/edits";
import { isCubeFile, readCubeFile } from "@/features/lut/cube";
import type { FileLoader } from "./registry";
-/** A `.cube` file adds a LUT layer on top of the stack; one that can't be read shows beside the document. */
+/** A `.cube` file adds a LUT layer where the Add menu places effects; one that can't be read shows beside the document. */
export function createLutLoader(workspace: Workspace): FileLoader {
return {
kind: "settings",
@@ -11,9 +12,13 @@ export function createLutLoader(workspace: Workspace): FileLoader {
async load(file) {
const document = workspace.getDocument();
try {
- const table = await readCubeFile(file);
+ const { name, lut } = await readCubeFile(file);
if (workspace.state.getState().document === document) {
- addLut(document, file, table);
+ addLayer(
+ document,
+ createLutLayer(name, lut),
+ newLayerPlacement(document),
+ );
}
} catch (error) {
workspace.reportFailure(file.name, error);
diff --git a/src/app/scene-file.ts b/src/app/scene-file.ts
index 64897d4..d0484fd 100644
--- a/src/app/scene-file.ts
+++ b/src/app/scene-file.ts
@@ -3,7 +3,6 @@ import {
createDocument,
createResources,
type EditorDocument,
- layerLuts,
type ProcessingLayer,
type Scene,
walkLayers,
@@ -25,7 +24,7 @@ import {
maskOperation,
maskSchema,
} from "@/features/layers/model";
-import { readCubeFile } from "@/features/lut/cube";
+import { lutSchema } from "@/features/lut/model";
import { curveSchema } from "@/features/tone-curves/curve";
import { defaultVignette, vignetteSchema } from "@/features/vignette/model";
import { whiteBalanceSchema } from "@/features/white-balance/edits";
@@ -34,7 +33,7 @@ import { parse, withDefaults } from "@/lib/parse";
/** Raised only when older files can no longer load as written; a parameter added later takes its default. */
const version = 1;
-/** A saved scene: the scene as edited and the name and type of each source file, its image and LUTs, stored beside it by ID. */
+/** A saved scene: the scene as edited and the name and type of each source file, stored beside it by ID. */
export type SceneJson = {
format: "openlight";
version: number;
@@ -46,25 +45,14 @@ export type SceneJson = {
export function snapshotScene(document: EditorDocument) {
const scene = document.scene.getState();
const { source } = scene.layers[0];
- const files = new Map([
- [source, document.resources.get(source).file],
- ...Array.from(
- layerLuts(scene.layers),
- (id) => [id, document.resources.getLut(id).file] as const,
- ),
- ]);
+ const { file } = document.resources.get(source);
const json: SceneJson = {
format: "openlight",
version,
- sources: Object.fromEntries(
- Array.from(files, ([id, file]) => [
- id,
- { name: file.name, type: file.type },
- ]),
- ),
+ sources: { [source]: { name: file.name, type: file.type } },
scene,
};
- return { json, files };
+ return { json, files: new Map([[source, file]]) };
}
const id = z.string().check(z.minLength(1));
@@ -106,7 +94,7 @@ function processingLayer(children: z.ZodMiniType<readonly ProcessingLayer[]>) {
kind: z.literal("fill"),
fill: withDefaults(defaultFill, fillSchema),
}),
- z.object({ ...base, kind: z.literal("lut"), lut: id }),
+ z.object({ ...base, kind: z.literal("lut"), lut: lutSchema }),
z.object({
...base,
kind: z.literal("heal"),
@@ -201,22 +189,13 @@ export async function openScene(
}
const { sources, scene } = parse(savedSchema, saved, "Invalid scene");
const [image, ...layers] = scene.layers;
- function sourceFile(id: string, missing: string) {
- const source = sources[id];
- const data = files.get(id);
- if (!source || !data) {
- throw Error(missing);
- }
- return new File([data], source.name, { type: source.type });
+ const source = sources[image.source];
+ const data = files.get(image.source);
+ if (!source || !data) {
+ throw Error("The scene's image is missing.");
}
- const imageFile = sourceFile(image.source, "The scene's image is missing.");
- const luts = await Promise.all(
- Array.from(layerLuts(scene.layers), async (id) => {
- const file = sourceFile(id, "A LUT in this scene is missing.");
- return { id, file, table: await readCubeFile(file) };
- }),
- );
- const decoded = await decode(imageFile);
+ const sourceFile = new File([data], source.name, { type: source.type });
+ const decoded = await decode(sourceFile);
const asShot = decoded.raw?.asShot;
// Absolute white balance applies only to RAW images, which fall back to their as-shot balance.
const whiteBalance =
@@ -229,10 +208,7 @@ export async function openScene(
: asShot;
const resources = createResources();
try {
- resources.add(imageFile, decoded, image.source);
- for (const { id, file, table } of luts) {
- resources.addLut(file, table, id);
- }
+ resources.add(sourceFile, decoded, image.source);
return createDocument(
{
frame: scene.frame,
diff --git a/src/app/webmcp.ts b/src/app/webmcp.ts
index 1b07549..a04e29c 100644
--- a/src/app/webmcp.ts
+++ b/src/app/webmcp.ts
@@ -58,7 +58,9 @@ function sourceSize(document: EditorDocument) {
return document.resources.get(image.source).image.size;
}
-/** The open photo as an agent reads it; brush strokes and healing patches are counted, not listed. */
+const omitted = new Set(["strokes", "patches", "table"]);
+
+/** The open photo as an agent reads it; brush strokes, healing patches, and LUT tables are counted, not listed. */
function describe(workspace: Workspace, controls: Controls) {
const { file, failure, scene, selectedLayerId, preview, history } =
controls.getState();
@@ -74,7 +76,7 @@ function describe(workspace: Workspace, controls: Controls) {
history,
};
return JSON.stringify(state, (key, value) =>
- Array.isArray(value) && (key === "strokes" || key === "patches")
+ Array.isArray(value) && omitted.has(key)
? `${value.length} omitted`
: value,
);
diff --git a/src/components/editor/pipeline.tsx b/src/components/editor/pipeline.tsx
index f7c434e..fe69fe0 100644
--- a/src/components/editor/pipeline.tsx
+++ b/src/components/editor/pipeline.tsx
@@ -10,7 +10,6 @@ import type { Gpu } from "vgpu";
import { useGpu } from "vgpu-react";
import { adjustmentTarget } from "@/core/document";
import type { ImageSource } from "@/core/image";
-import type { LookupTable } from "@/core/image/lut";
import type { createRenderer } from "@/core/renderer";
import { useDisposable } from "@/hooks/use-disposable";
import { useDocument, useScene } from "./session";
@@ -40,7 +39,6 @@ type RendererProviderProps = {
createRenderer: (
gpu: Gpu,
source: ImageSource,
- luts: (id: string) => LookupTable,
) => ReturnType<typeof createRenderer>;
};
@@ -53,8 +51,8 @@ export function RendererProvider({
const sourceId = useScene((scene) => scene.layers[0].source);
const source = document.resources.get(sourceId);
const renderer = useDisposable(
- () => createRenderer(gpu, source, document.resources.getLut),
- [gpu, source, document, createRenderer],
+ () => createRenderer(gpu, source),
+ [gpu, source, createRenderer],
);
const [error, setError] = useState<string>();
diff --git a/src/core/document/index.ts b/src/core/document/index.ts
index ee83fe7..9c8075e 100644
--- a/src/core/document/index.ts
+++ b/src/core/document/index.ts
@@ -3,7 +3,7 @@ import { validateFrame } from "@/core/image/frame";
import { createHistory } from "./history";
import { createResources } from "./resources";
import type { Mask, MaskModifier, Scene } from "./scene";
-import { findLayer, layerLuts } from "./tree";
+import { findLayer } from "./tree";
export type {
Adjustments,
@@ -21,6 +21,7 @@ export type {
ImageLayer,
Layer,
LinearGradient,
+ LookupTable,
Mask,
MaskLayer,
MaskModifier,
@@ -35,7 +36,6 @@ export {
adjustmentTarget,
editLayer,
findLayer,
- layerLuts,
locateLayer,
maskModifiers,
updateLayer,
@@ -93,12 +93,7 @@ export function createDocument(initial: Scene, resources = createResources()) {
100,
(retained) => {
resources.retain(
- new Set(
- retained.flatMap((state) => [
- state.layers[0].source,
- ...layerLuts(state.layers),
- ]),
- ),
+ new Set(retained.map((state) => state.layers[0].source)),
);
},
);
diff --git a/src/core/document/resources.ts b/src/core/document/resources.ts
index c9d7262..1dcb505 100644
--- a/src/core/document/resources.ts
+++ b/src/core/document/resources.ts
@@ -1,23 +1,18 @@
import type { ImageSource } from "@/core/image";
-import type { LookupTable } from "@/core/image/lut";
-/** Owns the document's files, with each image's GPU target and each LUT's table, outside scene history. */
+/** Owns the document's image files and GPU targets, outside scene history. */
export function createResources() {
const images = new Map<string, { file: File } & ImageSource>();
- const luts = new Map<string, { file: File } & LookupTable>();
let disposed = false;
- function checkNew(id: string) {
- if (disposed) {
- throw new Error("Document is closed.");
- }
- if (images.has(id) || luts.has(id)) {
- throw new Error("Resource already exists.");
- }
- }
return {
/** A saved document restores each source under its original ID. */
add(file: File, source: ImageSource, id: string = crypto.randomUUID()) {
- checkNew(id);
+ if (disposed) {
+ throw new Error("Document is closed.");
+ }
+ if (images.has(id)) {
+ throw new Error("Image resource already exists.");
+ }
images.set(id, { file, ...source });
return id;
},
@@ -28,18 +23,6 @@ export function createResources() {
}
return resource;
},
- addLut(file: File, lut: LookupTable, id: string = crypto.randomUUID()) {
- checkNew(id);
- luts.set(id, { file, ...lut });
- return id;
- },
- getLut(id: string) {
- const resource = luts.get(id);
- if (!resource) {
- throw new Error("LUT is unavailable.");
- }
- return resource;
- },
retain(ids: ReadonlySet<string>) {
for (const [id, source] of images) {
if (!ids.has(id)) {
@@ -47,13 +30,7 @@ export function createResources() {
images.delete(id);
}
}
- for (const id of luts.keys()) {
- if (!ids.has(id)) {
- luts.delete(id);
- }
- }
},
- /** Tables hold no GPU memory, so they stay readable to an export still rendering the closed document. */
dispose() {
disposed = true;
for (const source of images.values()) {
diff --git a/src/core/document/scene.ts b/src/core/document/scene.ts
index f2d3d2b..7ed0273 100644
--- a/src/core/document/scene.ts
+++ b/src/core/document/scene.ts
@@ -57,6 +57,15 @@ export type Fill = {
readonly blend: Blend;
};
+type Rgb = readonly [number, number, number];
+/** A 3D color lookup table: `size`³ output colors for inputs spread evenly across `domain`. */
+export type LookupTable = {
+ readonly size: number;
+ readonly domain: readonly [min: Rgb, max: Rgb];
+ /** RGB triplets, with the red input varying fastest, then green, then blue. */
+ readonly table: readonly number[];
+};
+
export type ImageLayer = {
readonly kind: "image";
readonly id: string;
@@ -122,8 +131,7 @@ export type ProcessingLayer = {
| { readonly kind: "grain"; readonly grain: Grain }
| { readonly kind: "color-mixer"; readonly colorMixer: ColorMixer }
| { readonly kind: "fill"; readonly fill: Fill }
- /** A 3D LUT from the document's resources, by ID. */
- | { readonly kind: "lut"; readonly lut: string }
+ | { readonly kind: "lut"; readonly lut: LookupTable }
| { readonly kind: "heal"; readonly patches: readonly HealPatch[] }
| {
readonly kind: "mask";
diff --git a/src/core/document/tree.ts b/src/core/document/tree.ts
index 6e904d5..90c69d5 100644
--- a/src/core/document/tree.ts
+++ b/src/core/document/tree.ts
@@ -18,17 +18,6 @@ export function* walkLayers(
}
}
-/** The IDs of the LUTs these layers use, each once. */
-export function layerLuts(layers: readonly Layer[]) {
- const ids = new Set<string>();
- for (const { layer } of walkLayers(layers)) {
- if (layer.kind === "lut") {
- ids.add(layer.lut);
- }
- }
- return ids;
-}
-
export function locateLayer(layers: readonly Layer[], id: string) {
for (const location of walkLayers(layers)) {
if (location.layer.id === id) {
diff --git a/src/core/image/lut.ts b/src/core/image/lut.ts
deleted file mode 100644
index 3d14c49..0000000
--- a/src/core/image/lut.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-type Rgb = readonly [number, number, number];
-
-/** A 3D color lookup table: `size`³ output colors for inputs spread evenly across `domain`. */
-export type LookupTable = {
- /** Its TITLE, or the name of the file it came from. */
- readonly name: string;
- readonly size: number;
- readonly domain: readonly [min: Rgb, max: Rgb];
- /** RGB triplets, with the red input varying fastest, then green, then blue. */
- readonly table: Float32Array<ArrayBuffer>;
-};
diff --git a/src/features/layers/toolbar.tsx b/src/features/layers/toolbar.tsx
index 9477742..f41f3b1 100644
--- a/src/features/layers/toolbar.tsx
+++ b/src/features/layers/toolbar.tsx
@@ -58,7 +58,9 @@ export function CanvasToolbar({ children }: { children?: ReactNode }) {
// The canvas's width, kept so a resize always renders again, even when the bar is already at its
// roomiest step, and the overflow below is measured anew.
const [width, setWidth] = useState(0);
- const hasLayerOptions = layer.kind !== "image" && layer.kind !== "heal";
+ // A LUT's intensity is its opacity, which its panel shows.
+ const hasLayerOptions =
+ layer.kind !== "image" && layer.kind !== "heal" && layer.kind !== "lut";
const shown = Boolean(children) || hasLayerOptions;
const content = `${Boolean(children)}/${layer.kind}/${layer.kind === "mask" ? layer.mask.kind : ""}`;
// New content or a resized canvas starts again from the roomiest layout.
diff --git a/src/features/lut/controls.tsx b/src/features/lut/controls.tsx
deleted file mode 100644
index df52afd..0000000
--- a/src/features/lut/controls.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { Button } from "@roprgm/ui/button";
-import { ScrollText } from "@roprgm/ui/scroll-text";
-import { useRef } from "react";
-import { useDocument } from "@/components/editor/session";
-import { readCubeFile } from "./cube";
-import { setLut } from "./edits";
-import { LutInput } from "./input";
-
-/** The LUT's name and a way to replace its file; the layer's opacity sets its strength. */
-export function LutControls({
- id,
- lut,
- onFailure,
-}: {
- id: string;
- lut: string;
- onFailure: (file: string, error: unknown) => void;
-}) {
- const document = useDocument();
- const input = useRef<HTMLInputElement>(null);
- async function replace(file: File) {
- try {
- const table = await readCubeFile(file);
- setLut(document, id, document.resources.addLut(file, table));
- } catch (error) {
- onFailure(file.name, error);
- }
- }
- return (
- <section className="flex items-center gap-3 p-3.5">
- <ScrollText className="min-w-0 flex-1 text-foreground">
- {document.resources.getLut(lut).name}
- </ScrollText>
- <Button size="sm" onClick={() => input.current?.click()}>
- Replace…
- </Button>
- <LutInput ref={input} onChoose={replace} />
- </section>
- );
-}
diff --git a/src/features/lut/cube.ts b/src/features/lut/cube.ts
index d5ff607..a69f143 100644
--- a/src/features/lut/cube.ts
+++ b/src/features/lut/cube.ts
@@ -1,12 +1,12 @@
-import type { LookupTable } from "@/core/image/lut";
+import type { LookupTable } from "@/core/document";
+import { lutSizes } from "./model";
type Rgb = [number, number, number];
-/** Editors write sizes up to 65; two points already span the domain. */
-const maxSize = 65;
+export const cubeExtension = ".cube";
export function isCubeFile(file: File) {
- return /\.cube$/i.test(file.name);
+ return file.name.toLowerCase().endsWith(cubeExtension);
}
function numbers(tokens: readonly string[], count: number, at: string) {
@@ -28,14 +28,17 @@ function rgb(tokens: readonly string[], at: string): Rgb {
* Reads an Adobe or Resolve `.cube` 3D LUT: keywords, then `LUT_3D_SIZE`³ rows of RGB with red
* varying fastest. Other keywords are skipped; `name` stands in for a missing TITLE.
*/
-export function readCube(text: string, name: string): LookupTable {
+export function readCube(
+ text: string,
+ name: string,
+): { name: string; lut: LookupTable } {
+ const [minSize, maxSize] = lutSizes;
let title = name;
let min: Rgb = [0, 0, 0];
let max: Rgb = [1, 1, 1];
let size = 0;
- let table: Float32Array<ArrayBuffer> | undefined;
- let filled = 0;
- const lines = text.replace(/^\uFEFF/, "").split(/\r?\n|\r/);
+ const table: number[] = [];
+ const lines = text.replace(/^/, "").split(/\r?\n|\r/);
for (const [index, line] of lines.entries()) {
const [keyword, ...tokens] = line.trim().split(/\s+/);
const at = `Line ${index + 1}`;
@@ -54,16 +57,15 @@ export function readCube(text: string, name: string): LookupTable {
case "LUT_1D_SIZE":
throw Error("This is a 1D LUT; choose a 3D LUT.");
case "LUT_3D_SIZE":
- if (table) {
+ if (size) {
throw Error(`${at}: LUT_3D_SIZE appears twice.`);
}
[size] = numbers(tokens, 1, at);
- if (!Number.isInteger(size) || size < 2 || size > maxSize) {
+ if (!Number.isInteger(size) || size < minSize || size > maxSize) {
throw Error(
- `${at}: LUT_3D_SIZE must be a whole number from 2 to 65.`,
+ `${at}: LUT_3D_SIZE must be a whole number from ${minSize} to ${maxSize}.`,
);
}
- table = new Float32Array(3 * size ** 3);
break;
case "DOMAIN_MIN":
min = rgb(tokens, at);
@@ -81,28 +83,27 @@ export function readCube(text: string, name: string): LookupTable {
if (/^[a-z_]/i.test(keyword)) {
break;
}
- if (!table) {
+ if (!size) {
throw Error(`${at}: the table starts before LUT_3D_SIZE.`);
}
- if (filled === table.length) {
+ if (table.length === 3 * size ** 3) {
throw Error(`${at}: LUT_3D_SIZE ${size} needs ${size ** 3} rows.`);
}
- table.set(rgb([keyword, ...tokens], at), filled);
- filled += 3;
+ table.push(...rgb([keyword, ...tokens], at));
}
}
- if (!table) {
+ if (!size) {
throw Error("LUT_3D_SIZE is missing, so this isn't a 3D LUT.");
}
- if (filled < table.length) {
+ if (table.length < 3 * size ** 3) {
throw Error(
- `LUT_3D_SIZE ${size} needs ${size ** 3} rows; found ${filled / 3}.`,
+ `LUT_3D_SIZE ${size} needs ${size ** 3} rows; found ${table.length / 3}.`,
);
}
if (min.some((low, channel) => low >= max[channel])) {
throw Error("DOMAIN_MIN must be below DOMAIN_MAX in every channel.");
}
- return { name: title, size, domain: [min, max], table };
+ return { name: title, lut: { size, domain: [min, max], table } };
}
/** Reads a `.cube` file, named after its TITLE or else the file. */
diff --git a/src/features/lut/curves.tsx b/src/features/lut/curves.tsx
new file mode 100644
index 0000000..d215590
--- /dev/null
+++ b/src/features/lut/curves.tsx
@@ -0,0 +1,66 @@
+import type { LookupTable } from "@/core/document";
+
+/** Screened together, the three channels draw white where the LUT keeps grays neutral. */
+const channels = ["#ff4d4d", "#4dff4d", "#4d4dff"];
+
+const toLinear = (value: number) =>
+ value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+const toSrgb = (value: number) =>
+ value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;
+
+/** Each channel's output along the gray axis at `opacity`, which mixes in linear light as the renderer does. */
+function grayResponse(
+ { size, table }: LookupTable,
+ channel: number,
+ opacity: number,
+) {
+ return Array.from({ length: size }, (_, i) => {
+ const input = i / (size - 1);
+ const graded = Math.min(
+ Math.max(table[3 * i * (1 + size + size * size) + channel], 0),
+ 1,
+ );
+ const linear =
+ toLinear(input) + (toLinear(graded) - toLinear(input)) * opacity;
+ return `${input},${1 - toSrgb(linear)}`;
+ }).join(" ");
+}
+
+/** A read-only view of what the layer does to grays, one curve per channel. */
+export function LutCurves({
+ lut,
+ opacity,
+}: {
+ lut: LookupTable;
+ opacity: number;
+}) {
+ return (
+ <section className="flex flex-col gap-2.5">
+ <h2 className="text-muted">Gray response</h2>
+ <svg
+ role="img"
+ aria-label="Each channel's output for grays from black to white"
+ viewBox="0 0 1 1"
+ preserveAspectRatio="none"
+ className="aspect-square max-h-45 w-full overflow-visible rounded bg-field"
+ >
+ <path
+ d="M.25 0V1M.5 0V1M.75 0V1M0 .25H1M0 .5H1M0 .75H1"
+ stroke="white"
+ strokeOpacity="0.07"
+ vectorEffect="non-scaling-stroke"
+ />
+ {channels.map((color, channel) => (
+ <polyline
+ key={color}
+ points={grayResponse(lut, channel, opacity)}
+ fill="none"
+ stroke={color}
+ vectorEffect="non-scaling-stroke"
+ className="mix-blend-screen"
+ />
+ ))}
+ </svg>
+ </section>
+ );
+}
diff --git a/src/features/lut/edits.ts b/src/features/lut/edits.ts
deleted file mode 100644
index 0522aed..0000000
--- a/src/features/lut/edits.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { type EditorDocument, editLayer } from "@/core/document";
-
-/** Points a LUT layer at another table; a layer still named after its old table takes the new name. */
-export function setLut(document: EditorDocument, id: string, lut: string) {
- const { name } = document.resources.getLut(lut);
- editLayer(document, id, (layer) => {
- if (layer.kind !== "lut") {
- throw Error("Select a LUT layer.");
- }
- const named = layer.name === document.resources.getLut(layer.lut).name;
- return { ...layer, lut, name: named ? name : layer.name };
- });
-}
diff --git a/src/features/lut/input.tsx b/src/features/lut/input.tsx
deleted file mode 100644
index 57febb9..0000000
--- a/src/features/lut/input.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { RefObject } from "react";
-
-/** The hidden `.cube` picker; clearing it after each pick lets the same file be chosen again. */
-export function LutInput({
- ref,
- onChoose,
-}: {
- ref: RefObject<HTMLInputElement | null>;
- onChoose: (file: File) => void;
-}) {
- return (
- <input
- ref={ref}
- type="file"
- accept=".cube"
- hidden
- onChange={(event) => {
- const file = event.currentTarget.files?.[0];
- if (file) {
- onChoose(file);
- }
- event.currentTarget.value = "";
- }}
- />
- );
-}
diff --git a/src/features/lut/model.ts b/src/features/lut/model.ts
new file mode 100644
index 0000000..6fb2ce0
--- /dev/null
+++ b/src/features/lut/model.ts
@@ -0,0 +1,24 @@
+import { z } from "zod/mini";
+import type { LookupTable } from "@/core/document";
+
+/** Editors write sizes up to 65; two points already span the domain. */
+export const lutSizes = [2, 65] as const;
+
+const rgb = z.tuple([z.number(), z.number(), z.number()]);
+
+export const lutSchema = z
+ .object({
+ size: z.int().check(z.minimum(lutSizes[0]), z.maximum(lutSizes[1])),
+ domain: z.tuple([rgb, rgb]),
+ table: z.array(z.number()),
+ })
+ .check(
+ z.refine(
+ ({ domain: [min, max] }) => min.every((low, i) => low < max[i]),
+ "The domain's minimum must be below its maximum",
+ ),
+ z.refine(
+ ({ size, table }) => table.length === 3 * size ** 3,
+ "The table needs three values per entry",
+ ),
+ ) satisfies z.ZodMiniType<LookupTable>;
diff --git a/src/features/lut/pass.ts b/src/features/lut/pass.ts
index 00f1037..86e17d6 100644
--- a/src/features/lut/pass.ts
+++ b/src/features/lut/pass.ts
@@ -1,16 +1,28 @@
-import type { LookupTable } from "@/core/image/lut";
+import type { LookupTable } from "@/core/document";
import { node } from "@/core/renderer";
import shader from "./lut.wgsl";
-export function lut(table: LookupTable, name = "lut") {
+/** One array per table, so the graph uploads a table once rather than on every render. */
+const uploads = new WeakMap<readonly number[], Float32Array<ArrayBuffer>>();
+
+function tableData(table: readonly number[]) {
+ let data = uploads.get(table);
+ if (!data) {
+ data = new Float32Array(table);
+ uploads.set(table, data);
+ }
+ return data;
+}
+
+export function lut(lut: LookupTable, name = "lut") {
return node(name, shader, {
set: {
params: {
- size: table.size,
- domainMin: table.domain[0],
- domainMax: table.domain[1],
+ size: lut.size,
+ domainMin: lut.domain[0],
+ domainMax: lut.domain[1],
},
},
- storage: { table: table.table },
+ storage: { table: tableData(lut.table) },
});
}
diff --git a/tests/lut.e2e.ts b/tests/lut.e2e.ts
index 38374b9..b46ae08 100644
--- a/tests/lut.e2e.ts
+++ b/tests/lut.e2e.ts
@@ -1,14 +1,7 @@
import { expect, test } from "./fixtures";
import { readImage } from "./images";
-/** A two-point LUT that returns its input, rows listed with red varying fastest. */
-const identity = [
- 'TITLE "Identity"',
- "LUT_3D_SIZE 2",
- ...Array.from({ length: 8 }, (_, i) => `${i & 1} ${(i >> 1) & 1} ${i >> 2}`),
-].join("\n");
-
-test("a LUT layer grades the photo from a .cube file at the layer's opacity, replaces its file, undoes, and saves with the scene", async ({
+test("a LUT layer grades the photo from a .cube file at the layer's opacity, undoes, and saves with the scene", async ({
page,
}) => {
test.setTimeout(90_000);
@@ -43,19 +36,30 @@ test("a LUT layer grades the photo from a .cube file at the layer's opacity, rep
await page.getByRole("menuitem", { name: "LUT", exact: true }).click();
await (await chooser).setFiles("tests/fixtures/swap.cube");
await expect(layers.getByText("Swap red and blue")).toBeVisible();
- await expect(
- page.getByRole("button", { name: "Replace…", exact: true }),
- ).toBeVisible();
const [patch, gray] = (await sample()) ?? [];
near(patch, [128, 80, 48, 255]);
near(gray, [128, 128, 128, 255]);
});
const swapped = await sample();
- await test.step("the layer's opacity sets its strength", async () => {
- const opacity = page.getByRole("textbox", { name: "Opacity", exact: true });
- await opacity.fill("50");
- await opacity.press("Enter");
+ await test.step("the panel's Intensity sets the layer's opacity", async () => {
+ await expect(
+ page.getByRole("textbox", { name: "Opacity", exact: true }),
+ ).toHaveCount(0);
+ const intensity = page.getByRole("textbox", {
+ name: "Intensity",
+ exact: true,
+ });
+ await intensity.fill("50");
+ await intensity.press("Enter");
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const layer = window.openlight.getState().scene?.layers.at(-1);
+ return layer?.kind === "lut" ? layer.opacity : undefined;
+ }),
+ )
+ .toBe(0.5);
const [patch] = (await sample()) ?? [];
expect(patch?.[0]).toBeGreaterThan(48);
expect(patch?.[0]).toBeLessThan(128);
@@ -64,23 +68,7 @@ test("a LUT layer grades the photo from a .cube file at the layer's opacity, rep
});
const half = await sample();
- await test.step("replacing the file with an identity LUT leaves the photo as it was", async () => {
- const chooser = page.waitForEvent("filechooser");
- await page.getByRole("button", { name: "Replace…", exact: true }).click();
- await (await chooser).setFiles({
- name: "identity.cube",
- mimeType: "",
- buffer: Buffer.from(identity),
- });
- await expect(layers.getByText("Identity")).toBeVisible();
- const [patch, gray] = (await sample()) ?? [];
- near(patch, original?.[0] ?? []);
- near(gray, original?.[1] ?? []);
- });
-
- await test.step("undo steps back through the replacement, the opacity, and the layer", async () => {
- await page.keyboard.press("ControlOrMeta+z");
- expect(await sample()).toEqual(half);
+ await test.step("undo steps back through the opacity and the layer", async () => {
await page.keyboard.press("ControlOrMeta+z");
expect(await sample()).toEqual(swapped);
await page.keyboard.press("ControlOrMeta+z");
diff --git a/tests/lut.test.ts b/tests/lut.test.ts
index a4561a8..a3f6299 100644
--- a/tests/lut.test.ts
+++ b/tests/lut.test.ts
@@ -1,15 +1,17 @@
import { expect, test } from "bun:test";
import { init, target } from "vgpu/mock";
-import { addLut, createImageLayer, createMask } from "@/app/editor/layers";
+import {
+ createImageLayer,
+ createLutLayer,
+ createMask,
+} from "@/app/editor/layers";
import { createEditorRenderer } from "@/app/editor/renderer";
-import { createDocument, createResources, findLayer } from "@/core/document";
+import { createDocument, createResources } from "@/core/document";
import { createImageSource } from "@/core/image";
import { imageFrame } from "@/core/image/frame";
-import { setAdjustments } from "@/features/adjustments/edits";
-import { addLayer, setLayer } from "@/features/layers/edits";
+import { addLayer } from "@/features/layers/edits";
import { defaultGradient } from "@/features/layers/gradient";
import { readCube, readCubeFile } from "@/features/lut/cube";
-import { setLut } from "@/features/lut/edits";
/** A two-point LUT that swaps red and blue, rows listed with red varying fastest. */
const swap = [
@@ -24,9 +26,9 @@ const swap = [
];
test("a .cube file reads into a 3D table with its title, domain, and row order, and a broken one says why", async () => {
- const lut = readCube(
+ const { name, lut } = readCube(
[
- "\uFEFF# Created by hand",
+ "# Created by hand",
'TITLE "Red and blue swapped"',
"",
"LUT_3D_SIZE 2",
@@ -38,8 +40,8 @@ test("a .cube file reads into a 3D table with its title, domain, and row order,
].join("\r\n"),
"swap",
);
+ expect(name).toBe("Red and blue swapped");
expect(lut).toMatchObject({
- name: "Red and blue swapped",
size: 2,
domain: [
[0, 0, 0],
@@ -47,8 +49,8 @@ test("a .cube file reads into a 3D table with its title, domain, and row order,
],
});
// Red varies fastest: the second row answers pure red, the fifth pure blue.
- expect([...lut.table.subarray(3, 6)]).toEqual([0, 0, 1]);
- expect([...lut.table.subarray(12, 15)]).toEqual([1, 0, 0]);
+ expect(lut.table.slice(3, 6)).toEqual([0, 0, 1]);
+ expect(lut.table.slice(12, 15)).toEqual([1, 0, 0]);
const untitled = await readCubeFile(
new File(
[["LUT_3D_SIZE 2", "LUT_3D_INPUT_RANGE -0.5 1.5", ...swap].join("\n")],
@@ -57,10 +59,12 @@ test("a .cube file reads into a 3D table with its title, domain, and row order,
);
expect(untitled).toMatchObject({
name: "Warm film",
- domain: [
- [-0.5, -0.5, -0.5],
- [1.5, 1.5, 1.5],
- ],
+ lut: {
+ domain: [
+ [-0.5, -0.5, -0.5],
+ [1.5, 1.5, 1.5],
+ ],
+ },
});
const broken: [string[], string][] = [
[swap, "Line 1: the table starts before LUT_3D_SIZE."],
@@ -83,7 +87,7 @@ test("a .cube file reads into a 3D table with its title, domain, and row order,
}
});
-test("a LUT layer renders its table, nests in a mask, follows a replacement's name, and keeps its file only while history uses it", async () => {
+test("a LUT layer renders its table inside a mask", async () => {
const gpu = await init();
const source = createImageSource(
target(gpu, { size: [16, 8], format: "rgba16float" }),
@@ -93,58 +97,22 @@ test("a LUT layer renders its table, nests in a mask, follows a replacement's na
const document = createDocument(
{
frame: imageFrame(source.image.size),
- layers: [{ ...createImageLayer(sourceId, "Photo"), id: "base" }],
+ layers: [createImageLayer(sourceId, "Photo")],
},
resources,
);
- const renderer = createEditorRenderer(gpu, source, resources.getLut);
- const read = (lines: string[], name: string) =>
- readCube(["LUT_3D_SIZE 2", ...lines].join("\n"), name);
- const swapFile = new File([], "swap.cube");
- const layer = (id: string) => findLayer(document.scene.getState().layers, id);
- const lutOf = (id: string) => {
- const item = layer(id);
- if (item?.kind !== "lut") throw Error("Missing LUT layer.");
- return item.lut;
- };
+ const renderer = createEditorRenderer(gpu, source);
try {
const mask = addLayer(document, createMask(defaultGradient([16, 8])));
- const nested = addLut(document, swapFile, read(swap, "Swap"), {
+ const { name, lut } = readCube(["LUT_3D_SIZE 2", ...swap].join("\n"), "");
+ const layer = addLayer(document, createLutLayer(name, lut), {
inside: mask,
});
- expect(layer(nested)).toMatchObject({ kind: "lut", name: "Swap" });
await renderer.update(document.scene.getState());
expect(renderer.inspect().passes).toEqual([
- `layer/${nested}/lut`,
+ `layer/${layer}/lut`,
`layer/${mask}/mix`,
]);
-
- const identity = read(
- Array.from({ length: 8 }, (_, i) => `${i & 1} ${(i >> 1) & 1} ${i >> 2}`),
- "Identity",
- );
- const replaced = resources.addLut(new File([], "identity.cube"), identity);
- setLut(document, nested, replaced);
- expect(layer(nested)).toMatchObject({ lut: replaced, name: "Identity" });
- setLayer(document, nested, { name: "Neutral" });
- setLut(document, nested, resources.addLut(swapFile, read(swap, "Swap")));
- expect(layer(nested)).toMatchObject({ name: "Neutral" });
- expect(() => setLut(document, mask, replaced)).toThrow("Select a LUT");
- expect(() => setLut(document, nested, "missing")).toThrow("unavailable");
-
- // A LUT stays while undo or redo can reach it and goes once a new edit drops that branch.
- const top = lutOf(addLut(document, swapFile, read(swap, "Top")));
- document.history.undo();
- expect(resources.getLut(top).name).toBe("Top");
- setAdjustments(document, { exposure: 1 });
- expect(() => resources.getLut(top)).toThrow("unavailable");
- expect(resources.getLut(replaced).name).toBe("Identity");
-
- // Adding while a gesture is open commits it first, so the new table is kept.
- document.history.begin();
- setAdjustments(document, { exposure: 0.5 });
- const grouped = lutOf(addLut(document, swapFile, read(swap, "Grouped")));
- expect(resources.getLut(grouped).name).toBe("Grouped");
} finally {
renderer.dispose();
document.dispose();
diff --git a/tests/rendering-benchmark.ts b/tests/rendering-benchmark.ts
index a367e9c..91c6ca5 100644
--- a/tests/rendering-benchmark.ts
+++ b/tests/rendering-benchmark.ts
@@ -4,6 +4,7 @@ import { createImageLayer } from "@/app/editor/layers";
import { createEditorRenderer } from "@/app/editor/renderer";
import type {
BrushStroke,
+ LookupTable,
Mask,
ProcessingLayer,
Scene,
@@ -11,7 +12,6 @@ import type {
} from "@/core/document";
import { createImageSource } from "@/core/image";
import { imageFrame } from "@/core/image/frame";
-import type { LookupTable } from "@/core/image/lut";
import { defaultAdjustments } from "@/features/adjustments/model";
import { createHistogram } from "@/features/histogram/histogram";
import { defaultCurve } from "@/features/tone-curves/curve";
@@ -84,15 +84,13 @@ function benchmarkMask(workload: Workload, size: [number, number]): Mask {
/** A 33-point LUT that warms highlights and cools shadows, as a creative grade does. */
function benchmarkLut(): LookupTable {
const size = 33;
- const table = new Float32Array(3 * size ** 3);
- for (let index = 0; index < size ** 3; index++) {
+ const table = Array.from({ length: size ** 3 }, (_, index) => {
const r = (index % size) / (size - 1);
const g = (Math.floor(index / size) % size) / (size - 1);
const b = Math.floor(index / size ** 2) / (size - 1);
- table.set([r ** 0.9, g, b ** 1.1], 3 * index);
- }
+ return [r ** 0.9, g, b ** 1.1];
+ }).flat();
return {
- name: "Benchmark",
size,
domain: [
[0, 0, 0],
@@ -222,7 +220,7 @@ export async function benchmarkRendering(
id: "benchmark-lut",
name: "LUT",
kind: "lut",
- lut: "benchmark-table",
+ lut: benchmarkLut(),
});
}
if (
@@ -277,9 +275,8 @@ export async function benchmarkRendering(
...effects,
],
};
- const lut = benchmarkLut();
function create(clock?: Timer) {
- const renderer = createEditorRenderer(gpu, source, () => lut, clock);
+ const renderer = createEditorRenderer(gpu, source, clock);
// Half a device pixel per source pixel, as a fitted view of a large photo, renders at a factor of 2.
renderer.setDisplayScale(proxy ? 0.5 : 1);
return renderer;
diff --git a/tests/scene-file.test.ts b/tests/scene-file.test.ts
index 5c0cbae..e2dbebe 100644
--- a/tests/scene-file.test.ts
+++ b/tests/scene-file.test.ts
@@ -104,16 +104,22 @@ test("scene files reopen the photo with every layer for further editing", async
api.setVignette({ intensity: 70, softness: 20 });
api.setColorMixer("blue", { hue: 20, luminance: -10 });
api.setExposure(api.addLayer("exposure"), -0.5);
- const cube = [
- "TITLE Grade",
- "LUT_3D_SIZE 2",
- ...Array(8).fill("0.5 0.5 0.5"),
- ];
- await api.openFile(new File([cube.join("\n")], "grade.cube"));
- const lut = api.getState().scene?.layers.at(-1);
- if (lut?.kind !== "lut") throw Error("Missing LUT layer.");
- api.duplicateLayer(lut.id);
+ await api.openFile(
+ new File(
+ [
+ [
+ "TITLE Grade",
+ "LUT_3D_SIZE 2",
+ ...Array(8).fill("0.5 0.5 0.5"),
+ ].join("\n"),
+ ],
+ "grade.cube",
+ ),
+ );
const edited = workspace.getDocument().scene.getState();
+ const lut = edited.layers.at(-1);
+ if (lut?.kind !== "lut") throw Error("Missing LUT layer.");
+ expect(lut.name).toBe("Grade");
const file = await api.exportScene();
expect(file.name).toBe("photo.openlight");
@@ -123,18 +129,11 @@ test("scene files reopen the photo with every layer for further editing", async
expect(json).toMatchObject({
format: "openlight",
version: 1,
- sources: {
- [source]: { name: "photo.nef", type: "image/x-nikon-nef" },
- [lut.lut]: { name: "grade.cube", type: "" },
- },
+ sources: { [source]: { name: "photo.nef", type: "image/x-nikon-nef" } },
scene: edited,
});
- expect(Object.keys(json.sources)).toHaveLength(2);
const stored = await entries.get(`sources/${source}`)?.bytes();
expect(stored).toEqual(bytes);
- expect(await entries.get(`sources/${lut.lut}`)?.text()).toBe(
- cube.join("\n"),
- );
const opened = await openSceneFile(file, raw.decode);
const reopened = raw.decoded.at(-1);
@@ -142,7 +141,6 @@ test("scene files reopen the photo with every layer for further editing", async
expect(reopened?.type).toBe("image/x-nikon-nef");
expect(await reopened?.bytes()).toEqual(bytes);
expect(opened.scene.getState()).toEqual(edited);
- expect(opened.resources.getLut(lut.lut).name).toBe("Grade");
expect(opened.history.status.getState().undoCount).toBe(0);
opened.dispose();
@@ -162,13 +160,6 @@ test("scene files reopen the photo with every layer for further editing", async
],
[await archive({ ...json, version: 2 }), "needs a newer version"],
[await archive(json, new Map()), "The scene's image is missing."],
- [
- await archive(
- json,
- new Map([...entries].filter(([name]) => !name.endsWith(lut.lut))),
- ),
- "A LUT in this scene is missing.",
- ],
[
await archive({
...json,
@@ -192,6 +183,19 @@ test("scene files reopen the photo with every layer for further editing", async
}),
"Unknown layer kind: text.",
],
+ [
+ await archive({
+ ...json,
+ scene: {
+ ...json.scene,
+ layers: [
+ ...json.scene.layers,
+ { ...lut, id: "short", lut: { ...lut.lut, table: [0, 0, 0] } },
+ ],
+ },
+ }),
+ "The table needs three values per entry",
+ ],
];
for (const [value, message] of invalid) {
await expect(openSceneFile(value, raw.decode)).rejects.toThrow(message);