@phil65/demoreel 0.1.0 → 0.4.0
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.
- package/README.md +52 -8
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/dist/args.js +34 -0
- package/dist/cli.js +223 -5
- package/dist/compose.d.ts +4 -0
- package/dist/compose.js +4 -0
- package/dist/gif.d.ts +16 -0
- package/dist/gif.js +19 -0
- package/dist/idle.d.ts +8 -2
- package/dist/idle.js +12 -10
- package/dist/index.d.ts +5 -4
- package/dist/index.js +5 -4
- package/dist/marks.js +5 -4
- package/dist/motion.d.ts +1 -1
- package/dist/motion.js +3 -3
- package/dist/openscreen/project.js +3 -3
- package/dist/project.d.ts +51 -1
- package/dist/project.js +89 -1
- package/dist/record.d.ts +45 -3
- package/dist/record.js +110 -31
- package/dist/recorder.d.ts +1 -0
- package/dist/recorder.js +8 -0
- package/dist/renderer/assets/CanvasPool-PBu3bHFZ.js +1 -0
- package/dist/renderer/assets/CanvasRenderer-HmF-4gyW.js +1 -0
- package/dist/renderer/assets/RenderTargetSystem-Dk1U4wDJ.js +184 -0
- package/dist/renderer/assets/WebGLRenderer-C0v9HBel.js +149 -0
- package/dist/renderer/assets/WebGPURenderer-Ce0-U9Q1.js +95 -0
- package/dist/renderer/assets/{browserAll-aHn2isHo.js → browserAll-DhvWQ7nM.js} +2 -2
- package/dist/renderer/assets/canvasUtils-KRroregW.js +1 -0
- package/dist/renderer/assets/{getTexelRangeRects-yD6MQ0xy.js → getTexelRangeRects-D3pwCyRt.js} +3 -3
- package/dist/renderer/assets/index-CE-lli1m.js +556 -0
- package/dist/renderer/assets/init-DfmWKarH.js +83 -0
- package/dist/renderer/assets/webworkerAll-B41hok0-.js +1 -0
- package/dist/renderer/index.html +1 -6
- package/dist/scene.d.ts +85 -9
- package/dist/scene.js +310 -48
- package/dist/types.d.ts +6 -1
- package/dist/zoom.d.ts +2 -0
- package/dist/zoom.js +10 -4
- package/package.json +2 -2
- package/dist/renderer/assets/CanvasPool-CHSHS1-v.js +0 -23
- package/dist/renderer/assets/RenderTargetSystem-EAUH9iQk.js +0 -404
- package/dist/renderer/assets/canvasUtils-n5g2f3_X.js +0 -1
- package/dist/renderer/assets/getTextureBatchBindGroup-Bwvgbco6.js +0 -1
- package/dist/renderer/assets/index-BwP6rH7I.js +0 -556
- package/dist/renderer/assets/init-C2Za5NQh.js +0 -83
- package/dist/renderer/assets/webworkerAll-JSSmbaR2.js +0 -1
package/dist/marks.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { sourceToOutputMs } from "./idle.js";
|
|
9
9
|
import { clipUnit, DEPTH_SCALES, boxToStage, clampFocus, toStage } from "./layout.js";
|
|
10
10
|
import { captionRect } from "./project.js";
|
|
11
|
+
import { normalizeDepth } from "./zoom.js";
|
|
11
12
|
/** Action target boxes in output-frame coordinates (padding + zoom camera applied). */
|
|
12
13
|
export function targetRects(input) {
|
|
13
14
|
const out = [];
|
|
@@ -74,7 +75,7 @@ export function applyCamera(rect, regions, t) {
|
|
|
74
75
|
const cam = cameraAt(regions, t);
|
|
75
76
|
if (!cam)
|
|
76
77
|
return rect;
|
|
77
|
-
const s = DEPTH_SCALES[cam.region.depth];
|
|
78
|
+
const s = DEPTH_SCALES[normalizeDepth(cam.region.depth)];
|
|
78
79
|
const f = clampFocus(cam.region.focus, s);
|
|
79
80
|
const scale = 1 + (s - 1) * cam.p;
|
|
80
81
|
const ox = (0.5 - f.cx * s) * cam.p;
|
|
@@ -104,8 +105,8 @@ export function buildMarks(input) {
|
|
|
104
105
|
});
|
|
105
106
|
}
|
|
106
107
|
for (const a of input.actions) {
|
|
107
|
-
if (a.point && (a.kind === "click" || a.kind === "type")) {
|
|
108
|
-
const t = a.kind === "
|
|
108
|
+
if (a.point && (a.kind === "click" || a.kind === "select" || a.kind === "type")) {
|
|
109
|
+
const t = a.kind === "type" ? a.arriveMs : a.endMs;
|
|
109
110
|
const p = applyCamera({ ...toStage(layout, vp, a.point), w: 0, h: 0 }, zr, t);
|
|
110
111
|
if (p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1) {
|
|
111
112
|
marks.points.push({
|
|
@@ -124,7 +125,7 @@ export function buildMarks(input) {
|
|
|
124
125
|
marks.regions.push({
|
|
125
126
|
start,
|
|
126
127
|
end: Math.max(start, Math.min(endS, out(z.endMs))),
|
|
127
|
-
label: `zoom ${DEPTH_SCALES[z.depth]}x (${z.source ?? "auto"})`,
|
|
128
|
+
label: `zoom ${DEPTH_SCALES[normalizeDepth(z.depth)]}x (${z.source ?? "auto"})`,
|
|
128
129
|
kind: "zoom",
|
|
129
130
|
});
|
|
130
131
|
}
|
package/dist/motion.d.ts
CHANGED
|
@@ -12,4 +12,4 @@ export declare function travelDuration(distance: number, targetSize?: number, sp
|
|
|
12
12
|
/** Deterministic pseudo-random so re-renders of a scenario produce the same motion. */
|
|
13
13
|
export declare function mulberry32(seed: number): () => number;
|
|
14
14
|
export declare function makePath(from: Point, to: Point, rand: () => number): (t: number) => Point;
|
|
15
|
-
export declare const sleep: (ms: number) => Promise<
|
|
15
|
+
export declare const sleep: (ms: number) => Promise<void>;
|
package/dist/motion.js
CHANGED
|
@@ -14,8 +14,8 @@ export function easeAimed(t) {
|
|
|
14
14
|
export function travelDuration(distance, targetSize = 40, speed = 1) {
|
|
15
15
|
if (distance < 2)
|
|
16
16
|
return 0;
|
|
17
|
-
const fitts =
|
|
18
|
-
return Math.round(Math.min(
|
|
17
|
+
const fitts = 190 + 120 * Math.log2(distance / Math.max(targetSize, 8) + 1);
|
|
18
|
+
return Math.round(Math.min(950, Math.max(240, fitts)) / speed);
|
|
19
19
|
}
|
|
20
20
|
/** Deterministic pseudo-random so re-renders of a scenario produce the same motion. */
|
|
21
21
|
export function mulberry32(seed) {
|
|
@@ -46,4 +46,4 @@ export function makePath(from, to, rand) {
|
|
|
46
46
|
};
|
|
47
47
|
};
|
|
48
48
|
}
|
|
49
|
-
export const sleep = (ms) => new Promise((r) => setTimeout(r,
|
|
49
|
+
export const sleep = (ms) => (ms <= 0 ? Promise.resolve() : new Promise((r) => setTimeout(r, ms)));
|
|
@@ -548,9 +548,9 @@ function getAspectRatioValue(aspectRatio) {
|
|
|
548
548
|
case "9:16": return 9 / 16;
|
|
549
549
|
case "1:1": return 1;
|
|
550
550
|
case "4:3": return 4 / 3;
|
|
551
|
-
case "4:5": return
|
|
552
|
-
case "16:10": return
|
|
553
|
-
case "10:16": return
|
|
551
|
+
case "4:5": return .8;
|
|
552
|
+
case "16:10": return 1.6;
|
|
553
|
+
case "10:16": return .625;
|
|
554
554
|
case "native": return NATIVE_ASPECT_RATIO_FALLBACK;
|
|
555
555
|
default: return aspectRatio;
|
|
556
556
|
}
|
package/dist/project.d.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import type { Caption, CursorSample, SpeedRegion, TrimRegion, ZoomRegion } from "./types.ts";
|
|
1
|
+
import type { ActionRecord, Caption, CursorSample, SpeedRegion, TrimRegion, ZoomRegion } from "./types.ts";
|
|
2
2
|
export declare const PROJECT_VERSION = 2;
|
|
3
3
|
export declare const CURSOR_TELEMETRY_VERSION = 2;
|
|
4
|
+
export type KeyHudPosition = "bottom-right" | "top-right" | "bottom-left" | "top-left";
|
|
5
|
+
export interface KeyHudOptions {
|
|
6
|
+
/** Corner where shortcut keycap badges appear (default "bottom-right"). */
|
|
7
|
+
position?: KeyHudPosition;
|
|
8
|
+
/** How long each keycap stays visible (ms, default 1100). */
|
|
9
|
+
durationMs?: number;
|
|
10
|
+
/** Font size in px (default 24). */
|
|
11
|
+
fontSize?: number;
|
|
12
|
+
}
|
|
4
13
|
export interface LookOptions {
|
|
5
14
|
/** Wallpaper: "#hex", CSS gradient, or one of OpenScreen's "/wallpapers/wallpaperN.jpg". */
|
|
6
15
|
wallpaper: string;
|
|
@@ -14,6 +23,8 @@ export interface LookOptions {
|
|
|
14
23
|
/** Where captions sit; "auto" (default) = bottom, unless that covers an active target. */
|
|
15
24
|
captionPosition: "auto" | "bottom" | "top";
|
|
16
25
|
captionFontSize: number;
|
|
26
|
+
/** Show floating keycap pills for `scene.press()` shortcuts (default false). */
|
|
27
|
+
showKeys?: boolean | KeyHudOptions;
|
|
17
28
|
}
|
|
18
29
|
export declare const DEFAULT_LOOK: LookOptions;
|
|
19
30
|
/** Caption box in percent of the output canvas (OpenScreen annotation position/size). */
|
|
@@ -23,6 +34,44 @@ export declare function captionRect(position: LookOptions["captionPosition"] | u
|
|
|
23
34
|
width: number;
|
|
24
35
|
height: number;
|
|
25
36
|
};
|
|
37
|
+
/** Formats a Playwright key chord (e.g. "Control+Shift+K") into a compact keycap label ("Ctrl + ⇧ + K"). */
|
|
38
|
+
export declare function formatKeycap(key: string): string;
|
|
39
|
+
/** Keycap HUD box in percent of the output canvas (sits clear of top/bottom captions). */
|
|
40
|
+
export declare function keycapRect(position?: KeyHudPosition, text?: string): {
|
|
41
|
+
x: number;
|
|
42
|
+
y: number;
|
|
43
|
+
width: number;
|
|
44
|
+
height: number;
|
|
45
|
+
};
|
|
46
|
+
/** Builds OpenScreen text annotations for `scene.press()` actions when enabled globally or per-action. */
|
|
47
|
+
export declare function keycapAnnotations(actions: ActionRecord[], look?: LookOptions, startZIndex?: number): {
|
|
48
|
+
id: string;
|
|
49
|
+
startMs: number;
|
|
50
|
+
endMs: number;
|
|
51
|
+
type: string;
|
|
52
|
+
content: string;
|
|
53
|
+
textContent: string;
|
|
54
|
+
position: {
|
|
55
|
+
x: number;
|
|
56
|
+
y: number;
|
|
57
|
+
};
|
|
58
|
+
size: {
|
|
59
|
+
width: number;
|
|
60
|
+
height: number;
|
|
61
|
+
};
|
|
62
|
+
style: {
|
|
63
|
+
color: string;
|
|
64
|
+
backgroundColor: string;
|
|
65
|
+
fontSize: number;
|
|
66
|
+
fontFamily: string;
|
|
67
|
+
fontWeight: string;
|
|
68
|
+
fontStyle: string;
|
|
69
|
+
textDecoration: string;
|
|
70
|
+
textAlign: string;
|
|
71
|
+
textAnimation: string;
|
|
72
|
+
};
|
|
73
|
+
zIndex: number;
|
|
74
|
+
}[];
|
|
26
75
|
export declare function captionAnnotations(captions: Caption[], look?: LookOptions): {
|
|
27
76
|
id: string;
|
|
28
77
|
startMs: number;
|
|
@@ -55,6 +104,7 @@ export interface BuildProjectOptions {
|
|
|
55
104
|
videoPath: string;
|
|
56
105
|
zoomRegions: ZoomRegion[];
|
|
57
106
|
captions: Caption[];
|
|
107
|
+
actions?: ActionRecord[];
|
|
58
108
|
trimRegions?: TrimRegion[];
|
|
59
109
|
speedRegions?: SpeedRegion[];
|
|
60
110
|
look?: Partial<LookOptions>;
|
package/dist/project.js
CHANGED
|
@@ -16,11 +16,97 @@ export const DEFAULT_LOOK = {
|
|
|
16
16
|
aspectRatio: "16:9",
|
|
17
17
|
captionPosition: "auto",
|
|
18
18
|
captionFontSize: 30,
|
|
19
|
+
showKeys: false,
|
|
19
20
|
};
|
|
20
21
|
/** Caption box in percent of the output canvas (OpenScreen annotation position/size). */
|
|
21
22
|
export function captionRect(position) {
|
|
22
23
|
return { x: 15, y: position === "top" ? 3.5 : 88.5, width: 70, height: 8 };
|
|
23
24
|
}
|
|
25
|
+
const KEY_LABELS = {
|
|
26
|
+
meta: "⌘",
|
|
27
|
+
cmd: "⌘",
|
|
28
|
+
command: "⌘",
|
|
29
|
+
control: "Ctrl",
|
|
30
|
+
ctrl: "Ctrl",
|
|
31
|
+
controlormeta: "⌘",
|
|
32
|
+
shift: "⇧",
|
|
33
|
+
alt: "Alt",
|
|
34
|
+
option: "⌥",
|
|
35
|
+
enter: "↵",
|
|
36
|
+
return: "↵",
|
|
37
|
+
escape: "Esc",
|
|
38
|
+
esc: "Esc",
|
|
39
|
+
backspace: "⌫",
|
|
40
|
+
delete: "Del",
|
|
41
|
+
tab: "⇥",
|
|
42
|
+
space: "Space",
|
|
43
|
+
" ": "Space",
|
|
44
|
+
arrowup: "↑",
|
|
45
|
+
arrowdown: "↓",
|
|
46
|
+
arrowleft: "←",
|
|
47
|
+
arrowright: "→",
|
|
48
|
+
};
|
|
49
|
+
/** Formats a Playwright key chord (e.g. "Control+Shift+K") into a compact keycap label ("Ctrl + ⇧ + K"). */
|
|
50
|
+
export function formatKeycap(key) {
|
|
51
|
+
return key
|
|
52
|
+
.split("+")
|
|
53
|
+
.map((part) => {
|
|
54
|
+
const trimmed = part.trim();
|
|
55
|
+
const mapped = KEY_LABELS[trimmed.toLowerCase()];
|
|
56
|
+
if (mapped)
|
|
57
|
+
return mapped;
|
|
58
|
+
return trimmed.length === 1 ? trimmed.toUpperCase() : trimmed;
|
|
59
|
+
})
|
|
60
|
+
.filter(Boolean)
|
|
61
|
+
.join(" + ");
|
|
62
|
+
}
|
|
63
|
+
/** Keycap HUD box in percent of the output canvas (sits clear of top/bottom captions). */
|
|
64
|
+
export function keycapRect(position = "bottom-right", text = "") {
|
|
65
|
+
const width = Math.min(34, Math.max(12, 8 + text.length * 1.5));
|
|
66
|
+
const height = 6.5;
|
|
67
|
+
const x = position.endsWith("left") ? 4 : 95 - width;
|
|
68
|
+
const y = position.startsWith("top") ? 13 : 77.5;
|
|
69
|
+
return { x: Math.round(x * 10) / 10, y, width: Math.round(width * 10) / 10, height };
|
|
70
|
+
}
|
|
71
|
+
/** Builds OpenScreen text annotations for `scene.press()` actions when enabled globally or per-action. */
|
|
72
|
+
export function keycapAnnotations(actions, look = DEFAULT_LOOK, startZIndex = 1) {
|
|
73
|
+
const globalOn = Boolean(look.showKeys);
|
|
74
|
+
const opts = typeof look.showKeys === "object" && look.showKeys ? look.showKeys : {};
|
|
75
|
+
const position = opts.position ?? "bottom-right";
|
|
76
|
+
const defaultDur = opts.durationMs ?? 1100;
|
|
77
|
+
const fontSize = opts.fontSize ?? 24;
|
|
78
|
+
const presses = actions.filter((a) => a.kind === "press" && (a.showKey ?? globalOn) && (a.text ?? a.label));
|
|
79
|
+
return presses.map((a, i) => {
|
|
80
|
+
const raw = a.text ?? a.label ?? "";
|
|
81
|
+
const text = formatKeycap(raw);
|
|
82
|
+
const r = keycapRect(position, text);
|
|
83
|
+
const nextStart = presses[i + 1]?.startMs;
|
|
84
|
+
const desiredEnd = a.startMs + (a.keyDurationMs ?? defaultDur);
|
|
85
|
+
const endMs = nextStart !== undefined ? Math.max(a.startMs + 250, Math.min(desiredEnd, nextStart - 60)) : desiredEnd;
|
|
86
|
+
return {
|
|
87
|
+
id: `keycap-${i + 1}`,
|
|
88
|
+
startMs: Math.round(a.startMs),
|
|
89
|
+
endMs: Math.round(endMs),
|
|
90
|
+
type: "text",
|
|
91
|
+
content: text,
|
|
92
|
+
textContent: text,
|
|
93
|
+
position: { x: r.x, y: r.y },
|
|
94
|
+
size: { width: r.width, height: r.height },
|
|
95
|
+
style: {
|
|
96
|
+
color: "#f8fafc",
|
|
97
|
+
backgroundColor: "rgba(15, 18, 32, 0.88)",
|
|
98
|
+
fontSize,
|
|
99
|
+
fontFamily: "'JetBrains Mono', ui-monospace, 'DejaVu Sans Mono', monospace",
|
|
100
|
+
fontWeight: "bold",
|
|
101
|
+
fontStyle: "normal",
|
|
102
|
+
textDecoration: "none",
|
|
103
|
+
textAlign: "center",
|
|
104
|
+
textAnimation: "none",
|
|
105
|
+
},
|
|
106
|
+
zIndex: startZIndex + i,
|
|
107
|
+
};
|
|
108
|
+
});
|
|
109
|
+
}
|
|
24
110
|
export function captionAnnotations(captions, look = DEFAULT_LOOK) {
|
|
25
111
|
return captions.map((c, i) => {
|
|
26
112
|
const r = captionRect(c.position ?? look.captionPosition);
|
|
@@ -51,6 +137,8 @@ export function captionAnnotations(captions, look = DEFAULT_LOOK) {
|
|
|
51
137
|
export function buildProject(opts) {
|
|
52
138
|
const look = { ...DEFAULT_LOOK, ...opts.look };
|
|
53
139
|
const videoPath = path.resolve(opts.videoPath);
|
|
140
|
+
const captions = captionAnnotations(opts.captions, look);
|
|
141
|
+
const keycaps = keycapAnnotations(opts.actions ?? [], look, captions.length + 1);
|
|
54
142
|
return {
|
|
55
143
|
version: PROJECT_VERSION,
|
|
56
144
|
// Legacy field: OpenScreen <= 1.2 (v1 projects) only reads `videoPath`; >= 1.3 prefers `media`.
|
|
@@ -73,7 +161,7 @@ export function buildProject(opts) {
|
|
|
73
161
|
autoFocusAll: false,
|
|
74
162
|
trimRegions: opts.trimRegions ?? [],
|
|
75
163
|
speedRegions: opts.speedRegions ?? [],
|
|
76
|
-
annotationRegions:
|
|
164
|
+
annotationRegions: [...captions, ...keycaps],
|
|
77
165
|
aspectRatio: look.aspectRatio,
|
|
78
166
|
webcamLayoutPreset: "picture-in-picture",
|
|
79
167
|
webcamMaskShape: "rectangle",
|
package/dist/record.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { Page } from "playwright";
|
|
1
2
|
import { type ComposeResult } from "./compose.ts";
|
|
2
3
|
import type { IdleOptions } from "./idle.ts";
|
|
3
4
|
import type { LookOptions } from "./project.ts";
|
|
4
|
-
import
|
|
5
|
-
import type
|
|
5
|
+
import type { CursorStyle } from "./render.ts";
|
|
6
|
+
import { type ClickRippleOptions, type PacingOptions, Scene } from "./scene.ts";
|
|
7
|
+
import type { ActionRecord, RecordingResult, Viewport } from "./types.ts";
|
|
6
8
|
import type { ZoomOptions } from "./zoom.ts";
|
|
7
9
|
export interface ScenarioContext {
|
|
8
10
|
/** URL of the scenario's `serve` directory ("" if none). */
|
|
@@ -22,12 +24,18 @@ export interface Scenario {
|
|
|
22
24
|
cssZoom?: number;
|
|
23
25
|
/** Static directory (relative to the scenario file) served at `ctx.baseUrl`. */
|
|
24
26
|
serve?: string;
|
|
27
|
+
/** Saved Playwright storageState JSON file (relative to the scenario file, like `serve`). */
|
|
28
|
+
storageState?: string;
|
|
25
29
|
colorScheme?: "light" | "dark";
|
|
26
30
|
/** Seed for the cursor-path jitter (same seed => same motion). */
|
|
27
31
|
seed?: number;
|
|
28
32
|
pacing?: Partial<PacingOptions>;
|
|
29
33
|
zoom?: Partial<ZoomOptions>;
|
|
30
34
|
look?: Partial<LookOptions>;
|
|
35
|
+
/** Optional OpenScreen cursor styling (size, clickBounce, smoothing, motionBlur, show). */
|
|
36
|
+
cursor?: CursorStyle;
|
|
37
|
+
/** Draw an expanding translucent ring at each click (default false). */
|
|
38
|
+
clickRipple?: boolean | ClickRippleOptions;
|
|
31
39
|
/** Cut (or speed up) idle stretches with OpenScreen trim/speed regions. */
|
|
32
40
|
trimIdle?: boolean | Partial<IdleOptions>;
|
|
33
41
|
run(scene: Scene, ctx: ScenarioContext): Promise<void>;
|
|
@@ -37,10 +45,12 @@ export declare function defineScenario(s: Scenario): Scenario;
|
|
|
37
45
|
export interface RecordOptions {
|
|
38
46
|
/** Output directory (default: out/<name>). */
|
|
39
47
|
outDir?: string;
|
|
40
|
-
/** Path of the scenario file; `serve`
|
|
48
|
+
/** Path of the scenario file; `serve` and `storageState` are resolved relative to it (default: cwd). */
|
|
41
49
|
scenarioFile?: string;
|
|
42
50
|
/** Override scenario fields (e.g. from CLI flags). */
|
|
43
51
|
overrides?: Partial<Omit<Scenario, "run" | "name">>;
|
|
52
|
+
/** Override `scenario.storageState` (resolved relative to cwd). */
|
|
53
|
+
storageState?: string;
|
|
44
54
|
/** Show the browser while recording (debugging; the recording then includes OS chrome timing). */
|
|
45
55
|
headed?: boolean;
|
|
46
56
|
log?: (msg: string) => void;
|
|
@@ -50,4 +60,36 @@ export interface RecordResult extends ComposeResult {
|
|
|
50
60
|
outDir: string;
|
|
51
61
|
zoomRegions: ComposeResult["timeline"]["zoomRegions"];
|
|
52
62
|
}
|
|
63
|
+
export interface DryRunError {
|
|
64
|
+
message: string;
|
|
65
|
+
/** Index of the failing step: the number of actions that completed before it. */
|
|
66
|
+
actionIndex: number;
|
|
67
|
+
}
|
|
68
|
+
export interface DryRunOptions {
|
|
69
|
+
/** Path of the scenario file; `serve` and `storageState` are resolved relative to it (default: cwd). */
|
|
70
|
+
scenarioFile?: string;
|
|
71
|
+
/** Override scenario fields (e.g. from CLI flags). */
|
|
72
|
+
overrides?: Partial<Omit<Scenario, "run" | "name">>;
|
|
73
|
+
/** Override `scenario.storageState` (resolved relative to cwd). */
|
|
74
|
+
storageState?: string;
|
|
75
|
+
/** Show the browser while running. */
|
|
76
|
+
headed?: boolean;
|
|
77
|
+
/** Called with the Playwright page at the end of the run (both on success and failure), before closing the browser. */
|
|
78
|
+
atEnd?: (page: Page) => Promise<void> | void;
|
|
79
|
+
/** Called on failure with the error and page, before `atEnd` and before closing the browser. */
|
|
80
|
+
onFailure?: (err: DryRunError, page: Page) => Promise<void> | void;
|
|
81
|
+
}
|
|
82
|
+
export interface DryRunResult {
|
|
83
|
+
ok: boolean;
|
|
84
|
+
actions: ActionRecord[];
|
|
85
|
+
durationMs: number;
|
|
86
|
+
error?: DryRunError;
|
|
87
|
+
}
|
|
88
|
+
/** Resolves a Playwright storageState file path and throws a clear DemoreelError if missing. */
|
|
89
|
+
export declare function resolveStorageState(statePath: string | undefined, baseDir?: string): string | undefined;
|
|
53
90
|
export declare function recordScenario(input: Scenario, opts?: RecordOptions): Promise<RecordResult>;
|
|
91
|
+
/**
|
|
92
|
+
* Runs a scenario quickly in fast mode (no ffmpeg, no CDP screencast, no output files).
|
|
93
|
+
* Invokes `atEnd(page)` on both success and failure before closing the browser and static server.
|
|
94
|
+
*/
|
|
95
|
+
export declare function dryRunScenario(input: Scenario, opts?: DryRunOptions): Promise<DryRunResult>;
|
package/dist/record.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { compose } from "./compose.js";
|
|
5
|
-
import { checkFfmpeg, launchChromium } from "./env.js";
|
|
5
|
+
import { checkFfmpeg, DemoreelError, launchChromium } from "./env.js";
|
|
6
6
|
import { ScreencastRecorder } from "./recorder.js";
|
|
7
7
|
import { Scene } from "./scene.js";
|
|
8
8
|
import { serveStatic } from "./server.js";
|
|
@@ -10,20 +10,30 @@ import { serveStatic } from "./server.js";
|
|
|
10
10
|
export function defineScenario(s) {
|
|
11
11
|
return s;
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
/** Resolves a Playwright storageState file path and throws a clear DemoreelError if missing. */
|
|
14
|
+
export function resolveStorageState(statePath, baseDir = process.cwd()) {
|
|
15
|
+
if (!statePath)
|
|
16
|
+
return undefined;
|
|
17
|
+
const resolved = path.resolve(baseDir, statePath);
|
|
18
|
+
if (!fs.existsSync(resolved)) {
|
|
19
|
+
throw new DemoreelError(`storageState file not found: ${resolved}`, `demoreel login <url> --state ${statePath}`);
|
|
20
|
+
}
|
|
21
|
+
return resolved;
|
|
22
|
+
}
|
|
23
|
+
function mergeScenario(input, overrides) {
|
|
24
|
+
const scenario = { ...input, ...overrides };
|
|
15
25
|
if (!scenario.name || typeof scenario.run !== "function") {
|
|
16
26
|
throw new Error("a scenario needs a `name` and an async `run(scene, ctx)` (use defineScenario)");
|
|
17
27
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const viewport = scenario.viewport ?? { width: 1920, height: 1080 };
|
|
24
|
-
const framesDir = path.join(outDir, ".frames");
|
|
25
|
-
fs.rmSync(framesDir, { recursive: true, force: true });
|
|
28
|
+
return scenario;
|
|
29
|
+
}
|
|
30
|
+
/** Shared Chromium context + static server setup for both recording and dry runs. */
|
|
31
|
+
async function openScenarioSession(input, opts) {
|
|
32
|
+
const scenario = mergeScenario(input, opts.overrides);
|
|
26
33
|
const baseDir = opts.scenarioFile ? path.dirname(path.resolve(opts.scenarioFile)) : process.cwd();
|
|
34
|
+
const storageState = opts.storageState
|
|
35
|
+
? resolveStorageState(opts.storageState, process.cwd())
|
|
36
|
+
: resolveStorageState(scenario.storageState, baseDir);
|
|
27
37
|
let server = null;
|
|
28
38
|
if (scenario.serve) {
|
|
29
39
|
const dir = path.resolve(baseDir, scenario.serve);
|
|
@@ -31,11 +41,16 @@ export async function recordScenario(input, opts = {}) {
|
|
|
31
41
|
throw new Error(`scenario.serve: ${dir} does not exist`);
|
|
32
42
|
server = await serveStatic(dir);
|
|
33
43
|
}
|
|
34
|
-
const
|
|
35
|
-
let
|
|
36
|
-
let scene = null;
|
|
44
|
+
const viewport = scenario.viewport ?? { width: 1920, height: 1080 };
|
|
45
|
+
let browser = null;
|
|
37
46
|
try {
|
|
38
|
-
|
|
47
|
+
browser = await launchChromium({ headless: !opts.headed });
|
|
48
|
+
const context = await browser.newContext({
|
|
49
|
+
viewport,
|
|
50
|
+
deviceScaleFactor: 1,
|
|
51
|
+
colorScheme: scenario.colorScheme ?? "light",
|
|
52
|
+
...(storageState ? { storageState } : {}),
|
|
53
|
+
});
|
|
39
54
|
if (scenario.cssZoom && scenario.cssZoom !== 1) {
|
|
40
55
|
await context.addInitScript((z) => {
|
|
41
56
|
const apply = () => document.documentElement?.style.setProperty("zoom", String(z), "important");
|
|
@@ -45,32 +60,57 @@ export async function recordScenario(input, opts = {}) {
|
|
|
45
60
|
}, scenario.cssZoom);
|
|
46
61
|
}
|
|
47
62
|
const page = await context.newPage();
|
|
48
|
-
|
|
49
|
-
|
|
63
|
+
const close = async () => {
|
|
64
|
+
await browser?.close().catch(() => { });
|
|
65
|
+
await server?.close();
|
|
66
|
+
};
|
|
67
|
+
return { scenario, viewport, browser, context, page, baseUrl: server?.url ?? "", close };
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
await browser?.close().catch(() => { });
|
|
71
|
+
await server?.close();
|
|
72
|
+
throw e;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
export async function recordScenario(input, opts = {}) {
|
|
76
|
+
const scenario = mergeScenario(input, opts.overrides);
|
|
77
|
+
checkFfmpeg();
|
|
78
|
+
const outDir = path.resolve(opts.outDir ?? path.join("out", scenario.name));
|
|
79
|
+
const timings = {};
|
|
80
|
+
const t0 = Date.now();
|
|
81
|
+
const session = await openScenarioSession(input, opts);
|
|
82
|
+
const framesDir = path.join(outDir, ".frames");
|
|
83
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
84
|
+
fs.rmSync(framesDir, { recursive: true, force: true });
|
|
85
|
+
let recorder = null;
|
|
86
|
+
let scene = null;
|
|
87
|
+
try {
|
|
88
|
+
scene = new Scene(session.page, session.viewport, async () => {
|
|
89
|
+
recorder = new ScreencastRecorder(session.page, framesDir, {
|
|
90
|
+
maxWidth: session.viewport.width,
|
|
91
|
+
maxHeight: session.viewport.height,
|
|
92
|
+
});
|
|
50
93
|
await recorder.start();
|
|
51
94
|
return recorder;
|
|
52
|
-
}, { seed: scenario.seed, pacing: scenario.pacing });
|
|
95
|
+
}, { seed: session.scenario.seed, pacing: session.scenario.pacing, clickRipple: session.scenario.clickRipple });
|
|
53
96
|
const tRun = Date.now();
|
|
54
|
-
await scenario.run(scene, { baseUrl:
|
|
97
|
+
await session.scenario.run(scene, { baseUrl: session.baseUrl });
|
|
55
98
|
// Hold the last frame so the final zoom-out and captions finish.
|
|
56
99
|
const lastCaptionEnd = Math.max(0, ...scene.captions.map((c) => c.endMs));
|
|
57
100
|
await scene.pause(Math.max(900, lastCaptionEnd - scene.now() + 300));
|
|
58
101
|
timings.scenarioMs = Date.now() - tRun;
|
|
59
102
|
}
|
|
60
103
|
catch (e) {
|
|
61
|
-
await
|
|
62
|
-
await server?.close();
|
|
104
|
+
await session.close();
|
|
63
105
|
throw e;
|
|
64
106
|
}
|
|
65
107
|
const rec = recorder;
|
|
66
108
|
if (!rec || !scene) {
|
|
67
|
-
await
|
|
68
|
-
await server?.close();
|
|
109
|
+
await session.close();
|
|
69
110
|
throw new Error("scenario never started recording (call scene.goto first)");
|
|
70
111
|
}
|
|
71
112
|
const { durationMs, frameCount } = await rec.stop();
|
|
72
|
-
await
|
|
73
|
-
await server?.close();
|
|
113
|
+
await session.close();
|
|
74
114
|
const videoPath = path.join(outDir, "recording.mp4");
|
|
75
115
|
const tEnc = Date.now();
|
|
76
116
|
await rec.encode(videoPath, 30);
|
|
@@ -79,27 +119,28 @@ export async function recordScenario(input, opts = {}) {
|
|
|
79
119
|
fs.rmSync(framesDir, { recursive: true, force: true });
|
|
80
120
|
timings.recordTotalMs = Date.now() - t0;
|
|
81
121
|
const composed = compose({
|
|
82
|
-
name: scenario.name,
|
|
122
|
+
name: session.scenario.name,
|
|
83
123
|
outDir,
|
|
84
124
|
videoPath,
|
|
85
125
|
durationMs,
|
|
86
126
|
frameCount,
|
|
87
|
-
viewport,
|
|
127
|
+
viewport: session.viewport,
|
|
88
128
|
frameSize: rec.frameSize,
|
|
89
129
|
actions: scene.actions,
|
|
90
130
|
captions: scene.captions,
|
|
91
131
|
samples: scene.samples,
|
|
92
132
|
frameTimes,
|
|
93
133
|
timings,
|
|
94
|
-
zoom: scenario.zoom,
|
|
95
|
-
look: scenario.look,
|
|
96
|
-
trimIdle: scenario.trimIdle,
|
|
134
|
+
zoom: session.scenario.zoom,
|
|
135
|
+
look: session.scenario.look,
|
|
136
|
+
trimIdle: session.scenario.trimIdle,
|
|
137
|
+
cursor: session.scenario.cursor,
|
|
97
138
|
});
|
|
98
139
|
const result = {
|
|
99
140
|
videoPath,
|
|
100
141
|
durationMs,
|
|
101
142
|
frameSize: rec.frameSize,
|
|
102
|
-
viewport,
|
|
143
|
+
viewport: session.viewport,
|
|
103
144
|
samples: scene.samples,
|
|
104
145
|
actions: scene.actions,
|
|
105
146
|
captions: scene.captions,
|
|
@@ -109,3 +150,41 @@ export async function recordScenario(input, opts = {}) {
|
|
|
109
150
|
};
|
|
110
151
|
return { ...composed, result, outDir, zoomRegions: composed.timeline.zoomRegions };
|
|
111
152
|
}
|
|
153
|
+
/**
|
|
154
|
+
* Runs a scenario quickly in fast mode (no ffmpeg, no CDP screencast, no output files).
|
|
155
|
+
* Invokes `atEnd(page)` on both success and failure before closing the browser and static server.
|
|
156
|
+
*/
|
|
157
|
+
export async function dryRunScenario(input, opts = {}) {
|
|
158
|
+
const t0 = performance.now();
|
|
159
|
+
const session = await openScenarioSession(input, opts);
|
|
160
|
+
try {
|
|
161
|
+
const startClock = async () => {
|
|
162
|
+
const origin = performance.now();
|
|
163
|
+
return { now: () => performance.now() - origin };
|
|
164
|
+
};
|
|
165
|
+
const scene = new Scene(session.page, session.viewport, startClock, {
|
|
166
|
+
seed: session.scenario.seed,
|
|
167
|
+
pacing: session.scenario.pacing,
|
|
168
|
+
fast: true,
|
|
169
|
+
});
|
|
170
|
+
try {
|
|
171
|
+
await session.scenario.run(scene, { baseUrl: session.baseUrl });
|
|
172
|
+
const durationMs = Math.round(performance.now() - t0);
|
|
173
|
+
await opts.atEnd?.(session.page);
|
|
174
|
+
return { ok: true, actions: scene.actions, durationMs };
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
const durationMs = Math.round(performance.now() - t0);
|
|
178
|
+
const error = {
|
|
179
|
+
message: e instanceof Error ? e.message : String(e),
|
|
180
|
+
actionIndex: scene.actions.length,
|
|
181
|
+
};
|
|
182
|
+
await opts.onFailure?.(error, session.page);
|
|
183
|
+
await opts.atEnd?.(session.page);
|
|
184
|
+
return { ok: false, actions: scene.actions, durationMs, error };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
await session.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
package/dist/recorder.d.ts
CHANGED
package/dist/recorder.js
CHANGED
|
@@ -13,6 +13,7 @@ import { ffmpegBin } from "./env.js";
|
|
|
13
13
|
export class ScreencastRecorder {
|
|
14
14
|
session = null;
|
|
15
15
|
frames = [];
|
|
16
|
+
lastFrameData = null;
|
|
16
17
|
pending = [];
|
|
17
18
|
stopTs = 0;
|
|
18
19
|
firstFrame;
|
|
@@ -39,6 +40,13 @@ export class ScreencastRecorder {
|
|
|
39
40
|
this.session = session;
|
|
40
41
|
session.on("Page.screencastFrame", (ev) => {
|
|
41
42
|
const index = this.frames.length;
|
|
43
|
+
// Skip byte-identical repaints (e.g. idle WebGL/Three.js requestAnimationFrame loops)
|
|
44
|
+
// so encode() holds the previous frame and frameTimes reflects real visual changes.
|
|
45
|
+
if (index > 0 && ev.data === this.lastFrameData) {
|
|
46
|
+
session.send("Page.screencastFrameAck", { sessionId: ev.sessionId }).catch(() => { });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
this.lastFrameData = ev.data;
|
|
42
50
|
const file = path.join(this.dir, `f${String(index).padStart(6, "0")}.jpg`);
|
|
43
51
|
const ts = (ev.metadata.timestamp ?? Date.now() / 1000) * 1000;
|
|
44
52
|
this.frames.push({ file, ts });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Q as e,_t as t,ct as n,ht as r,mt as i,q as a,st as o,yt as s}from"./index-CE-lli1m.js";var c=32767;function l(e,t){return(e<<17)+(t<<2)}var u=new class{constructor(t){this._buckets=new Map,this._screens=new e,this._enableFullScreen=!1,this.canvasOptions=t||{}}get enableFullScreen(){return t(s,`CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize.`),this._enableFullScreen}set enableFullScreen(e){t(s,`CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize.`),this._enableFullScreen=e}_createCanvasAndContext(e,t){let n=a.get().createCanvas();return n.width=e,n.height=t,{canvas:n,context:n.getContext(`2d`)}}getOptimalCanvasAndContext(e,t,r=1){let{width:i,height:a}=this.getOptimalSize(e,t,r);(i>c||a>c)&&n(`CanvasPool: ${i}x${a} is larger than the ${c}px pool key limit, canvases of this size may be pooled together`);let o=l(i,a),s=this._buckets.get(o);s||(s=[],this._buckets.set(o,s));let u=s.pop();return u||=this._createCanvasAndContext(i,a),u}getOptimalSize(e,t,n=1){let i=Math.ceil(e*n-1e-6),a=Math.ceil(t*n-1e-6),o=r(i),s=this._screens.getFittingWidth(i),c=r(a),l=this._screens.getFittingHeight(a);return{width:s===void 0?o:Math.min(s,o),height:l===void 0?c:Math.min(l,c)}}returnCanvasAndContext(e){let{width:t,height:n}=e.canvas,r=this._buckets.get(l(t,n));r&&(e.context.resetTransform(),e.context.clearRect(0,0,t,n),r.push(e))}setScreenSize(e,t,n){this._screens.set(e,t,n)&&this._pruneScreenCanvases()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenCanvases()}clear(){this._buckets.clear()}_pruneScreenCanvases(){for(let[e]of this._buckets){let t=e>>>17,n=e>>>2&32767;(!i(t)&&!this._screens.hasWidth(t)||!i(n)&&!this._screens.hasHeight(n))&&this._buckets.delete(e)}}};o.register(u);export{u as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ct as e,Dt as t,Et as n,K as r,L as i,O as a,St as o,a as s,ct as c,dt as l,et as u,i as d,lt as f,nt as p,o as m,q as h,r as g,s as _,t as v}from"./index-CE-lli1m.js";import{a as y,c as b,i as x,l as S,o as C,r as w,s as T,t as E}from"./RenderTargetSystem-Dk1U4wDJ.js";import{n as D,t as O}from"./canvasUtils-KRroregW.js";var k=class e{static _getPatternRepeat(e,t){let n=e&&e!==`clamp-to-edge`,r=t&&t!==`clamp-to-edge`;return n&&r?`repeat`:n?`repeat-x`:r?`repeat-y`:`no-repeat`}start(e,t,n){}execute(t,n){let r=n.elements;if(!r||!r.length)return;let i=t.renderer,a=i.canvasContext,s=a.activeContext;for(let t=0;t<r.length;t++){let c=r[t];if(!c.packAsQuad)continue;let l=c,d=l.texture,f=d?O.getCanvasSource(d):null;if(!f)continue;let m=d.source.style,h=a.smoothProperty,g=m.scaleMode!==`nearest`;s[h]!==g&&(s[h]=g),a.setBlendMode(n.blendMode);let _=i.globalUniforms.globalUniformData?.worldColor??0xffffffff,v=l.color,y=(_>>>24&255)/255,b=(v>>>24&255)/255,x=i.filter?.alphaMultiplier??1,S=y*b*x;if(S<=0)continue;s.globalAlpha=S;let C=_&0xffffff,w=v&0xffffff,T=u(p(w,C)),E=d.frame,D=m.addressModeU??m.addressMode,k=m.addressModeV??m.addressMode,A=e._getPatternRepeat(D,k),j=d.source._resolution??d.source.resolution??1,M=l.renderable?.renderGroup?.isCachedAsTexture,N=E.x*j,P=E.y*j,F=E.width*j,I=E.height*j,L=l.bounds,R=i.renderTarget.renderTarget.isRoot,z=L.minX,B=L.minY,V=L.maxX-L.minX,H=L.maxY-L.minY,U=d.rotate,W=d.uvs,G=Math.min(W.x0,W.x1,W.x2,W.x3,W.y0,W.y1,W.y2,W.y3),K=Math.max(W.x0,W.x1,W.x2,W.x3,W.y0,W.y1,W.y2,W.y3),q=A!==`no-repeat`&&(G<0||K>1),J=U&&(!!q||T===0xffffff&&!U);J?(e._tempPatternMatrix.copyFrom(l.transform),o.matrixAppendRotationInv(e._tempPatternMatrix,U,z,B,V,H),a.setContextTransform(e._tempPatternMatrix,l.roundPixels===1,void 0,M&&R)):a.setContextTransform(l.transform,l.roundPixels===1,void 0,M&&R);let Y=V,X=H,Z=J?0:z,Q=J?0:B;if(!J&&l.roundPixels===1&&(Z|=0,Q|=0),q){let t=f,n=T!==0xffffff&&!U,r=E.width<=d.source.width&&E.height<=d.source.height;n&&r&&(t=O.getTintedCanvas({texture:d},T));let i=s.createPattern(t,A);if(!i)continue;let a=Y,o=X;if(a===0||o===0)continue;let c=1/a,l=1/o,u=(W.x1-W.x0)*c,p=(W.y1-W.y0)*c,m=(W.x3-W.x0)*l,h=(W.y3-W.y0)*l,g=W.x0-u*Z-m*Q,_=W.y0-p*Z-h*Q,v=d.source.pixelWidth,y=d.source.pixelHeight;e._tempPatternMatrix.set(u*v,p*y,m*v,h*y,g*v,_*y),O.applyPatternTransform(i,e._tempPatternMatrix),s.fillStyle=i,s.fillRect(Z,Q,Y,X)}else{let e=T!==0xffffff||U?O.getTintedCanvas({texture:d},T):f,t=e!==f;s.drawImage(e,t?0:N,t?0:P,t?e.width:F,t?e.height:I,Z,Q,Y,X)}}}};k._tempPatternMatrix=new e,k.extension={type:[n.CanvasPipesAdaptor],name:`batch`};var A=k,j=class{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;let i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;this._colorStackIndex--;let i=r[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}};j.extension={type:[n.CanvasPipes],name:`colorMask`};function M(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function N(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;M(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.moveTo(n.x+n.radius,n.y),e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?(e.moveTo(n.x+n.halfWidth,n.y),e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2)):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.moveTo(1,0),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function P(e,t,n){let r=[],i=[],a=[];if(!d[t.type]?.build(t,r))return!1;let o=t.closePath??!0;_(r,n,!1,o,i,a);for(let t=0;t<a.length;t+=3){let n=a[t]*2,r=a[t+1]*2,o=a[t+2]*2;e.moveTo(i[n],i[n+1]),e.lineTo(i[r],i[r+1]),e.lineTo(i[o],i[o+1]),e.closePath()}return!0}function F(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),N(e,r.shape),a&&e.restore()}return!0}var I=class{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`popMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!==`pushMaskBegin`&&e.action!==`popMaskEnd`)return;let t=this._renderer,n=t.canvasContext,r=n?.activeContext;if(!r)return;if(e.action===`popMaskEnd`){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce(`inverse`,`CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.`);let i=e.mask.mask;if(!(i instanceof v)){this._warnOnce(`nonGraphics`,`CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask.`),this._canvasMaskStack.push(!1);return}let a=i,o=a.context?.instructions;if(!o?.length){this._canvasMaskStack.push(!1);return}r.save(),n.setContextTransform(a.groupTransform,(t._roundPixels|a._roundPixels)===1),r.beginPath();let s=!1,c=!1;for(let e=0;e<o.length;e++){let t=o[e],n=t.action;if(n!==`fill`&&n!==`stroke`)continue;let i=t.data,a=i?.path?.shapePath;if(!a?.shapePrimitives?.length)continue;let l=n===`stroke`,u=a.shapePrimitives;for(let e=0;e<u.length;e++){let t=u[e];if(!t?.shape)continue;let n=t.transform,a=n&&!n.isIdentity();a&&(r.save(),r.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),l&&i.style?s=P(r,t.shape,i.style)||s:(N(r,t.shape),c=F(r,t.holes)||c,s=!0),a&&r.restore()}}s?(c?r.clip(`evenodd`):r.clip(),this._canvasMaskStack.push(!0)):(r.restore(),this._canvasMaskStack.push(!1))}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),c(t))}};I.extension={type:[n.CanvasPipes],name:`stencilMask`};var L=`source-over`;function R(){let e=D(),t=Object.create(null);return t.inherit=L,t.none=L,t.normal=`source-over`,t.add=`lighter`,t.multiply=e?`multiply`:L,t.screen=e?`screen`:L,t.overlay=e?`overlay`:L,t.darken=e?`darken`:L,t.lighten=e?`lighten`:L,t[`color-dodge`]=e?`color-dodge`:L,t[`color-burn`]=e?`color-burn`:L,t[`hard-light`]=e?`hard-light`:L,t[`soft-light`]=e?`soft-light`:L,t.difference=e?`difference`:L,t.exclusion=e?`exclusion`:L,t.saturation=e?`saturation`:L,t.color=e?`color`:L,t.luminosity=e?`luminosity`:L,t[`linear-burn`]=e?`color-burn`:L,t[`linear-dodge`]=e?`color-dodge`:L,t[`linear-light`]=e?`hard-light`:L,t[`pin-light`]=e?`hard-light`:L,t[`vivid-light`]=e?`hard-light`:L,t[`hard-mix`]=L,t.negation=e?`difference`:L,t[`normal-npm`]=t.normal,t[`add-npm`]=t.add,t[`screen-npm`]=t.screen,t.erase=`destination-out`,t.subtract=L,t.divide=L,t.min=L,t.max=L,t}var z=new e,B=class{constructor(e){this.activeResolution=1,this.smoothProperty=`imageSmoothingEnabled`,this.blendModes=R(),this._activeBlendMode=`normal`,this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){let e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext(`2d`,{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){let e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty=`webkitImageSmoothingEnabled`:e.mozImageSmoothingEnabled?this.smoothProperty=`mozImageSmoothingEnabled`:e.oImageSmoothingEnabled?this.smoothProperty=`oImageSmoothingEnabled`:e.msImageSmoothingEnabled&&(this.smoothProperty=`msImageSmoothingEnabled`)}}setContextTransform(t,n,r,i){let a=i?e.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||e.IDENTITY,o=z;o.copyFrom(a),o.append(t);let s=this._projTransform,c=this.activeResolution;if(r||=c,s){let t=e.shared;t.copyFrom(o),t.prepend(s),o=t}n?this.activeContext.setTransform(o.a*r,o.b*r,o.c*r,o.d*r,o.tx*c|0,o.ty*c|0):this.activeContext.setTransform(o.a*r,o.b*r,o.c*r,o.d*r,o.tx*c,o.ty*c)}clear(e,t){let n=this.activeContext,r=this._renderer;if(n.clearRect(0,0,r.width,r.height),e){let i=f.shared.setValue(e);n.globalAlpha=t??i.alpha,n.fillStyle=i.toHex(),n.fillRect(0,0,r.width,r.height),n.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;let t=this.blendModes[e];t?this.activeContext.globalCompositeOperation=t:(this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation=`source-over`)}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}};B.extension={type:[n.CanvasSystem],name:`canvasContext`};var V=class{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0,this.minUniformBufferOffsetAlignment=0}init(){}};V.extension={type:[n.CanvasSystem],name:`limits`};var H=`#808080`,U=new e,W=new e,G=new e,K=new e,q=new e;function J(e,t,n){e.beginPath();for(let r=0;r<n.length;r+=3){let i=n[r]*2,a=n[r+1]*2,o=n[r+2]*2;e.moveTo(t[i],t[i+1]),e.lineTo(t[a],t[a+1]),e.lineTo(t[o],t[o+1]),e.closePath()}e.fill()}function Y(e){return`#${(e&0xffffff).toString(16).padStart(6,`0`)}`}function X(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function Z(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;X(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function Q(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),Z(e,r.shape),a&&e.restore()}return!0}function ee(e,t,n,r){let i=e.fill;if(i instanceof m){i.buildGradient();let a=i.texture;if(a){let o=O.getTintedPattern(a,t),s=n?K.copyFrom(n).scale(a.source.pixelWidth,a.source.pixelHeight):K.copyFrom(i.transform);return r&&!e.textureSpace&&s.append(r),O.applyPatternTransform(o,s),o}}if(i instanceof g){let e=O.getTintedPattern(i.texture,t);return O.applyPatternTransform(e,i.transform,!1),e}let a=e.texture;if(a&&a!==l.WHITE){if(!a.source.resource)return H;let r=O.getTintedPattern(a,t),i=e.matrix;if(n){let{resolution:e}=a.source;if(i=K.copyFrom(n),a.rotate){let{uvs:t,orig:n}=a;i.prepend(q.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0).invert()).scale(n.width*e,n.height*e)}else i.scale(a.source.pixelWidth,a.source.pixelHeight).translate(-a.frame.x*e,-a.frame.y*e)}return O.applyPatternTransform(r,i),r}return Y(t)}var $=class{constructor(){this.shader=null}contextChange(e){}execute(e,t){let n=e.renderer,r=n.canvasContext,i=r.activeContext,a=t.groupTransform,c=n.globalUniforms.globalUniformData?.worldColor??0xffffffff,f=t.groupColorAlpha,m=(c>>>24&255)/255,h=(f>>>24&255)/255,g=n.filter?.alphaMultiplier??1,v=m*h*g;if(v<=0)return;let y=c&0xffffff,b=f&0xffffff,x=u(p(b,y)),S=n._roundPixels|t._roundPixels;i.save(),r.setContextTransform(a,S===1),r.setBlendMode(t.groupBlendMode);let C=t.context.instructions;for(let e=0;e<C.length;e++){let t=C[e];if(t.action===`texture`){let e=t.data,n=e.image,s=n?O.getCanvasSource(n):null;if(!s)continue;let c=e.alpha*v;if(c<=0)continue;let l=p(e.style,x);i.globalAlpha=c;let u=s;l!==0xffffff&&(u=O.getTintedCanvas({texture:n},l));let d=n.frame,f=n.source._resolution??n.source.resolution??1,m=d.x*f,h=d.y*f,g=d.width*f,_=d.height*f;u!==s&&(m=0,h=0);let y=e.transform,b=y&&!y.isIdentity(),C=n.rotate;b||C?(U.copyFrom(a),b&&U.append(y),C&&o.matrixAppendRotationInv(U,C,e.dx,e.dy,e.dw,e.dh),r.setContextTransform(U,S===1)):r.setContextTransform(a,S===1),i.drawImage(u,m,h,u===s?g:u.width,u===s?_:u.height,C?0:e.dx,C?0:e.dy,e.dw,e.dh),(b||C)&&r.setContextTransform(a,S===1);continue}let n=t.data,c=n?.path?.shapePath;if(!c?.shapePrimitives?.length)continue;let u=n.style,f=p(u.color,x),m=u.alpha*v;if(m<=0)continue;let h=t.action===`stroke`;if(i.globalAlpha=m,h){let e=u;i.lineWidth=e.width,i.lineCap=e.cap,i.lineJoin=e.join,i.miterLimit=e.miterLimit}let g=c.shapePrimitives;if(!h&&n.hole?.shapePath?.shapePrimitives?.length){let e=g[g.length-1];e.holes=n.hole.shapePath.shapePrimitives}for(let e=0;e<g.length;e++){let t=g[e];if(!t?.shape)continue;let n=t.transform,r=n&&!n.isIdentity(),o=u.texture&&u.texture!==l.WHITE,c=u.textureSpace===`global`?n:null,p=ee(u,f,o?s(W,u,t.shape,c):null,r?G.copyFrom(a).append(n):a);if(r&&(i.save(),i.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),h){let e=u;if(e.alignment!==.5&&!e.pixelLine){let n=[],r=[],a=[];if(d[t.shape.type]?.build(t.shape,n)){let o=t.shape.closePath??!0;_(n,e,!1,o,r,a),i.fillStyle=p,J(i,r,a)}else i.strokeStyle=p,i.beginPath(),Z(i,t.shape),i.stroke()}else i.strokeStyle=p,i.beginPath(),Z(i,t.shape),i.stroke()}else i.fillStyle=p,i.beginPath(),Z(i,t.shape),Q(i,t.holes)?i.fill(`evenodd`):i.fill();r&&i.restore()}}i.restore()}destroy(){this.shader=null}};$.extension={type:[n.CanvasPipesAdaptor],name:`graphics`};var te=class{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){let t=e.colorTexture,{canvas:n,context:r}=this._ensureCanvas(t);return{canvas:n,context:r,width:n.width,height:n.height}}resizeGpuRenderTarget(e){let t=e.colorTexture,{canvas:n}=this._ensureCanvas(t);n.width=e.pixelWidth,n.height=e.pixelHeight}startRenderPass(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=i.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,n,r)}clear(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(i.setTransform(1,0,0,1,0,0),i.clearRect(a.x,a.y,a.width,a.height),n){let e=f.shared.setValue(n);e.alpha>0&&(i.globalAlpha=e.alpha,i.fillStyle=e.toHex(),i.fillRect(a.x,a.y,a.width,a.height),i.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,n,r,i){let a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,o=t.source,{context:s}=this._ensureCanvas(o),c=i?.x??0,l=i?.y??0;return s.drawImage(a,n.x,n.y,r.width,r.height,c,l,r.width,r.height),o.update(),t}copyDepthTexture(e,t,n,r,i){c(`[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer`)}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;t&&r.test(t)||(t=h.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);let n=t.getContext(`2d`);return{canvas:t,context:n}}},ne=class extends E{constructor(e){super(e),this.adaptor=new te,this.adaptor.init(e,this)}};ne.extension={type:[n.CanvasSystem],name:`renderTarget`};var re=class{constructor(e){}init(){}initSource(e){}generateCanvas(e){let t=h.get().createCanvas(),n=t.getContext(`2d`),r=O.getCanvasSource(e);if(!r)return t;let i=e.frame,a=e.source._resolution??e.source.resolution??1,o=i.x*a,s=i.y*a,c=i.width*a,l=i.height*a;return t.width=Math.ceil(c),t.height=Math.ceil(l),n.drawImage(r,o,s,c,l,0,0,c,l),t}getPixels(e){let t=this.generateCanvas(e);return{pixels:t.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}};re.extension={type:[n.CanvasSystem],name:`texture`};var ie=[...w,B,V,re,ne],ae=[x,S,y,C,b,I,j,T],oe=[A,$],se=[],ce=[],le=[],ue=[];t.handleByNamedList(n.CanvasSystem,se),t.handleByNamedList(n.CanvasPipes,ce),t.handleByNamedList(n.CanvasPipesAdaptor,le),t.handleByNamedList(n.CanvasLoader,ue),t.add(...ie,...ae,...oe);var de=class extends a{constructor(){let e={name:`canvas`,type:i.CANVAS,systems:se,renderPipes:ce,renderPipeAdaptors:le,loaders:ue};super(e)}};export{de as CanvasRenderer};
|