8000 feat(render): real WebGPU backend + render==preview pipeline by johannboehme · Pull Request #12 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"@vitest/browser": "^2.1.9",
"@webgpu/types": "^0.1.69",
"autoprefixer": "^10.4.20",
"jsdom": "^25.0.1",
"playwright": "^1.59.1",
Expand Down
32 changes: 22 additions & 10 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { ReactNode, useEffect, useMemo, useState } from "react";
import { Link, Navigate, NavLink, Route, Routes, useLocation } from "react-router-dom";
import { detectCapabilities, meetsMinRequirements } from "./local/capabilities";
import {
detectCapabilities,
initCapabilities,
meetsMinRequirements,
} from "./local/capabilities";
import { markInterruptedJobsOnLoad } from "./local/lifecycle";
import { HelpOverlay } from "./editor/components/HelpOverlay";
import { RecMark } from "./editor/components/RuleStrip";
Expand All @@ -22,7 +26,11 @@ export default function App() {
const isFullBleed =
/^\/job\/[^/]+\/edit/.test(location.pathname) ||
/^\/job\/[^/]+\/render$/.test(location.pathname);
const caps = useMemo(() => detectCapabilities(), []);
// `caps` starts with the sync probe (webgpu=false) and gets the
// async-probed `webgpu` merged in once `initCapabilities()` resolves.
// Both Settings (display) and any render-backend consumer that reads
// via `getCapabilities()` see the merged result.
const [caps, setCaps] = useState(() => detectCapabilities());
const min = useMemo(() => meetsMinRequirements(caps), [caps]);

// Hold off rendering anything browser-API-dependent until we've confirmed
Expand All @@ -31,17 +39,21 @@ export default function App() {
// We also clean up jobs left in `syncing`/`rendering` from a previous
// page session — they were necessarily interrupted (the work was driven
// by a now-dead tab) so surfacing that beats letting them hang in limbo.
// And we await the WebGPU adapter probe so the Render-Backend factory
// gets a reliable `caps.webgpu` from the very first mount.
const [ready, setReady] = useState(false);
useEffect(() => {
// Await the interrupted-job sweep before unblocking routing so any
// JobPage that mounts immediately after sees the freshly flipped
// "failed" status instead of a stale "rendering" snapshot.
let cancelled = false;
markInterruptedJobsOnLoad()
.catch(() => undefined)
.finally(() => {
if (!cancelled) setReady(true);
});
Promise.all([
markInterruptedJobsOnLoad().catch(() => undefined),
initCapabilities()
.then((merged) => {
if (!cancelled) setCaps(merged);
})
.catch(() => undefined),
]).finally(() => {
if (!cancelled) setReady(true);
});
return () => {
cancelled = true;
};
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/editor/components/Compositor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/
import { useEffect, useRef, useState } from "react";
import { useEditorStore } from "../store";
import { detectCapabilities } from "../../local/capabilities";
import { getCapabilities } from "../../local/capabilities";
import { MasterAudio } from "./MasterAudio";
import { TestPattern } from "./TestPattern";
import { OutputFrameBox } from "./OutputFrameBox";
Expand Down Expand Up @@ -87,7 +87,7 @@ function CompositorCanvas({ cams }: { cams: ClipUrlMap }) {
const runtime = new PreviewRuntime({
canvas,
cams,
capabilities: detectCapabilities(),
capabilities: getCapabilities(),
cssW,
cssH,
dpr,
Expand Down
100 changes: 100 additions & 0 deletions frontend/src/editor/fx/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import type {
CanvasLikeContext,
WebGL2DrawContext,
WebGPUDrawContext,
} from "./renderer-context";
import type { ADSREnvelope } from "./envelope";
import type { FxKind, FxParamDef, PunchFx } from "./types";
Expand Down Expand Up @@ -72,6 +73,17 @@ export interface FxDefinition {
t: number,
): void;

/** WebGPU renderer. Same parameters and contract as `drawWebGL2`,
* driving a `WebGPUDrawContext` in 1798 stead. Required: every FxKind
* must ship a WGSL implementation. */
drawWebGPU(
ctx: WebGPUDrawContext,
fx: PunchFx,
w: number,
h: number,
t: number,
): void;

/** Apply the ADSR-sampled wetness (0..1) to this kind's params and
* return the params the renderer should actually draw with. Each
* effect knows best how to scale itself: a vignette dims its
Expand Down Expand Up @@ -161,6 +173,16 @@ const VIGNETTE: FxDefinition = {
ctx.setUniform1f("u_falloff", falloff);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx) {
const { intensity, falloff } = vignetteParams(fx);
ctx.setBlendMode("over");
ctx.useProgram("vignette");
// Note: WebGPU uniform field names match the WGSL struct (no
// `u_` prefix), unlike the WebGL2 path which prefixes its globals.
ctx.setUniform1f("intensity", intensity);
ctx.setUniform1f("falloff", falloff);
ctx.drawFullscreenQuad();
},
// Vignette is a pure overlay — its alpha IS the intensity, so scaling
// intensity by wetness directly dims the corner darkness. Falloff
// (the gradient's geometry) stays put; only the strength fades.
Expand Down Expand Up @@ -358,6 +380,19 @@ const WEAR: FxDefinition = {
ctx.setUniform2f("u_texel", w > 0 ? 1 / w : 0, h > 0 ? 1 / h : 0);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx, w, h, t) {
const { decay, drift } = wearParams(fx);
const period = bipolarPeriodS(drift);
const driftPhase = isFinite(period) ? lfoPhase(t, fx.inS, period) : -1;
ctx.setBlendMode("replace");
ctx.useProgram("wear");
ctx.bindSourceTexture();
ctx.setUniform1f("decay", decay);
ctx.setUniform1f("driftPhase", driftPhase);
ctx.setUniform1f("t", t);
ctx.setUniform2f("texel", w > 0 ? 1 / w : 0, h > 0 ? 1 / h : 0);
ctx.drawFullscreenQuad();
},
// Wear's master amount is `decay` — every component (Y/C bleed,
// tracking-bar visibility, wobble depth, grain density, dropouts,
// tint) scales internally with it. Drift (LFO timing) keeps its
Expand Down Expand Up @@ -418,6 +453,17 @@ const RGB: FxDefinition = {
ctx.setUniform1f("u_angle", angle);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx) {
const p = fx.params ?? {};
const split = clamp01(p.split ?? RGB_DEFAULTS.split);
const angle = clamp01(p.angle ?? RGB_DEFAULTS.angle);
ctx.setBlendMode("replace");
ctx.useProgram("rgb");
ctx.bindSourceTexture();
ctx.setUniform1f("split", split);
ctx.setUniform1f("angle", angle);
ctx.drawFullscreenQuad();
},
// RGB-split's "amount" is the channel-offset distance. At wetness=0
// split=0 → all channels overlap → identity image. Angle (direction)
// is preserved.
Expand Down Expand Up @@ -522,6 +568,19 @@ const ZOOM: FxDefinition = {
ctx.setUniform1f("u_phase", phase);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx, _w, _h, t) {
const p = fx.params ?? {};
const punch = clamp01(p.punch ?? ZOOM_DEFAULTS.punch);
const rate = clamp01(p.rate ?? ZOOM_DEFAULTS.rate);
const period = bipolarPeriodS(rate);
const phase = lfoPhase(t, fx.inS, period);
ctx.setBlendMode("replace");
ctx.useProgram("zoom");
ctx.bindSourceTexture();
ctx.setUniform1f("punch", punch);
ctx.setUniform1f("phase", phase);
ctx.drawFullscreenQuad();
},
// Zoom is a displacement effect — alpha-blending source over zoomed
// would ghost. Scale `punch` (the pulse magnitude) linearly with the
// envelope's wetness so each pulse's amplitude tracks the envelope
Expand Down Expand Up @@ -601,6 +660,18 @@ const UV: FxDefinition = {
ctx.setUniform2f("u_texel", w > 0 ? 1 / w : 0, h > 0 ? 1 / h : 0);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx, w, h) {
const p = fx.params ?? {};
const glow = clamp01(p.glow ?? UV_DEFAULTS.glow);
const tint = clamp01(p.tint ?? UV_DEFAULTS.tint);
ctx.setBlendMode("replace");
ctx.useProgram("uv");
ctx.bindSourceTexture();
ctx.setUniform1f("glow", glow);
ctx.setUniform1f("tint", tint);
ctx.setUniform2f("texel", w > 0 ? 1 / w : 0, h > 0 ? 1 / h : 0);
ctx.drawFullscreenQuad();
},
// UV's `glow` is the intensity (bloom strength). `tint` is a colour
// selector — scaling it shifts the hue (tint=0.4 vs 0.2 are different
// colours, not different brightnesses), so a wetness ramp on tint
Expand Down Expand Up @@ -671,6 +742,20 @@ const ECHO: FxDefinition = {
ctx.setUniform1f("u_phase", phase);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx, _w, _h, t) {
const p = fx.params ?? {};
const trail = clamp01(p.trail ?? ECHO_DEFAULTS.trail);
const mix = clamp01(p.mix ?? ECHO_DEFAULTS.mix);
const period = bipolarPeriodS(trail);
const phase = lfoPhase(t, fx.inS, period);
ctx.setBlendMode("replace");
ctx.useProgram("echo");
ctx.bindSourceTexture();
ctx.setUniform1f("trail", trail);
ctx.setUniform1f("mix", mix);
ctx.setUniform1f("phase", phase);
ctx.drawFullscreenQuad();
},
// Echo's `mix` is its wet/dry — at mix=0 the additive trails vanish
// and only the source survives. Trail (LFO timing) keeps direction.
applyWetness(params, wetness) {
Expand Down Expand Up @@ -779,6 +864,21 @@ const TAPE: FxDefinition = {
ctx.setUniform1f("u_phase", phase);
ctx.drawFullscreenQuad();
},
drawWebGPU(ctx, fx, _w, _h, t) {
const p = fx.params ?? {};
const bend = clamp01(p.bend ?? TAPE_DEFAULTS.bend);
const warp = clamp01(p.warp ?? TAPE_DEFAULTS.warp);
const period = bipolarPeriodS(bend);
const fx.inS, period);
const phaseFloor = clamp01(p.phaseFloor ?? 0);
const phase = Math.max(oneShot, phaseFloor);
ctx.setBlendMode("replace");
ctx.useProgram("tape");
ctx.bindSourceTexture();
ctx.setUniform1f("warp", warp);
ctx.setUniform1f("phase", phase);
ctx.drawFullscreenQuad();
},
// Tape's visual stop is driven by `warp` (chroma + darken depth).
// At wetness=0 the warp collapses to 0 → no smear, no darkening,
// no chromatic split → identity image. Bend (which sets the one-shot
Expand Down
32 changes: 32 additions & 0 deletions frontend/src/editor/fx/renderer-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,38 @@ export interface WebGL2DrawContext {
drawFullscreenQuad(): void;
}

/** WebGPU-Pendant zu WebGL2DrawContext. Bewahrt strukturparallele
* Catalog-Aufrufe (`useProgram` / `setUniform*` / `bindSourceTexture` /
* `setBlendMode` / `drawFullscreenQuad`) damit `drawWebGPU` 1:1 zu
* `drawWebGL2` aussieht — anderer Backend, gleiche FX-Logik.
*
* Implementation lebt in `editor/render/webgpu/draw-context.ts` und
* managed:
* - GPURenderPipeline-Cache (pro FX-Kind, in 2 Blend-Varianten)
* - Scratch-Uniform-Buffer mit Per-Field-Offsets aus dem FX-Spec
* - SnapshotTex-Bindung (Pre-FX-Source) auf festem Texture-Binding
* - Bind 10BC8 -Group-Allocation pro `drawFullscreenQuad`
*
* Lifecycle: Backend setzt die aktive Render-Pass + Snapshot-View
* über interne Methoden; Catalog-Code sieht nur die Public-API hier. */
export interface WebGPUDrawContext {
/** Aktive FX-Pipeline binden (lazy-compiled durch den Cache). */
useProgram(name: string): void;
setUniform1i(name: string, value: number): void;
setUniform1f(name: string, value: number): void;
setUniform2f(name: string, a: number, b: number): void;
setUniform4f(name: string, a: number, b: number, c: number, d: number): void;
/** Source-Texture (= Pre-FX-Snapshot) ans Sampler-Slot binden. Der
* Backend reserviert die Slots (typischerweise binding=0 sampler,
* binding=1 source-tex, binding=2 uniforms). `samplerName` ist
* Compat-API mit WebGL2 — bei WebGPU informationell, weil das
* Layout-Slot fest ist. */
bindSourceTexture(samplerName?: string): void;
setBlendMode(mode: FxBlendMode): void;
/** Flush Uniforms → GPU, set Bind-Group, draw 3 (fullscreen triangle). */
drawFullscreenQuad(): void;
}

/** Shared helper for tests / debug logging — describes a fx call site. */
export function fxLogId(fx: PunchFx): string {
return `${fx.kind}#${fx.id}`;
Expand Down
73 changes: 73 additions & 0 deletions frontend/src/editor/fx/webgpu/echo.wgsl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* WGSL-Port von echo.frag.ts. Stateless 5-tap trail entlang einer
* phase-rotierenden Achse.
*
* Replace-Blend.
*/
import type { FxWebGPUSpec } from "../../render/webgpu/pipeline-cache";

export const ECHO_WGSL = `
struct Uniforms {
trail: f32,
mix: f32,
phase: f32,
};

@group(0) @binding(0) var u_samp: sampler;
@group(0) @binding(1) var u_source: texture_2d<f32>;
@group(0) @binding(2) var<uniform> u: Uniforms;

struct VsOut {
@builtin(position) pos: vec4f,
@location(0) uv: vec2f,
};

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VsOut {
let p = array<vec2f, 3>(
vec2f(-1.0, -1.0),
vec2f( 3.0, -1.0),
vec2f(-1.0, 3.0)
);
var out: VsOut;
out.pos = vec4f(p[idx], 0.0, 1.0);
out.uv = vec2f(p[idx].x * 0.5 + 0.5, p[idx].y * 0.5 + 0.5);
return out;
}

fn sampleSrc(uv: vec2f) -> vec4f {
return textureSample(u_source, u_samp, vec2f(uv.x, 1.0 - uv.y));
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4f {
let base = sampleSrc(in.uv).rgb;
if (u.mix <= 0.001 || u.trail <= 0.001) {
return vec4f(base, 1.0);
}
let a = u.phase * 6.28318530718;
let axis = vec2f(cos(a), sin(a)) * (u.trail * 0.10);
var trail = vec3f(0.0);
var wsum = 0.0;
for (var i: i32 = 1; i <= 5; i = i + 1) {
let fi = f32(i) / 5.0;
let w = exp(-fi * 2.5);
let uv = clamp(in.uv - axis * fi, vec2f(0.0), vec2f(1.0));
trail = trail + sampleSrc(uv).rgb * w;
wsum = wsum + w;
}
trail = trail / max(wsum, 0.0001);
let outRgb = mix(base, max(base, trail), u.mix);
return vec4f(outRgb, 1.0);
}
`;

export const ECHO_SPEC: FxWebGPUSpec = {
name: "echo",
wgsl: ECHO_WGSL,
uniformFields: [
{ name: "trail", type: "f1" },
{ name: "mix", type: "f1" },
{ name: "phase", type: "f1" },
],
};
Loading
Loading
0