agentcut 0.2.25 → 0.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +177 -148
  2. package/dist/config.d.ts +0 -1
  3. package/dist/config.js +0 -5
  4. package/dist/config.js.map +1 -1
  5. package/dist/studio/agents/claude.js +3 -2
  6. package/dist/studio/agents/claude.js.map +1 -1
  7. package/dist/studio/chat.js +1 -1
  8. package/dist/studio/chat.js.map +1 -1
  9. package/dist/studio/cli.js +40 -21
  10. package/dist/studio/cli.js.map +1 -1
  11. package/dist/studio/download.d.ts +24 -0
  12. package/dist/studio/download.js +234 -0
  13. package/dist/studio/download.js.map +1 -0
  14. package/dist/studio/host.d.ts +1 -2
  15. package/dist/studio/host.js +36 -8
  16. package/dist/studio/host.js.map +1 -1
  17. package/dist/studio/housekeeping.d.ts +2 -2
  18. package/dist/studio/housekeeping.js +18 -17
  19. package/dist/studio/housekeeping.js.map +1 -1
  20. package/dist/studio/mcp-guides.js +1 -18
  21. package/dist/studio/mcp-guides.js.map +1 -1
  22. package/dist/studio/proc.js +16 -6
  23. package/dist/studio/proc.js.map +1 -1
  24. package/dist/studio/proxies.d.ts +4 -0
  25. package/dist/studio/proxies.js +15 -6
  26. package/dist/studio/proxies.js.map +1 -1
  27. package/dist/studio/release-cursor.js +21 -21
  28. package/dist/studio/release-video.js +10 -10
  29. package/dist/studio/schema.d.ts +0 -1
  30. package/dist/studio/schema.js +0 -1
  31. package/dist/studio/schema.js.map +1 -1
  32. package/dist/studio/tools.d.ts +0 -4
  33. package/dist/studio/tools.js +32 -31
  34. package/dist/studio/tools.js.map +1 -1
  35. package/dist/studio/voice/kokoro-catalog.d.ts +56 -28
  36. package/dist/studio/voice/kokoro-catalog.js +56 -28
  37. package/dist/studio/voice/kokoro-catalog.js.map +1 -1
  38. package/dist/studio/voice/ming-catalog.d.ts +19 -0
  39. package/dist/studio/voice/ming-catalog.js +40 -0
  40. package/dist/studio/voice/ming-catalog.js.map +1 -0
  41. package/dist/studio/voice/ming.d.ts +12 -0
  42. package/dist/studio/voice/ming.js +397 -0
  43. package/dist/studio/voice/ming.js.map +1 -0
  44. package/dist/studio/voice/previews.d.ts +5 -0
  45. package/dist/studio/voice/previews.js +50 -0
  46. package/dist/studio/voice/previews.js.map +1 -0
  47. package/dist/studio/voice/registry.js +2 -0
  48. package/dist/studio/voice/registry.js.map +1 -1
  49. package/dist/studio/voice.d.ts +1 -1
  50. package/dist/studio/voice.js +5 -6
  51. package/dist/studio/voice.js.map +1 -1
  52. package/package.json +56 -56
  53. package/template/AGENTS.md +14 -14
  54. package/template/components/README.md +70 -70
  55. package/template/components/before-after/BeforeAfter.tsx +89 -89
  56. package/template/components/catalog.ts +107 -107
  57. package/template/components/cinematic/Device3D.tsx +324 -324
  58. package/template/components/cinematic/devices3d/display-model.ts +184 -184
  59. package/template/components/cinematic/devices3d/iphone-model.ts +643 -643
  60. package/template/components/cinematic/devices3d/macbook-model.ts +608 -608
  61. package/template/components/cinematic/devices3d/models.ts +657 -657
  62. package/template/components/cinematic/devices3d/runtime.ts +267 -267
  63. package/template/components/cinematic/math.ts +100 -100
  64. package/template/components/color/grade-effect.ts +650 -650
  65. package/template/components/color/grade.ts +512 -512
  66. package/template/components/color/looks.ts +154 -154
  67. package/template/components/countdown/Countdown.tsx +166 -166
  68. package/template/components/dot-trace-title/DotTraceTitle.tsx +181 -181
  69. package/template/components/dot-trace-title/meta.json +51 -51
  70. package/template/components/generate/GenerateReveal.tsx +381 -381
  71. package/template/components/hook-card/HookCard.tsx +554 -554
  72. package/template/components/index.ts +199 -199
  73. package/template/components/lib.ts +191 -191
  74. package/template/components/line-diagram/LineDiagram.tsx +205 -205
  75. package/template/components/line-diagram/meta.json +215 -215
  76. package/template/components/list-card/ListCard.tsx +104 -104
  77. package/template/components/live-clip.ts +75 -75
  78. package/template/components/looks.tsx +1447 -1447
  79. package/template/components/loops/LoopCanvas.tsx +132 -132
  80. package/template/components/loops/engine.ts +184 -184
  81. package/template/components/loops/library.ts +667 -667
  82. package/template/components/loops/library2.ts +777 -777
  83. package/template/components/motion-loop/MotionLoop.tsx +37 -37
  84. package/template/components/motion-loop/meta.json +311 -311
  85. package/template/components/props.ts +73 -73
  86. package/template/components/quote-card/QuoteCard.tsx +71 -71
  87. package/template/components/style-layer.tsx +233 -233
  88. package/template/components/styles.ts +113 -113
  89. package/template/components/types.ts +66 -66
  90. package/template/components/word-pop/WordPop.tsx +59 -59
  91. package/template/components/word-stack/WordStack.tsx +122 -122
  92. package/template/presets/charcoal-sketch/PROMPT.md +48 -48
  93. package/template/presets/charcoal-sketch/scripts/duck_music.py +34 -34
  94. package/template/presets/punk-cut-paper/scenes/Motif.tsx +376 -376
  95. package/template/presets/punk-cut-paper/scenes/Photo.tsx +73 -73
  96. package/template/presets/punk-cut-paper/scenes/Ransom.tsx +119 -119
  97. package/template/runtime/composition.tsx +1189 -1185
  98. package/template/runtime/helpers.tsx +230 -230
  99. package/template/runtime/index.tsx +22 -22
  100. package/template/runtime/types.ts +315 -315
  101. package/template/skill/SKILL.md +186 -351
  102. package/template/skill/references/broll.md +44 -44
  103. package/template/skill/references/browser-export.md +61 -61
  104. package/template/skill/references/cinematic.md +206 -206
  105. package/template/skill/references/color.md +79 -79
  106. package/template/skill/references/craft.md +54 -10
  107. package/template/skill/references/editing-styles.md +57 -57
  108. package/template/skill/references/feature-launch.md +5 -1
  109. package/template/skill/references/footage.md +72 -72
  110. package/template/skill/references/format.md +142 -142
  111. package/template/skill/references/how-to.md +0 -15
  112. package/template/skill/references/launch-direction.md +89 -0
  113. package/template/skill/references/loops.md +151 -151
  114. package/template/skill/references/mcp-external.md +19 -0
  115. package/template/skill/references/performance.md +93 -93
  116. package/template/skill/references/person-cutout.md +19 -19
  117. package/template/skill/references/presets.md +60 -60
  118. package/template/skill/references/product-launch.md +4 -1
  119. package/template/skill/references/release-capture.md +53 -0
  120. package/template/skill/references/sound.md +167 -155
  121. package/template/skill/references/style-spy.md +160 -160
  122. package/template/skill/references/website-howto.md +45 -45
  123. package/template/starter/.studio/chat.json +1 -1
  124. package/template/starter/layers.json +46 -46
  125. package/template/starter/notes.md +4 -4
  126. package/template/starter/project.json +13 -13
  127. package/template/starter/scenes/Title.tsx +38 -38
@@ -1,512 +1,512 @@
1
- // The colour grade model: what a `grade` means, independent of how it is drawn. Pure functions only,
2
- // so the studio, the runtime and the tests all share them. Numbers follow the slider conventions:
3
- // multipliers are neutral at 1, amounts are neutral at 0 and run -1…1 unless noted.
4
-
5
- export type GradeBand = "red" | "orange" | "yellow" | "green" | "aqua" | "blue" | "purple" | "magenta";
6
- export const GRADE_BANDS: GradeBand[] = ["red", "orange", "yellow", "green", "aqua", "blue", "purple", "magenta"];
7
-
8
- /** A colour wheel: x/y push towards a hue on the vectorscope disk (-1…1), level moves the brightness. */
9
- export interface GradeWheel { x?: number; y?: number; level?: number }
10
- export interface GradeWheels { shadows?: GradeWheel; midtones?: GradeWheel; highlights?: GradeWheel }
11
- export type GradeCurvePoint = [number, number];
12
- export interface GradeCurves { master?: GradeCurvePoint[]; r?: GradeCurvePoint[]; g?: GradeCurvePoint[]; b?: GradeCurvePoint[] }
13
- export interface GradeHsl { hue?: number; saturation?: number; luminance?: number }
14
- /** Shot matching result, applied before everything else so a look can sit on top of it. */
15
- export interface GradeMatch { gains?: [number, number, number]; contrast?: number; saturation?: number; anchor?: string }
16
-
17
- export interface GradeFields {
18
- // The original controls, drawn exactly as the CSS filters they started as.
19
- brightness?: number;
20
- contrast?: number;
21
- saturation?: number;
22
- warmth?: number;
23
- hue?: number;
24
- // Primary
25
- /** Stops, -5…5. */
26
- exposure?: number;
27
- temperature?: number;
28
- tint?: number;
29
- highlights?: number;
30
- shadows?: number;
31
- whites?: number;
32
- blacks?: number;
33
- vibrance?: number;
34
- /** Contrast pivot, 0…1. */
35
- pivot?: number;
36
- blackPoint?: number;
37
- whitePoint?: number;
38
- gamma?: number;
39
- wheels?: GradeWheels;
40
- curves?: GradeCurves;
41
- hsl?: Partial<Record<GradeBand, GradeHsl>>;
42
- // Looks
43
- /** Built-in look id (see looks.ts). */
44
- look?: string;
45
- lookStrength?: number;
46
- /** A .cube file in the project ("assets/looks/x.cube"). */
47
- lut?: string;
48
- lutStrength?: number;
49
- /** 0…1: keep skin tones out of the colour changes. */
50
- skinProtect?: number;
51
- match?: GradeMatch;
52
- // Finish
53
- grain?: number;
54
- /** Grain size, 0.5…4 (1 = film-like at 1080p). */
55
- grainSize?: number;
56
- halation?: number;
57
- bloom?: number;
58
- /** -1…1: positive darkens the corners. */
59
- vignette?: number;
60
- }
61
-
62
- /** A grade at one frame (clip-local). `hold` jumps instead of easing into the next key. */
63
- export type GradeKey = GradeFields & { frame: number; hold?: boolean };
64
- export interface ColorGrade extends GradeFields { keys?: GradeKey[] }
65
-
66
- const NEUTRAL: Record<string, number> = {
67
- brightness: 1, contrast: 1, saturation: 1, warmth: 0, hue: 0,
68
- exposure: 0, temperature: 0, tint: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0, vibrance: 0,
69
- pivot: 0.5, blackPoint: 0, whitePoint: 1, gamma: 1,
70
- skinProtect: 0, grain: 0, grainSize: 1, halation: 0, bloom: 0, vignette: 0,
71
- lookStrength: 1, lutStrength: 1,
72
- };
73
- const NUMERIC_FIELDS = Object.keys(NEUTRAL);
74
- const LEGACY_FIELDS = new Set(["brightness", "contrast", "saturation", "warmth", "hue"]);
75
- const FINISH_FIELDS = ["grain", "grainSize", "halation", "bloom", "vignette"] as const;
76
- /** These only change how the other fields act, so alone they change nothing. */
77
- const MODIFIER_FIELDS = new Set(["lookStrength", "lutStrength", "pivot", "grainSize", "skinProtect"]);
78
-
79
- const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
80
- const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v));
81
-
82
- function isNeutralWheel(w?: GradeWheel) {
83
- return !w || (!w.x && !w.y && !w.level);
84
- }
85
-
86
- function curveIsIdentity(points?: GradeCurvePoint[]) {
87
- return !points || points.length < 2 || points.every(([x, y]) => Math.abs(x - y) < 1e-4);
88
- }
89
-
90
- export function hasCurves(fields: GradeFields): boolean {
91
- const c = fields.curves;
92
- return Boolean(c && !(curveIsIdentity(c.master) && curveIsIdentity(c.r) && curveIsIdentity(c.g) && curveIsIdentity(c.b)));
93
- }
94
-
95
- /** True when these fields change nothing. */
96
- export function isNeutralGrade(grade: ColorGrade | undefined | null): boolean {
97
- if (!grade) return true;
98
- if (grade.keys?.length || grade.look || grade.lut || grade.match) return false;
99
- for (const key of NUMERIC_FIELDS) {
100
- if (MODIFIER_FIELDS.has(key)) continue;
101
- const value = grade[key as keyof GradeFields] as number | undefined;
102
- if (value !== undefined && Math.abs(value - NEUTRAL[key]) > 1e-6) return false;
103
- }
104
- const w = grade.wheels;
105
- if (w && !(isNeutralWheel(w.shadows) && isNeutralWheel(w.midtones) && isNeutralWheel(w.highlights))) return false;
106
- if (hasCurves(grade)) return false;
107
- if (grade.hsl && Object.values(grade.hsl).some((b) => b && (b.hue || b.saturation || b.luminance))) return false;
108
- return true;
109
- }
110
-
111
- /** True when the grade only uses the original five controls, which stay on CSS filters. */
112
- export function isCssGrade(grade: ColorGrade | undefined | null): boolean {
113
- if (!grade) return true;
114
- return Object.entries(grade).every(([key, value]) => value === undefined || LEGACY_FIELDS.has(key));
115
- }
116
-
117
- /** CSS filter for the original five controls. */
118
- export function gradeCssFilter(grade: ColorGrade | undefined | null): string | undefined {
119
- if (!grade) return undefined;
120
- const parts: string[] = [];
121
- if (grade.brightness !== undefined && grade.brightness !== 1) parts.push(`brightness(${grade.brightness})`);
122
- if (grade.contrast !== undefined && grade.contrast !== 1) parts.push(`contrast(${grade.contrast})`);
123
- if (grade.saturation !== undefined && grade.saturation !== 1) parts.push(`saturate(${grade.saturation})`);
124
- const warmth = grade.warmth ?? 0;
125
- if (warmth > 0) parts.push(`sepia(${(warmth * 0.35).toFixed(3)})`, `saturate(${(1 + warmth * 0.25).toFixed(3)})`);
126
- const hue = (grade.hue ?? 0) + (warmth < 0 ? warmth * -12 : warmth * -4);
127
- if (hue) parts.push(`hue-rotate(${hue.toFixed(1)}deg)`);
128
- return parts.length ? parts.join(" ") : undefined;
129
- }
130
-
131
- function mixWheel(a: GradeWheel | undefined, b: GradeWheel | undefined, t: number): GradeWheel {
132
- return { x: lerp(a?.x ?? 0, b?.x ?? 0, t), y: lerp(a?.y ?? 0, b?.y ?? 0, t), level: lerp(a?.level ?? 0, b?.level ?? 0, t) };
133
- }
134
-
135
- /** Fields between `a` and `b`. Numbers, wheels and the colour mixer ease; curves and files switch halfway. */
136
- export function mixGrades(a: GradeFields, b: GradeFields, t: number): GradeFields {
137
- const out: GradeFields = t < 0.5 ? { ...a } : { ...b };
138
- for (const key of NUMERIC_FIELDS) {
139
- const from = a[key as keyof GradeFields] as number | undefined;
140
- const to = b[key as keyof GradeFields] as number | undefined;
141
- if (from === undefined && to === undefined) continue;
142
- (out as Record<string, unknown>)[key] = lerp(from ?? NEUTRAL[key], to ?? NEUTRAL[key], t);
143
- }
144
- if (a.wheels || b.wheels) {
145
- out.wheels = {
146
- shadows: mixWheel(a.wheels?.shadows, b.wheels?.shadows, t),
147
- midtones: mixWheel(a.wheels?.midtones, b.wheels?.midtones, t),
148
- highlights: mixWheel(a.wheels?.highlights, b.wheels?.highlights, t),
149
- };
150
- }
151
- if (a.hsl || b.hsl) {
152
- out.hsl = {};
153
- for (const band of GRADE_BANDS) {
154
- const x = a.hsl?.[band];
155
- const y = b.hsl?.[band];
156
- if (!x && !y) continue;
157
- out.hsl[band] = {
158
- hue: lerp(x?.hue ?? 0, y?.hue ?? 0, t),
159
- saturation: lerp(x?.saturation ?? 0, y?.saturation ?? 0, t),
160
- luminance: lerp(x?.luminance ?? 0, y?.luminance ?? 0, t),
161
- };
162
- }
163
- }
164
- return out;
165
- }
166
-
167
- const smooth = (t: number) => t * t * (3 - 2 * t);
168
-
169
- /** The grade at a clip-local frame: keys ease over the base fields (a key only overrides what it names). */
170
- export function gradeAtFrame(grade: ColorGrade, frame: number): GradeFields {
171
- const { keys, ...base } = grade;
172
- if (!keys?.length) return base;
173
- const sorted = [...keys].sort((a, b) => a.frame - b.frame);
174
- const fieldsOf = (key: GradeKey): GradeFields => {
175
- const fields: GradeFields & { frame?: number; hold?: boolean } = { ...base, ...key };
176
- delete fields.frame;
177
- delete fields.hold;
178
- return fields;
179
- };
180
- if (frame <= sorted[0].frame) return fieldsOf(sorted[0]);
181
- const last = sorted[sorted.length - 1];
182
- if (frame >= last.frame) return fieldsOf(last);
183
- const nextIndex = sorted.findIndex((key) => key.frame > frame);
184
- const from = sorted[nextIndex - 1];
185
- const to = sorted[nextIndex];
186
- if (from.hold) return fieldsOf(from);
187
- return mixGrades(fieldsOf(from), fieldsOf(to), smooth((frame - from.frame) / (to.frame - from.frame)));
188
- }
189
-
190
- /** Fields scaled towards neutral: strength 0 changes nothing, 1 is the fields as written. */
191
- export function scaleGrade(fields: GradeFields, strength: number): GradeFields {
192
- if (strength >= 1) return fields;
193
- const out = mixGrades({}, fields, strength);
194
- out.look = fields.look;
195
- out.lut = fields.lut;
196
- out.lutStrength = fields.lut ? (fields.lutStrength ?? 1) * strength : undefined;
197
- if (fields.curves) {
198
- const scale = (points?: GradeCurvePoint[]) =>
199
- points?.map(([x, y]): GradeCurvePoint => [x, lerp(x, y, strength)]);
200
- out.curves = { master: scale(fields.curves.master), r: scale(fields.curves.r), g: scale(fields.curves.g), b: scale(fields.curves.b) };
201
- }
202
- if (fields.match) out.match = fields.match;
203
- return out;
204
- }
205
-
206
- export type GradeLookResolver = (id: string) => GradeFields | null;
207
-
208
- /**
209
- * The draw passes of one grade at a frame: the correction first, then the look on top. The finish
210
- * (grain, halation, …) moves to the last pass so a look never tints the grain.
211
- */
212
- export function gradePasses(grade: ColorGrade, frame: number, resolveLook: GradeLookResolver): GradeFields[] {
213
- const fields = gradeAtFrame(grade, frame);
214
- const { look: lookId, lookStrength, ...primary } = fields;
215
- const look = lookId ? resolveLook(lookId) : null;
216
- if (!look) return isNeutralGrade(primary) ? [] : [primary];
217
- const scaled = scaleGrade(look, lookStrength ?? 1);
218
- const finish: GradeFields = {};
219
- for (const key of FINISH_FIELDS) {
220
- const value = primary[key] ?? scaled[key];
221
- if (value !== undefined) finish[key] = value;
222
- delete primary[key];
223
- }
224
- const passes: GradeFields[] = [];
225
- if (!isNeutralGrade(primary)) passes.push(primary);
226
- passes.push({ ...scaled, ...finish });
227
- return passes;
228
- }
229
-
230
- // ---------------------------------------------------------------------------
231
- // Curves: a monotone cubic through the points, so a curve never overshoots or folds back.
232
-
233
- function sortedCurve(points: GradeCurvePoint[]): GradeCurvePoint[] {
234
- const sorted = points
235
- .filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y))
236
- .map(([x, y]): GradeCurvePoint => [clamp(x, 0, 1), clamp(y, 0, 1)])
237
- .sort((a, b) => a[0] - b[0]);
238
- const unique: GradeCurvePoint[] = [];
239
- for (const point of sorted) {
240
- if (unique.length && point[0] - unique[unique.length - 1][0] < 1e-4) unique[unique.length - 1] = point;
241
- else unique.push(point);
242
- }
243
- if (!unique.length) return [[0, 0], [1, 1]];
244
- if (unique[0][0] > 0) unique.unshift([0, unique[0][1]]);
245
- if (unique[unique.length - 1][0] < 1) unique.push([1, unique[unique.length - 1][1]]);
246
- return unique;
247
- }
248
-
249
- /** Sample a curve at `size` evenly spaced inputs (Fritsch–Carlson monotone cubic). */
250
- export function bakeCurve(points: GradeCurvePoint[] | undefined, size = 1024): Float32Array {
251
- const out = new Float32Array(size);
252
- const curve = sortedCurve(points?.length ? points : [[0, 0], [1, 1]]);
253
- const n = curve.length;
254
- const dx: number[] = [];
255
- const slope: number[] = [];
256
- for (let i = 0; i < n - 1; i += 1) {
257
- dx.push(curve[i + 1][0] - curve[i][0]);
258
- slope.push((curve[i + 1][1] - curve[i][1]) / dx[i]);
259
- }
260
- const m: number[] = new Array(n).fill(0);
261
- m[0] = slope[0];
262
- m[n - 1] = slope[n - 2];
263
- for (let i = 1; i < n - 1; i += 1) m[i] = slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2;
264
- for (let i = 0; i < n - 1; i += 1) {
265
- if (slope[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; }
266
- const a = m[i] / slope[i];
267
- const b = m[i + 1] / slope[i];
268
- const s = a * a + b * b;
269
- if (s > 9) {
270
- const t = 3 / Math.sqrt(s);
271
- m[i] = t * a * slope[i];
272
- m[i + 1] = t * b * slope[i];
273
- }
274
- }
275
- let segment = 0;
276
- for (let i = 0; i < size; i += 1) {
277
- const x = i / (size - 1);
278
- while (segment < n - 2 && x > curve[segment + 1][0]) segment += 1;
279
- const h = dx[segment];
280
- const t = (x - curve[segment][0]) / h;
281
- const t2 = t * t;
282
- const t3 = t2 * t;
283
- const y =
284
- (2 * t3 - 3 * t2 + 1) * curve[segment][1] +
285
- (t3 - 2 * t2 + t) * h * m[segment] +
286
- (-2 * t3 + 3 * t2) * curve[segment + 1][1] +
287
- (t3 - t2) * h * m[segment + 1];
288
- out[i] = clamp(y, 0, 1);
289
- }
290
- return out;
291
- }
292
-
293
- // ---------------------------------------------------------------------------
294
- // .cube files
295
-
296
- export interface CubeLut {
297
- size: number;
298
- domainMin: [number, number, number];
299
- domainMax: [number, number, number];
300
- /** RGBA floats, red changing fastest (the order WebGL's 3D textures want). */
301
- data: Float32Array;
302
- }
303
-
304
- export const MAX_CUBE_SIZE = 65;
305
-
306
- /** Parse a 3D .cube file. Throws a readable error on anything else, including 1D LUTs. */
307
- export function parseCube(text: string): CubeLut {
308
- let size = 0;
309
- let domainMin: [number, number, number] = [0, 0, 0];
310
- let domainMax: [number, number, number] = [1, 1, 1];
311
- let data: Float32Array | null = null;
312
- let filled = 0;
313
- for (const raw of text.split(/\r?\n/)) {
314
- const line = raw.trim();
315
- if (!line || line.startsWith("#")) continue;
316
- const head = line.split(/\s+/, 1)[0].toUpperCase();
317
- if (head === "TITLE") continue;
318
- if (head === "LUT_1D_SIZE") throw new Error("This is a 1D LUT. Only 3D .cube files are supported.");
319
- if (head === "LUT_3D_SIZE") {
320
- size = Number(line.split(/\s+/)[1]);
321
- if (!Number.isInteger(size) || size < 2 || size > MAX_CUBE_SIZE)
322
- throw new Error(`LUT_3D_SIZE must be between 2 and ${MAX_CUBE_SIZE}.`);
323
- data = new Float32Array(size * size * size * 4);
324
- continue;
325
- }
326
- if (head === "DOMAIN_MIN" || head === "DOMAIN_MAX") {
327
- const values = line.split(/\s+/).slice(1).map(Number);
328
- if (values.length !== 3 || values.some((v) => !Number.isFinite(v))) throw new Error(`${head} needs three numbers.`);
329
- if (head === "DOMAIN_MIN") domainMin = values as [number, number, number];
330
- else domainMax = values as [number, number, number];
331
- continue;
332
- }
333
- if (!/^[-+.\d]/.test(head)) continue;
334
- if (!data) throw new Error("This .cube file has values before LUT_3D_SIZE.");
335
- const values = line.split(/\s+/).map(Number);
336
- if (values.length < 3 || values.slice(0, 3).some((v) => !Number.isFinite(v))) throw new Error("This .cube file has an unreadable row.");
337
- if (filled >= size * size * size) throw new Error("This .cube file has too many rows for its LUT_3D_SIZE.");
338
- data.set([values[0], values[1], values[2], 1], filled * 4);
339
- filled += 1;
340
- }
341
- if (!data) throw new Error("This doesn't look like a .cube file (no LUT_3D_SIZE).");
342
- if (filled !== size * size * size) throw new Error(`This .cube file is incomplete: ${filled} of ${size * size * size} rows.`);
343
- if (domainMin.some((v, i) => v >= domainMax[i])) throw new Error("DOMAIN_MIN must be below DOMAIN_MAX.");
344
- return { size, domainMin, domainMax, data };
345
- }
346
-
347
- /** Write a .cube file from `lut(r, g, b)`. Values are 0…1 inputs and outputs. */
348
- export function serializeCube(size: number, title: string, lut: (r: number, g: number, b: number) => [number, number, number]): string {
349
- const rows = [`TITLE "${title.replace(/["\r\n]/g, " ")}"`, `LUT_3D_SIZE ${size}`, ""];
350
- const last = size - 1;
351
- for (let b = 0; b < size; b += 1)
352
- for (let g = 0; g < size; g += 1)
353
- for (let r = 0; r < size; r += 1) {
354
- const [x, y, z] = lut(r / last, g / last, b / last);
355
- rows.push(`${clamp(x, 0, 1).toFixed(6)} ${clamp(y, 0, 1).toFixed(6)} ${clamp(z, 0, 1).toFixed(6)}`);
356
- }
357
- return `${rows.join("\n")}\n`;
358
- }
359
-
360
- // ---------------------------------------------------------------------------
361
- // Uniforms: the fields as the numbers the shader reads.
362
-
363
- export type Vec3 = [number, number, number];
364
- const REC709: Vec3 = [0.2126, 0.7152, 0.0722];
365
-
366
- /** Rows of a 3×3 matrix. */
367
- type Mat3 = [Vec3, Vec3, Vec3];
368
- const IDENTITY: Mat3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
369
-
370
- function multiply(a: Mat3, b: Mat3): Mat3 {
371
- return a.map((row) =>
372
- [0, 1, 2].map((c) => row[0] * b[0][c] + row[1] * b[1][c] + row[2] * b[2][c]),
373
- ) as Mat3;
374
- }
375
-
376
- // The matrices from the CSS filter effects spec, so the GPU draws the same picture as the CSS path.
377
- function saturateMatrix(s: number): Mat3 {
378
- return [
379
- [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s],
380
- [0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s],
381
- [0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s],
382
- ];
383
- }
384
-
385
- function sepiaMatrix(a: number): Mat3 {
386
- const k = 1 - a;
387
- return [
388
- [0.393 + 0.607 * k, 0.769 - 0.769 * k, 0.189 - 0.189 * k],
389
- [0.349 - 0.349 * k, 0.686 + 0.314 * k, 0.168 - 0.168 * k],
390
- [0.272 - 0.272 * k, 0.534 - 0.534 * k, 0.131 + 0.869 * k],
391
- ];
392
- }
393
-
394
- function hueMatrix(degrees: number): Mat3 {
395
- const r = (degrees * Math.PI) / 180;
396
- const c = Math.cos(r);
397
- const s = Math.sin(r);
398
- return [
399
- [0.213 + c * 0.787 - s * 0.213, 0.715 - c * 0.715 - s * 0.715, 0.072 - c * 0.072 + s * 0.928],
400
- [0.213 - c * 0.213 + s * 0.143, 0.715 + c * 0.285 + s * 0.14, 0.072 - c * 0.072 - s * 0.283],
401
- [0.213 - c * 0.213 - s * 0.787, 0.715 - c * 0.715 + s * 0.715, 0.072 + c * 0.928 + s * 0.072],
402
- ];
403
- }
404
-
405
- /** Direction of a wheel's push as an RGB offset that keeps brightness about the same. */
406
- function wheelRgb(wheel: GradeWheel | undefined): Vec3 {
407
- const x = wheel?.x ?? 0;
408
- const y = wheel?.y ?? 0;
409
- return [x, -0.5 * x + 0.866 * y, -0.5 * x - 0.866 * y];
410
- }
411
-
412
- /** White balance as linear channel gains, normalised to keep brightness. */
413
- function whiteBalanceGains(temperature: number, tint: number): Vec3 {
414
- const r = Math.pow(2, temperature * 0.7 + tint * 0.2);
415
- const g = Math.pow(2, -tint * 0.5);
416
- const b = Math.pow(2, -temperature * 0.7 + tint * 0.2);
417
- const y = REC709[0] * r + REC709[1] * g + REC709[2] * b;
418
- return [r / y, g / y, b / y];
419
- }
420
-
421
- export interface GradeUniforms {
422
- brightness: number;
423
- contrast: number;
424
- pivot: number;
425
- /** Rows: saturate, warmth and hue as one matrix. */
426
- matrix: Mat3;
427
- gains: Vec3;
428
- matchContrast: number;
429
- matchSaturation: number;
430
- shadows: number;
431
- highlights: number;
432
- whites: number;
433
- blacks: number;
434
- blackPoint: number;
435
- whitePoint: number;
436
- gamma: number;
437
- lift: Vec3;
438
- wheelGamma: Vec3;
439
- gain: Vec3;
440
- vibrance: number;
441
- /** One [hue, saturation, luminance] per band in GRADE_BANDS order. */
442
- hsl: number[];
443
- hasHsl: boolean;
444
- skinProtect: number;
445
- lutStrength: number;
446
- grain: number;
447
- grainSize: number;
448
- halation: number;
449
- bloom: number;
450
- vignette: number;
451
- }
452
-
453
- export function gradeUniforms(fields: GradeFields): GradeUniforms {
454
- const warmth = fields.warmth ?? 0;
455
- let matrix = IDENTITY;
456
- const saturation = fields.saturation ?? 1;
457
- if (saturation !== 1) matrix = multiply(saturateMatrix(saturation), matrix);
458
- if (warmth > 0) {
459
- matrix = multiply(sepiaMatrix(warmth * 0.35), matrix);
460
- matrix = multiply(saturateMatrix(1 + warmth * 0.25), matrix);
461
- }
462
- const hue = (fields.hue ?? 0) + (warmth < 0 ? warmth * -12 : warmth * -4);
463
- if (hue) matrix = multiply(hueMatrix(hue), matrix);
464
-
465
- const exposure = Math.pow(2, fields.exposure ?? 0);
466
- const wb = whiteBalanceGains(fields.temperature ?? 0, fields.tint ?? 0);
467
- const match = fields.match?.gains ?? [1, 1, 1];
468
- const gains = wb.map((g, i) => g * exposure * match[i]) as Vec3;
469
-
470
- const wheels = fields.wheels;
471
- const lift = wheelRgb(wheels?.shadows).map((v) => v * 0.12 + (wheels?.shadows?.level ?? 0) * 0.12) as Vec3;
472
- const wheelGamma = wheelRgb(wheels?.midtones).map((v) => clamp(1 + v * 0.35 + (wheels?.midtones?.level ?? 0) * 0.45, 0.2, 3)) as Vec3;
473
- const gain = wheelRgb(wheels?.highlights).map((v) => Math.max(0, 1 + v * 0.3 + (wheels?.highlights?.level ?? 0) * 0.4)) as Vec3;
474
-
475
- let hasHsl = false;
476
- const hsl: number[] = [];
477
- for (const band of GRADE_BANDS) {
478
- const entry = fields.hsl?.[band];
479
- hsl.push(entry?.hue ?? 0, entry?.saturation ?? 0, entry?.luminance ?? 0);
480
- if (entry?.hue || entry?.saturation || entry?.luminance) hasHsl = true;
481
- }
482
-
483
- return {
484
- brightness: fields.brightness ?? 1,
485
- contrast: fields.contrast ?? 1,
486
- pivot: fields.pivot ?? 0.5,
487
- matrix,
488
- gains,
489
- matchContrast: fields.match?.contrast ?? 1,
490
- matchSaturation: fields.match?.saturation ?? 1,
491
- shadows: fields.shadows ?? 0,
492
- highlights: fields.highlights ?? 0,
493
- whites: fields.whites ?? 0,
494
- blacks: fields.blacks ?? 0,
495
- blackPoint: fields.blackPoint ?? 0,
496
- whitePoint: Math.max((fields.blackPoint ?? 0) + 0.001, fields.whitePoint ?? 1),
497
- gamma: Math.max(0.01, fields.gamma ?? 1),
498
- lift,
499
- wheelGamma,
500
- gain,
501
- vibrance: fields.vibrance ?? 0,
502
- hsl,
503
- hasHsl,
504
- skinProtect: fields.skinProtect ?? 0,
505
- lutStrength: fields.lut ? clamp(fields.lutStrength ?? 1, 0, 1) : 0,
506
- grain: fields.grain ?? 0,
507
- grainSize: fields.grainSize ?? 1,
508
- halation: fields.halation ?? 0,
509
- bloom: fields.bloom ?? 0,
510
- vignette: fields.vignette ?? 0,
511
- };
512
- }
1
+ // The colour grade model: what a `grade` means, independent of how it is drawn. Pure functions only,
2
+ // so the studio, the runtime and the tests all share them. Numbers follow the slider conventions:
3
+ // multipliers are neutral at 1, amounts are neutral at 0 and run -1…1 unless noted.
4
+
5
+ export type GradeBand = "red" | "orange" | "yellow" | "green" | "aqua" | "blue" | "purple" | "magenta";
6
+ export const GRADE_BANDS: GradeBand[] = ["red", "orange", "yellow", "green", "aqua", "blue", "purple", "magenta"];
7
+
8
+ /** A colour wheel: x/y push towards a hue on the vectorscope disk (-1…1), level moves the brightness. */
9
+ export interface GradeWheel { x?: number; y?: number; level?: number }
10
+ export interface GradeWheels { shadows?: GradeWheel; midtones?: GradeWheel; highlights?: GradeWheel }
11
+ export type GradeCurvePoint = [number, number];
12
+ export interface GradeCurves { master?: GradeCurvePoint[]; r?: GradeCurvePoint[]; g?: GradeCurvePoint[]; b?: GradeCurvePoint[] }
13
+ export interface GradeHsl { hue?: number; saturation?: number; luminance?: number }
14
+ /** Shot matching result, applied before everything else so a look can sit on top of it. */
15
+ export interface GradeMatch { gains?: [number, number, number]; contrast?: number; saturation?: number; anchor?: string }
16
+
17
+ export interface GradeFields {
18
+ // The original controls, drawn exactly as the CSS filters they started as.
19
+ brightness?: number;
20
+ contrast?: number;
21
+ saturation?: number;
22
+ warmth?: number;
23
+ hue?: number;
24
+ // Primary
25
+ /** Stops, -5…5. */
26
+ exposure?: number;
27
+ temperature?: number;
28
+ tint?: number;
29
+ highlights?: number;
30
+ shadows?: number;
31
+ whites?: number;
32
+ blacks?: number;
33
+ vibrance?: number;
34
+ /** Contrast pivot, 0…1. */
35
+ pivot?: number;
36
+ blackPoint?: number;
37
+ whitePoint?: number;
38
+ gamma?: number;
39
+ wheels?: GradeWheels;
40
+ curves?: GradeCurves;
41
+ hsl?: Partial<Record<GradeBand, GradeHsl>>;
42
+ // Looks
43
+ /** Built-in look id (see looks.ts). */
44
+ look?: string;
45
+ lookStrength?: number;
46
+ /** A .cube file in the project ("assets/looks/x.cube"). */
47
+ lut?: string;
48
+ lutStrength?: number;
49
+ /** 0…1: keep skin tones out of the colour changes. */
50
+ skinProtect?: number;
51
+ match?: GradeMatch;
52
+ // Finish
53
+ grain?: number;
54
+ /** Grain size, 0.5…4 (1 = film-like at 1080p). */
55
+ grainSize?: number;
56
+ halation?: number;
57
+ bloom?: number;
58
+ /** -1…1: positive darkens the corners. */
59
+ vignette?: number;
60
+ }
61
+
62
+ /** A grade at one frame (clip-local). `hold` jumps instead of easing into the next key. */
63
+ export type GradeKey = GradeFields & { frame: number; hold?: boolean };
64
+ export interface ColorGrade extends GradeFields { keys?: GradeKey[] }
65
+
66
+ const NEUTRAL: Record<string, number> = {
67
+ brightness: 1, contrast: 1, saturation: 1, warmth: 0, hue: 0,
68
+ exposure: 0, temperature: 0, tint: 0, highlights: 0, shadows: 0, whites: 0, blacks: 0, vibrance: 0,
69
+ pivot: 0.5, blackPoint: 0, whitePoint: 1, gamma: 1,
70
+ skinProtect: 0, grain: 0, grainSize: 1, halation: 0, bloom: 0, vignette: 0,
71
+ lookStrength: 1, lutStrength: 1,
72
+ };
73
+ const NUMERIC_FIELDS = Object.keys(NEUTRAL);
74
+ const LEGACY_FIELDS = new Set(["brightness", "contrast", "saturation", "warmth", "hue"]);
75
+ const FINISH_FIELDS = ["grain", "grainSize", "halation", "bloom", "vignette"] as const;
76
+ /** These only change how the other fields act, so alone they change nothing. */
77
+ const MODIFIER_FIELDS = new Set(["lookStrength", "lutStrength", "pivot", "grainSize", "skinProtect"]);
78
+
79
+ const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
80
+ const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v));
81
+
82
+ function isNeutralWheel(w?: GradeWheel) {
83
+ return !w || (!w.x && !w.y && !w.level);
84
+ }
85
+
86
+ function curveIsIdentity(points?: GradeCurvePoint[]) {
87
+ return !points || points.length < 2 || points.every(([x, y]) => Math.abs(x - y) < 1e-4);
88
+ }
89
+
90
+ export function hasCurves(fields: GradeFields): boolean {
91
+ const c = fields.curves;
92
+ return Boolean(c && !(curveIsIdentity(c.master) && curveIsIdentity(c.r) && curveIsIdentity(c.g) && curveIsIdentity(c.b)));
93
+ }
94
+
95
+ /** True when these fields change nothing. */
96
+ export function isNeutralGrade(grade: ColorGrade | undefined | null): boolean {
97
+ if (!grade) return true;
98
+ if (grade.keys?.length || grade.look || grade.lut || grade.match) return false;
99
+ for (const key of NUMERIC_FIELDS) {
100
+ if (MODIFIER_FIELDS.has(key)) continue;
101
+ const value = grade[key as keyof GradeFields] as number | undefined;
102
+ if (value !== undefined && Math.abs(value - NEUTRAL[key]) > 1e-6) return false;
103
+ }
104
+ const w = grade.wheels;
105
+ if (w && !(isNeutralWheel(w.shadows) && isNeutralWheel(w.midtones) && isNeutralWheel(w.highlights))) return false;
106
+ if (hasCurves(grade)) return false;
107
+ if (grade.hsl && Object.values(grade.hsl).some((b) => b && (b.hue || b.saturation || b.luminance))) return false;
108
+ return true;
109
+ }
110
+
111
+ /** True when the grade only uses the original five controls, which stay on CSS filters. */
112
+ export function isCssGrade(grade: ColorGrade | undefined | null): boolean {
113
+ if (!grade) return true;
114
+ return Object.entries(grade).every(([key, value]) => value === undefined || LEGACY_FIELDS.has(key));
115
+ }
116
+
117
+ /** CSS filter for the original five controls. */
118
+ export function gradeCssFilter(grade: ColorGrade | undefined | null): string | undefined {
119
+ if (!grade) return undefined;
120
+ const parts: string[] = [];
121
+ if (grade.brightness !== undefined && grade.brightness !== 1) parts.push(`brightness(${grade.brightness})`);
122
+ if (grade.contrast !== undefined && grade.contrast !== 1) parts.push(`contrast(${grade.contrast})`);
123
+ if (grade.saturation !== undefined && grade.saturation !== 1) parts.push(`saturate(${grade.saturation})`);
124
+ const warmth = grade.warmth ?? 0;
125
+ if (warmth > 0) parts.push(`sepia(${(warmth * 0.35).toFixed(3)})`, `saturate(${(1 + warmth * 0.25).toFixed(3)})`);
126
+ const hue = (grade.hue ?? 0) + (warmth < 0 ? warmth * -12 : warmth * -4);
127
+ if (hue) parts.push(`hue-rotate(${hue.toFixed(1)}deg)`);
128
+ return parts.length ? parts.join(" ") : undefined;
129
+ }
130
+
131
+ function mixWheel(a: GradeWheel | undefined, b: GradeWheel | undefined, t: number): GradeWheel {
132
+ return { x: lerp(a?.x ?? 0, b?.x ?? 0, t), y: lerp(a?.y ?? 0, b?.y ?? 0, t), level: lerp(a?.level ?? 0, b?.level ?? 0, t) };
133
+ }
134
+
135
+ /** Fields between `a` and `b`. Numbers, wheels and the colour mixer ease; curves and files switch halfway. */
136
+ export function mixGrades(a: GradeFields, b: GradeFields, t: number): GradeFields {
137
+ const out: GradeFields = t < 0.5 ? { ...a } : { ...b };
138
+ for (const key of NUMERIC_FIELDS) {
139
+ const from = a[key as keyof GradeFields] as number | undefined;
140
+ const to = b[key as keyof GradeFields] as number | undefined;
141
+ if (from === undefined && to === undefined) continue;
142
+ (out as Record<string, unknown>)[key] = lerp(from ?? NEUTRAL[key], to ?? NEUTRAL[key], t);
143
+ }
144
+ if (a.wheels || b.wheels) {
145
+ out.wheels = {
146
+ shadows: mixWheel(a.wheels?.shadows, b.wheels?.shadows, t),
147
+ midtones: mixWheel(a.wheels?.midtones, b.wheels?.midtones, t),
148
+ highlights: mixWheel(a.wheels?.highlights, b.wheels?.highlights, t),
149
+ };
150
+ }
151
+ if (a.hsl || b.hsl) {
152
+ out.hsl = {};
153
+ for (const band of GRADE_BANDS) {
154
+ const x = a.hsl?.[band];
155
+ const y = b.hsl?.[band];
156
+ if (!x && !y) continue;
157
+ out.hsl[band] = {
158
+ hue: lerp(x?.hue ?? 0, y?.hue ?? 0, t),
159
+ saturation: lerp(x?.saturation ?? 0, y?.saturation ?? 0, t),
160
+ luminance: lerp(x?.luminance ?? 0, y?.luminance ?? 0, t),
161
+ };
162
+ }
163
+ }
164
+ return out;
165
+ }
166
+
167
+ const smooth = (t: number) => t * t * (3 - 2 * t);
168
+
169
+ /** The grade at a clip-local frame: keys ease over the base fields (a key only overrides what it names). */
170
+ export function gradeAtFrame(grade: ColorGrade, frame: number): GradeFields {
171
+ const { keys, ...base } = grade;
172
+ if (!keys?.length) return base;
173
+ const sorted = [...keys].sort((a, b) => a.frame - b.frame);
174
+ const fieldsOf = (key: GradeKey): GradeFields => {
175
+ const fields: GradeFields & { frame?: number; hold?: boolean } = { ...base, ...key };
176
+ delete fields.frame;
177
+ delete fields.hold;
178
+ return fields;
179
+ };
180
+ if (frame <= sorted[0].frame) return fieldsOf(sorted[0]);
181
+ const last = sorted[sorted.length - 1];
182
+ if (frame >= last.frame) return fieldsOf(last);
183
+ const nextIndex = sorted.findIndex((key) => key.frame > frame);
184
+ const from = sorted[nextIndex - 1];
185
+ const to = sorted[nextIndex];
186
+ if (from.hold) return fieldsOf(from);
187
+ return mixGrades(fieldsOf(from), fieldsOf(to), smooth((frame - from.frame) / (to.frame - from.frame)));
188
+ }
189
+
190
+ /** Fields scaled towards neutral: strength 0 changes nothing, 1 is the fields as written. */
191
+ export function scaleGrade(fields: GradeFields, strength: number): GradeFields {
192
+ if (strength >= 1) return fields;
193
+ const out = mixGrades({}, fields, strength);
194
+ out.look = fields.look;
195
+ out.lut = fields.lut;
196
+ out.lutStrength = fields.lut ? (fields.lutStrength ?? 1) * strength : undefined;
197
+ if (fields.curves) {
198
+ const scale = (points?: GradeCurvePoint[]) =>
199
+ points?.map(([x, y]): GradeCurvePoint => [x, lerp(x, y, strength)]);
200
+ out.curves = { master: scale(fields.curves.master), r: scale(fields.curves.r), g: scale(fields.curves.g), b: scale(fields.curves.b) };
201
+ }
202
+ if (fields.match) out.match = fields.match;
203
+ return out;
204
+ }
205
+
206
+ export type GradeLookResolver = (id: string) => GradeFields | null;
207
+
208
+ /**
209
+ * The draw passes of one grade at a frame: the correction first, then the look on top. The finish
210
+ * (grain, halation, …) moves to the last pass so a look never tints the grain.
211
+ */
212
+ export function gradePasses(grade: ColorGrade, frame: number, resolveLook: GradeLookResolver): GradeFields[] {
213
+ const fields = gradeAtFrame(grade, frame);
214
+ const { look: lookId, lookStrength, ...primary } = fields;
215
+ const look = lookId ? resolveLook(lookId) : null;
216
+ if (!look) return isNeutralGrade(primary) ? [] : [primary];
217
+ const scaled = scaleGrade(look, lookStrength ?? 1);
218
+ const finish: GradeFields = {};
219
+ for (const key of FINISH_FIELDS) {
220
+ const value = primary[key] ?? scaled[key];
221
+ if (value !== undefined) finish[key] = value;
222
+ delete primary[key];
223
+ }
224
+ const passes: GradeFields[] = [];
225
+ if (!isNeutralGrade(primary)) passes.push(primary);
226
+ passes.push({ ...scaled, ...finish });
227
+ return passes;
228
+ }
229
+
230
+ // ---------------------------------------------------------------------------
231
+ // Curves: a monotone cubic through the points, so a curve never overshoots or folds back.
232
+
233
+ function sortedCurve(points: GradeCurvePoint[]): GradeCurvePoint[] {
234
+ const sorted = points
235
+ .filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y))
236
+ .map(([x, y]): GradeCurvePoint => [clamp(x, 0, 1), clamp(y, 0, 1)])
237
+ .sort((a, b) => a[0] - b[0]);
238
+ const unique: GradeCurvePoint[] = [];
239
+ for (const point of sorted) {
240
+ if (unique.length && point[0] - unique[unique.length - 1][0] < 1e-4) unique[unique.length - 1] = point;
241
+ else unique.push(point);
242
+ }
243
+ if (!unique.length) return [[0, 0], [1, 1]];
244
+ if (unique[0][0] > 0) unique.unshift([0, unique[0][1]]);
245
+ if (unique[unique.length - 1][0] < 1) unique.push([1, unique[unique.length - 1][1]]);
246
+ return unique;
247
+ }
248
+
249
+ /** Sample a curve at `size` evenly spaced inputs (Fritsch–Carlson monotone cubic). */
250
+ export function bakeCurve(points: GradeCurvePoint[] | undefined, size = 1024): Float32Array {
251
+ const out = new Float32Array(size);
252
+ const curve = sortedCurve(points?.length ? points : [[0, 0], [1, 1]]);
253
+ const n = curve.length;
254
+ const dx: number[] = [];
255
+ const slope: number[] = [];
256
+ for (let i = 0; i < n - 1; i += 1) {
257
+ dx.push(curve[i + 1][0] - curve[i][0]);
258
+ slope.push((curve[i + 1][1] - curve[i][1]) / dx[i]);
259
+ }
260
+ const m: number[] = new Array(n).fill(0);
261
+ m[0] = slope[0];
262
+ m[n - 1] = slope[n - 2];
263
+ for (let i = 1; i < n - 1; i += 1) m[i] = slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2;
264
+ for (let i = 0; i < n - 1; i += 1) {
265
+ if (slope[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; }
266
+ const a = m[i] / slope[i];
267
+ const b = m[i + 1] / slope[i];
268
+ const s = a * a + b * b;
269
+ if (s > 9) {
270
+ const t = 3 / Math.sqrt(s);
271
+ m[i] = t * a * slope[i];
272
+ m[i + 1] = t * b * slope[i];
273
+ }
274
+ }
275
+ let segment = 0;
276
+ for (let i = 0; i < size; i += 1) {
277
+ const x = i / (size - 1);
278
+ while (segment < n - 2 && x > curve[segment + 1][0]) segment += 1;
279
+ const h = dx[segment];
280
+ const t = (x - curve[segment][0]) / h;
281
+ const t2 = t * t;
282
+ const t3 = t2 * t;
283
+ const y =
284
+ (2 * t3 - 3 * t2 + 1) * curve[segment][1] +
285
+ (t3 - 2 * t2 + t) * h * m[segment] +
286
+ (-2 * t3 + 3 * t2) * curve[segment + 1][1] +
287
+ (t3 - t2) * h * m[segment + 1];
288
+ out[i] = clamp(y, 0, 1);
289
+ }
290
+ return out;
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // .cube files
295
+
296
+ export interface CubeLut {
297
+ size: number;
298
+ domainMin: [number, number, number];
299
+ domainMax: [number, number, number];
300
+ /** RGBA floats, red changing fastest (the order WebGL's 3D textures want). */
301
+ data: Float32Array;
302
+ }
303
+
304
+ export const MAX_CUBE_SIZE = 65;
305
+
306
+ /** Parse a 3D .cube file. Throws a readable error on anything else, including 1D LUTs. */
307
+ export function parseCube(text: string): CubeLut {
308
+ let size = 0;
309
+ let domainMin: [number, number, number] = [0, 0, 0];
310
+ let domainMax: [number, number, number] = [1, 1, 1];
311
+ let data: Float32Array | null = null;
312
+ let filled = 0;
313
+ for (const raw of text.split(/\r?\n/)) {
314
+ const line = raw.trim();
315
+ if (!line || line.startsWith("#")) continue;
316
+ const head = line.split(/\s+/, 1)[0].toUpperCase();
317
+ if (head === "TITLE") continue;
318
+ if (head === "LUT_1D_SIZE") throw new Error("This is a 1D LUT. Only 3D .cube files are supported.");
319
+ if (head === "LUT_3D_SIZE") {
320
+ size = Number(line.split(/\s+/)[1]);
321
+ if (!Number.isInteger(size) || size < 2 || size > MAX_CUBE_SIZE)
322
+ throw new Error(`LUT_3D_SIZE must be between 2 and ${MAX_CUBE_SIZE}.`);
323
+ data = new Float32Array(size * size * size * 4);
324
+ continue;
325
+ }
326
+ if (head === "DOMAIN_MIN" || head === "DOMAIN_MAX") {
327
+ const values = line.split(/\s+/).slice(1).map(Number);
328
+ if (values.length !== 3 || values.some((v) => !Number.isFinite(v))) throw new Error(`${head} needs three numbers.`);
329
+ if (head === "DOMAIN_MIN") domainMin = values as [number, number, number];
330
+ else domainMax = values as [number, number, number];
331
+ continue;
332
+ }
333
+ if (!/^[-+.\d]/.test(head)) continue;
334
+ if (!data) throw new Error("This .cube file has values before LUT_3D_SIZE.");
335
+ const values = line.split(/\s+/).map(Number);
336
+ if (values.length < 3 || values.slice(0, 3).some((v) => !Number.isFinite(v))) throw new Error("This .cube file has an unreadable row.");
337
+ if (filled >= size * size * size) throw new Error("This .cube file has too many rows for its LUT_3D_SIZE.");
338
+ data.set([values[0], values[1], values[2], 1], filled * 4);
339
+ filled += 1;
340
+ }
341
+ if (!data) throw new Error("This doesn't look like a .cube file (no LUT_3D_SIZE).");
342
+ if (filled !== size * size * size) throw new Error(`This .cube file is incomplete: ${filled} of ${size * size * size} rows.`);
343
+ if (domainMin.some((v, i) => v >= domainMax[i])) throw new Error("DOMAIN_MIN must be below DOMAIN_MAX.");
344
+ return { size, domainMin, domainMax, data };
345
+ }
346
+
347
+ /** Write a .cube file from `lut(r, g, b)`. Values are 0…1 inputs and outputs. */
348
+ export function serializeCube(size: number, title: string, lut: (r: number, g: number, b: number) => [number, number, number]): string {
349
+ const rows = [`TITLE "${title.replace(/["\r\n]/g, " ")}"`, `LUT_3D_SIZE ${size}`, ""];
350
+ const last = size - 1;
351
+ for (let b = 0; b < size; b += 1)
352
+ for (let g = 0; g < size; g += 1)
353
+ for (let r = 0; r < size; r += 1) {
354
+ const [x, y, z] = lut(r / last, g / last, b / last);
355
+ rows.push(`${clamp(x, 0, 1).toFixed(6)} ${clamp(y, 0, 1).toFixed(6)} ${clamp(z, 0, 1).toFixed(6)}`);
356
+ }
357
+ return `${rows.join("\n")}\n`;
358
+ }
359
+
360
+ // ---------------------------------------------------------------------------
361
+ // Uniforms: the fields as the numbers the shader reads.
362
+
363
+ export type Vec3 = [number, number, number];
364
+ const REC709: Vec3 = [0.2126, 0.7152, 0.0722];
365
+
366
+ /** Rows of a 3×3 matrix. */
367
+ type Mat3 = [Vec3, Vec3, Vec3];
368
+ const IDENTITY: Mat3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
369
+
370
+ function multiply(a: Mat3, b: Mat3): Mat3 {
371
+ return a.map((row) =>
372
+ [0, 1, 2].map((c) => row[0] * b[0][c] + row[1] * b[1][c] + row[2] * b[2][c]),
373
+ ) as Mat3;
374
+ }
375
+
376
+ // The matrices from the CSS filter effects spec, so the GPU draws the same picture as the CSS path.
377
+ function saturateMatrix(s: number): Mat3 {
378
+ return [
379
+ [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s],
380
+ [0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s],
381
+ [0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s],
382
+ ];
383
+ }
384
+
385
+ function sepiaMatrix(a: number): Mat3 {
386
+ const k = 1 - a;
387
+ return [
388
+ [0.393 + 0.607 * k, 0.769 - 0.769 * k, 0.189 - 0.189 * k],
389
+ [0.349 - 0.349 * k, 0.686 + 0.314 * k, 0.168 - 0.168 * k],
390
+ [0.272 - 0.272 * k, 0.534 - 0.534 * k, 0.131 + 0.869 * k],
391
+ ];
392
+ }
393
+
394
+ function hueMatrix(degrees: number): Mat3 {
395
+ const r = (degrees * Math.PI) / 180;
396
+ const c = Math.cos(r);
397
+ const s = Math.sin(r);
398
+ return [
399
+ [0.213 + c * 0.787 - s * 0.213, 0.715 - c * 0.715 - s * 0.715, 0.072 - c * 0.072 + s * 0.928],
400
+ [0.213 - c * 0.213 + s * 0.143, 0.715 + c * 0.285 + s * 0.14, 0.072 - c * 0.072 - s * 0.283],
401
+ [0.213 - c * 0.213 - s * 0.787, 0.715 - c * 0.715 + s * 0.715, 0.072 + c * 0.928 + s * 0.072],
402
+ ];
403
+ }
404
+
405
+ /** Direction of a wheel's push as an RGB offset that keeps brightness about the same. */
406
+ function wheelRgb(wheel: GradeWheel | undefined): Vec3 {
407
+ const x = wheel?.x ?? 0;
408
+ const y = wheel?.y ?? 0;
409
+ return [x, -0.5 * x + 0.866 * y, -0.5 * x - 0.866 * y];
410
+ }
411
+
412
+ /** White balance as linear channel gains, normalised to keep brightness. */
413
+ function whiteBalanceGains(temperature: number, tint: number): Vec3 {
414
+ const r = Math.pow(2, temperature * 0.7 + tint * 0.2);
415
+ const g = Math.pow(2, -tint * 0.5);
416
+ const b = Math.pow(2, -temperature * 0.7 + tint * 0.2);
417
+ const y = REC709[0] * r + REC709[1] * g + REC709[2] * b;
418
+ return [r / y, g / y, b / y];
419
+ }
420
+
421
+ export interface GradeUniforms {
422
+ brightness: number;
423
+ contrast: number;
424
+ pivot: number;
425
+ /** Rows: saturate, warmth and hue as one matrix. */
426
+ matrix: Mat3;
427
+ gains: Vec3;
428
+ matchContrast: number;
429
+ matchSaturation: number;
430
+ shadows: number;
431
+ highlights: number;
432
+ whites: number;
433
+ blacks: number;
434
+ blackPoint: number;
435
+ whitePoint: number;
436
+ gamma: number;
437
+ lift: Vec3;
438
+ wheelGamma: Vec3;
439
+ gain: Vec3;
440
+ vibrance: number;
441
+ /** One [hue, saturation, luminance] per band in GRADE_BANDS order. */
442
+ hsl: number[];
443
+ hasHsl: boolean;
444
+ skinProtect: number;
445
+ lutStrength: number;
446
+ grain: number;
447
+ grainSize: number;
448
+ halation: number;
449
+ bloom: number;
450
+ vignette: number;
451
+ }
452
+
453
+ export function gradeUniforms(fields: GradeFields): GradeUniforms {
454
+ const warmth = fields.warmth ?? 0;
455
+ let matrix = IDENTITY;
456
+ const saturation = fields.saturation ?? 1;
457
+ if (saturation !== 1) matrix = multiply(saturateMatrix(saturation), matrix);
458
+ if (warmth > 0) {
459
+ matrix = multiply(sepiaMatrix(warmth * 0.35), matrix);
460
+ matrix = multiply(saturateMatrix(1 + warmth * 0.25), matrix);
461
+ }
462
+ const hue = (fields.hue ?? 0) + (warmth < 0 ? warmth * -12 : warmth * -4);
463
+ if (hue) matrix = multiply(hueMatrix(hue), matrix);
464
+
465
+ const exposure = Math.pow(2, fields.exposure ?? 0);
466
+ const wb = whiteBalanceGains(fields.temperature ?? 0, fields.tint ?? 0);
467
+ const match = fields.match?.gains ?? [1, 1, 1];
468
+ const gains = wb.map((g, i) => g * exposure * match[i]) as Vec3;
469
+
470
+ const wheels = fields.wheels;
471
+ const lift = wheelRgb(wheels?.shadows).map((v) => v * 0.12 + (wheels?.shadows?.level ?? 0) * 0.12) as Vec3;
472
+ const wheelGamma = wheelRgb(wheels?.midtones).map((v) => clamp(1 + v * 0.35 + (wheels?.midtones?.level ?? 0) * 0.45, 0.2, 3)) as Vec3;
473
+ const gain = wheelRgb(wheels?.highlights).map((v) => Math.max(0, 1 + v * 0.3 + (wheels?.highlights?.level ?? 0) * 0.4)) as Vec3;
474
+
475
+ let hasHsl = false;
476
+ const hsl: number[] = [];
477
+ for (const band of GRADE_BANDS) {
478
+ const entry = fields.hsl?.[band];
479
+ hsl.push(entry?.hue ?? 0, entry?.saturation ?? 0, entry?.luminance ?? 0);
480
+ if (entry?.hue || entry?.saturation || entry?.luminance) hasHsl = true;
481
+ }
482
+
483
+ return {
484
+ brightness: fields.brightness ?? 1,
485
+ contrast: fields.contrast ?? 1,
486
+ pivot: fields.pivot ?? 0.5,
487
+ matrix,
488
+ gains,
489
+ matchContrast: fields.match?.contrast ?? 1,
490
+ matchSaturation: fields.match?.saturation ?? 1,
491
+ shadows: fields.shadows ?? 0,
492
+ highlights: fields.highlights ?? 0,
493
+ whites: fields.whites ?? 0,
494
+ blacks: fields.blacks ?? 0,
495
+ blackPoint: fields.blackPoint ?? 0,
496
+ whitePoint: Math.max((fields.blackPoint ?? 0) + 0.001, fields.whitePoint ?? 1),
497
+ gamma: Math.max(0.01, fields.gamma ?? 1),
498
+ lift,
499
+ wheelGamma,
500
+ gain,
501
+ vibrance: fields.vibrance ?? 0,
502
+ hsl,
503
+ hasHsl,
504
+ skinProtect: fields.skinProtect ?? 0,
505
+ lutStrength: fields.lut ? clamp(fields.lutStrength ?? 1, 0, 1) : 0,
506
+ grain: fields.grain ?? 0,
507
+ grainSize: fields.grainSize ?? 1,
508
+ halation: fields.halation ?? 0,
509
+ bloom: fields.bloom ?? 0,
510
+ vignette: fields.vignette ?? 0,
511
+ };
512
+ }