The clipFrame command takes an undistort flag, honoured only for full-frame reads to mirror need_undistortion_postprocess, so the engine applies BKE_tracking_distortion_exec on the fly. The reader exports every distortion model's coefficients and the Camera Data panel edits focal, sensor, model and the active model's fields (display rounded past the DNA float32 noise). CLIP_OT_track_copy_color gets its panel button, and plane use_auto_keying round-trips with an off-path that re-derives the plane from point-track motion instead of keying. The headed suite grows to 26 Clip cases with [clip-undistort] (border- concentrated pixel difference plus a zeroed-coefficient identity check) and the extended copy-colour/auto-keying assertions: 28/28 PASS, receipt tests/golden/CLIP-HEADED-20261204-124651, wasm 3c81eb06. Acceptance stays NOT_CLAIMED. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2017 lines
124 KiB
TypeScript
2017 lines
124 KiB
TypeScript
import crypto from "node:crypto";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { expect, test, type TestInfo } from "@playwright/test";
|
|
import { markerDeleteSource, markerWriteSource, parsePlaneTrackIndices, parseTrackIndices, planeMarkerWriteSource } from "../../app/src/tracking/clipEditorCommands";
|
|
import { observeNative } from "../fixtures/native-ui-workflow";
|
|
|
|
const root = path.resolve(import.meta.dirname, "../../..");
|
|
const blendPath = process.env.CLIP_BLEND_FIXTURE ?? path.join(root, "blender-5.2.0/tests/files/tracking/tripod-motion.blend");
|
|
const footagePath = process.env.CLIP_FOOTAGE_FIXTURE ?? path.join(root, "blender-5.2.0/tests/files/tracking/footage/tripod-motion.avi");
|
|
const blend = fs.readFileSync(blendPath);
|
|
const footage = fs.readFileSync(footagePath);
|
|
const blendSha256 = crypto.createHash("sha256").update(blend).digest("hex");
|
|
const footageSha256 = crypto.createHash("sha256").update(footage).digest("hex");
|
|
const solveBlendPath = process.env.CLIP_SOLVE_BLEND_FIXTURE ?? path.join(root, "blender-5.2.0/tests/files/tracking/synthetic-tripod-motion.blend");
|
|
const solveFootagePath = process.env.CLIP_SOLVE_FOOTAGE_FIXTURE ?? path.join(root, "blender-5.2.0/tests/files/tracking/footage/synthetic-tripod-motion.avi");
|
|
const solveBlend = fs.readFileSync(solveBlendPath);
|
|
const solveFootage = fs.readFileSync(solveFootagePath);
|
|
const solveFootageSha256 = crypto.createHash("sha256").update(solveFootage).digest("hex");
|
|
|
|
type ClipMode = "read" | "frame" | "missing" | "reopen";
|
|
|
|
async function runClip(page: import("@playwright/test").Page, mode: ClipMode) {
|
|
return page.evaluate(async ({ mode, blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const makeResources = () => [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }];
|
|
const summarize = (project: any) => {
|
|
const clips = project?.clips ?? [];
|
|
const clip = clips[0];
|
|
if (!clip) return null;
|
|
const tracks = (clip.tracks ?? []) as Array<{ id: string; markers: Array<{ frame: number }> }>;
|
|
const planes = (clip.planeTracks ?? []) as Array<{ id: string; pointTrackIds: string[]; keyframes: Array<{ frame: number; corners: number[][] }> }>;
|
|
const solve = clip.cameraSolve as any;
|
|
return {
|
|
clipId: clip.id as string,
|
|
name: clip.name as string,
|
|
sourcePath: clip.sourcePath as string | undefined,
|
|
sourceStatus: clip.sourceStatus as string,
|
|
sourceSha256: clip.sourceSha256 as string | undefined,
|
|
width: clip.width as number,
|
|
height: clip.height as number,
|
|
frameStart: clip.frameStart as number,
|
|
frameEnd: clip.frameEnd as number,
|
|
fpsNumerator: clip.fpsNumerator as number | undefined,
|
|
fpsDenominator: clip.fpsDenominator as number | undefined,
|
|
trackIds: tracks.map((track) => track.id),
|
|
markerFrames: tracks.map((track) => track.markers.length),
|
|
planeTrackCount: planes.length,
|
|
planeTrackIds: planes.map((plane) => plane.id),
|
|
planePointTrackCounts: planes.map((plane) => plane.pointTrackIds.length),
|
|
planeKeyframeCounts: planes.map((plane) => plane.keyframes.length),
|
|
cameraSolveStatus: (solve?.status ?? null) as string | null,
|
|
cameraSolveSha: solve?.sourceSha256 as string | undefined,
|
|
cameraSolveSettingsHash: solve?.settingsHash as string | undefined,
|
|
cameraSolveFrames: (solve?.solvedFrames ?? []).length as number,
|
|
cameraSolveFocal: solve?.focalLength as number | undefined,
|
|
cameraSolveError: solve?.reprojectionError as number | undefined,
|
|
bindingCount: (project?.bindings ?? []).length,
|
|
};
|
|
};
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], mode === "missing" ? [] : makeResources());
|
|
const first = summarize(opened.snapshot.trackingMasks);
|
|
if (!first) throw new Error("trackingMasks.clips is empty");
|
|
if (mode === "read" || mode === "missing") return { mode, clip: first };
|
|
if (mode === "frame") {
|
|
const decoded = await client.movieClipFrame(first.clipId, first.frameStart);
|
|
const pixels = Uint8Array.from(atob(decoded.pixelsBase64), (character) => character.charCodeAt(0));
|
|
let minimum = 255;
|
|
let maximum = 0;
|
|
for (let index = 0; index < pixels.length; index += 997) {
|
|
minimum = Math.min(minimum, pixels[index]);
|
|
maximum = Math.max(maximum, pixels[index]);
|
|
}
|
|
return { mode, clip: first, decoded: { width: decoded.width, height: decoded.height, byteLength: pixels.length, minimum, maximum } };
|
|
}
|
|
const saved = await client.saveBlend();
|
|
/* Reopen on the same client: a second concurrent engine would hold the
|
|
* native OPFS file lock. */
|
|
const second = await client.openBlend(saved.slice(0), undefined, undefined, [], [], makeResources());
|
|
return { mode, clip: first, reopened: summarize(second.snapshot.trackingMasks) };
|
|
}
|
|
catch (error) { return { mode, failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { mode, blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64") });
|
|
}
|
|
|
|
async function runSolve(page: import("@playwright/test").Page) {
|
|
return page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/synthetic-tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
return {
|
|
clipId: clip.id,
|
|
sourceStatus: clip.sourceStatus,
|
|
sourceSha256: clip.sourceSha256,
|
|
cameraSolve: clip.cameraSolve ?? null,
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: solveBlend.toString("base64"), footageBase64: solveFootage.toString("base64") });
|
|
}
|
|
|
|
async function runTrackMarkers(page: import("@playwright/test").Page) {
|
|
return page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const makeResources = () => [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }];
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const markerFrames = (clipValue: any, trackId: string) =>
|
|
((clipValue?.tracks ?? []).find((track: any) => track.id === trackId)?.markers ?? []).map((marker: any) => marker.frame as number);
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], makeResources());
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const keyed = (clip.tracks ?? []).flatMap((track: any) =>
|
|
track.markers.filter((marker: any) => marker.keyframe).map((marker: any) => ({ trackId: track.id as string, frame: marker.frame as number })));
|
|
const startFrame = keyed[0]?.frame ?? clip.frameStart;
|
|
const trackId = keyed[0]?.trackId ?? clip.tracks[0]?.id;
|
|
const selectSource = `import bpy\nclip = bpy.data.movieclips.get(${JSON.stringify(clip.name)})\nfor tracking_object in clip.tracking.objects:\n for track in tracking_object.tracks:\n track.select = True\n track.lock = False\n for marker in track.markers:\n marker.mute = False\n`;
|
|
const selected = await client.executeEmbeddedPython(selectSource, "ClipTrackSelect.py", false);
|
|
const beforeCount = markerFrames(clip, trackId).length;
|
|
const single = await client.trackMarkers(clip.id, startFrame, false, false);
|
|
const afterSingle = clipOf(single.snapshot.trackingMasks);
|
|
const sequence = await client.trackMarkers(clip.id, startFrame, false, true);
|
|
return {
|
|
pythonState: selected.python.state,
|
|
clipId: clip.id as string,
|
|
startFrame,
|
|
trackId,
|
|
beforeCount,
|
|
single: {
|
|
lastFrame: single.lastFrame,
|
|
tracks: single.tracks,
|
|
afterCount: markerFrames(afterSingle, trackId).length,
|
|
hasNext: markerFrames(afterSingle, trackId).includes(startFrame + 1),
|
|
},
|
|
sequence: { lastFrame: sequence.lastFrame, tracks: sequence.tracks },
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64") });
|
|
}
|
|
|
|
async function runSolveCommand(page: import("@playwright/test").Page) {
|
|
return page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/synthetic-tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const beforeStatus = clip.cameraSolve?.status ?? null;
|
|
const solved = await client.solveCamera(clip.id);
|
|
const afterClip = solved.snapshot.trackingMasks?.clips?.[0];
|
|
return {
|
|
clipId: clip.id as string,
|
|
beforeStatus,
|
|
reprojectionError: solved.reprojectionError,
|
|
solvedFrames: solved.solvedFrames,
|
|
snapshotStatus: (afterClip?.cameraSolve?.status ?? null) as string | null,
|
|
snapshotFrames: ((afterClip?.cameraSolve?.solvedFrames ?? []) as number[]).length,
|
|
sourceStatus: afterClip?.sourceStatus as string | undefined,
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: solveBlend.toString("base64"), footageBase64: solveFootage.toString("base64") });
|
|
}
|
|
|
|
async function runProxy(page: import("@playwright/test").Page) {
|
|
return page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const makeResources = () => [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }];
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], makeResources());
|
|
const clip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const built = await client.rebuildClipProxies(clip.id, [25], 75);
|
|
const afterClip = built.snapshot.trackingMasks?.clips?.[0];
|
|
const frame = Math.min(clip.frameStart + 10, clip.frameEnd);
|
|
const decoded = await client.movieClipFrame(clip.id, frame, 25);
|
|
const pixels = Uint8Array.from(atob(decoded.pixelsBase64), (character) => character.charCodeAt(0));
|
|
let minimum = 255;
|
|
let maximum = 0;
|
|
for (let index = 0; index < pixels.length; index += 997) {
|
|
minimum = Math.min(minimum, pixels[index]);
|
|
maximum = Math.max(maximum, pixels[index]);
|
|
}
|
|
return {
|
|
clipId: clip.id as string,
|
|
sourceWidth: clip.width as number,
|
|
frame,
|
|
sizes: built.sizes,
|
|
proxy: afterClip?.proxy ?? null,
|
|
decoded: { width: decoded.width, height: decoded.height, byteLength: pixels.length, minimum, maximum },
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64") });
|
|
}
|
|
|
|
async function runPlane(page: import("@playwright/test").Page, writeSource: string | null, writeFrame: number) {
|
|
return page.evaluate(async ({ blendBase64, footageBase64, writeSource, writeFrame }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const makeResources = () => [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }];
|
|
const planesOf = (project: any) => (project?.clips?.[0]?.planeTracks ?? []) as Array<{ id: string; name: string; pointTrackIds: string[]; keyframes: Array<{ frame: number; corners: number[][] }> }>;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], makeResources());
|
|
const clip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const before = planesOf(opened.snapshot.trackingMasks);
|
|
const trackIds = clip.tracks.slice(0, 4).map((track) => track.id);
|
|
const frame = clip.frameStart + 10;
|
|
const created = await client.createPlaneTrack(clip.id, trackIds, frame);
|
|
const afterCreate = planesOf(created.snapshot.trackingMasks);
|
|
const plane = afterCreate[afterCreate.length - 1] ?? null;
|
|
let edited = null;
|
|
if (writeSource && plane) {
|
|
const written = await client.executeEmbeddedPython(writeSource, "ClipPlaneMarkerEdit.py", false);
|
|
edited = planesOf(written.snapshot.trackingMasks).find((item) => item.id === plane.id) ?? null;
|
|
}
|
|
const saved = await client.saveBlend();
|
|
const reopened = await client.openBlend(saved.slice(0), undefined, undefined, [], [], makeResources());
|
|
const persisted = planesOf(reopened.snapshot.trackingMasks).find((item) => item.id === plane?.id) ?? null;
|
|
return { clipId: clip.id, frame, beforeCount: before.length, createdName: created.planeName, afterCount: afterCreate.length, plane, edited, persisted, writeFrame };
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64"), writeSource, writeFrame });
|
|
}
|
|
|
|
async function attach(testInfo: TestInfo, name: string, payload: unknown) {
|
|
/* A path-backed attachment lands on disk so the headed runner can copy it
|
|
* into the receipt as case evidence. */
|
|
const file = testInfo.outputPath(`${name}.json`);
|
|
fs.writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`);
|
|
await testInfo.attach(name, { path: file, contentType: "application/json" });
|
|
}
|
|
|
|
test.beforeEach(async ({ page }) => {
|
|
await page.goto("/");
|
|
});
|
|
|
|
test("[clip-read-web] reads the tripod MovieClip from the WASM engine", async ({ page }, testInfo) => {
|
|
const result = await runClip(page, "read");
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-read", result);
|
|
expect(result.clip.clipId).toMatch(/^movieclip:/);
|
|
expect(result.clip.sourcePath).toBe("//footage/tripod-motion.avi");
|
|
expect(result.clip.sourceStatus).toBe("AVAILABLE");
|
|
expect(result.clip.sourceSha256).toBe(footageSha256);
|
|
expect(result.clip.width).toBeGreaterThan(0);
|
|
expect(result.clip.height).toBeGreaterThan(0);
|
|
expect(result.clip.frameEnd).toBeGreaterThanOrEqual(result.clip.frameStart);
|
|
expect(result.clip.fpsNumerator! / result.clip.fpsDenominator!).toBeGreaterThan(0);
|
|
expect(result.clip.trackIds.length).toBeGreaterThan(0);
|
|
expect(result.clip.markerFrames.reduce((count, value) => count + value, 0)).toBeGreaterThan(0);
|
|
expect(result.clip.bindingCount).toBeGreaterThan(0);
|
|
});
|
|
|
|
test("[clip-frame-web] decodes the clip frame to RGBA pixels", async ({ page }, testInfo) => {
|
|
const result = await runClip(page, "frame");
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-frame", result);
|
|
expect(result.decoded?.width).toBe(result.clip.width);
|
|
expect(result.decoded?.height).toBe(result.clip.height);
|
|
expect(result.decoded?.byteLength).toBe(result.decoded!.width * result.decoded!.height * 4);
|
|
expect(result.decoded!.maximum).toBeGreaterThan(result.decoded!.minimum);
|
|
});
|
|
|
|
test("[clip-missing-web] keeps the clip while the footage is absent", async ({ page }, testInfo) => {
|
|
const result = await runClip(page, "missing");
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-missing", result);
|
|
expect(result.clip.clipId).toMatch(/^movieclip:/);
|
|
expect(result.clip.sourceStatus).toBe("MISSING");
|
|
expect(result.clip.sourceSha256).toBeUndefined();
|
|
expect(result.clip.trackIds.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
test("[clip-reopen-web] keeps clip identity and tracking data through save and reopen", async ({ page }, testInfo) => {
|
|
const result = await runClip(page, "reopen");
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-reopen", result);
|
|
expect(result.reopened).toBeTruthy();
|
|
expect(result.reopened!.clipId).toBe(result.clip.clipId);
|
|
expect(result.reopened!.sourceSha256).toBe(footageSha256);
|
|
expect(result.reopened!.width).toBe(result.clip.width);
|
|
expect(result.reopened!.height).toBe(result.clip.height);
|
|
expect(result.reopened!.trackIds).toEqual(result.clip.trackIds);
|
|
expect(result.reopened!.markerFrames).toEqual(result.clip.markerFrames);
|
|
expect(result.reopened!.bindingCount).toBe(result.clip.bindingCount);
|
|
});
|
|
|
|
test("[clip-edit-web] writes a tracking marker through the embedded bpy channel", async ({ page }, testInfo) => {
|
|
const readResult = await runClip(page, "read");
|
|
expect((readResult as any).failed ?? false, (readResult as any).message).toBe(false);
|
|
const clip = readResult.clip;
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const indices = parseTrackIndices(clip.trackIds[0]);
|
|
if (!indices) throw new Error("track id cannot be resolved");
|
|
const target = { clipName: clip.name, ...indices, frame: clip.frameEnd + 100 };
|
|
const writeSource = markerWriteSource({ ...target, x: 0.25, y: 0.75, mute: false });
|
|
const deleteSource = markerDeleteSource(target);
|
|
const result = await page.evaluate(async (input) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const makeResources = () => [{ path: "footage/tripod-motion.avi", buffer: bytes(input.footageBase64) }];
|
|
const marker = (project: any) => {
|
|
const clip = project?.clips?.[0];
|
|
const track = clip?.tracks?.find((item: any) => item.id === input.trackId);
|
|
return track?.markers?.find((item: any) => item.frame === input.frame) ?? null;
|
|
};
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(input.blendBase64), undefined, undefined, [], [], makeResources());
|
|
const firstClip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!firstClip) throw new Error("trackingMasks.clips is empty");
|
|
const written = await client.executeEmbeddedPython(input.writeSource, "ClipMarkerEdit.py", false);
|
|
const inserted = marker(written.snapshot.trackingMasks);
|
|
const saved = await client.saveBlend();
|
|
const reopened = await client.openBlend(saved.slice(0), undefined, undefined, [], [], makeResources());
|
|
const persisted = marker(reopened.snapshot.trackingMasks);
|
|
const deleted = await client.executeEmbeddedPython(input.deleteSource, "ClipMarkerDelete.py", false);
|
|
const removed = marker(deleted.snapshot.trackingMasks);
|
|
return { inserted, persisted, removed, pythonState: written.python.state, pythonOutput: written.python.output?.slice(0, 400) ?? "" };
|
|
}
|
|
finally { client.terminate(); }
|
|
}, {
|
|
blendBase64: blend.toString("base64"),
|
|
footageBase64: footage.toString("base64"),
|
|
frame: target.frame, trackId: clip.trackIds[0],
|
|
writeSource, deleteSource,
|
|
});
|
|
await attach(testInfo, "clip-edit", { clip, result });
|
|
expect(result.pythonState).toBe("DONE");
|
|
expect(result.inserted?.position[0]).toBeCloseTo(0.25, 4);
|
|
expect(result.inserted?.position[1]).toBeCloseTo(0.75, 4);
|
|
expect(result.persisted?.position[0]).toBeCloseTo(0.25, 4);
|
|
expect(result.persisted?.position[1]).toBeCloseTo(0.75, 4);
|
|
expect(result.removed).toBeNull();
|
|
});
|
|
|
|
test("[clip-solve-web] imports the reconstruction as a camera solve", async ({ page }, testInfo) => {
|
|
const result = await runSolve(page);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-solve", result);
|
|
expect(result.clipId).toMatch(/^movieclip:/);
|
|
expect(result.sourceStatus).toBe("AVAILABLE");
|
|
expect(result.sourceSha256).toBe(solveFootageSha256);
|
|
const solve = result.cameraSolve as {
|
|
status?: string; sourceSha256?: string; settingsHash?: string; solvedFrames?: number[];
|
|
focalLength?: number; reprojectionError?: number; principalPoint?: number[];
|
|
} | null;
|
|
expect(solve).toBeTruthy();
|
|
expect(solve!.status).toBe("SOLVED");
|
|
expect(solve!.sourceSha256).toBe(solveFootageSha256);
|
|
expect(solve!.settingsHash).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(solve!.solvedFrames?.length).toBe(50);
|
|
expect(solve!.focalLength).toBeGreaterThan(500);
|
|
expect(solve!.focalLength).toBeLessThan(2000);
|
|
expect(solve!.reprojectionError).toBeGreaterThanOrEqual(0);
|
|
expect(solve!.reprojectionError).toBeLessThan(1);
|
|
expect(solve!.principalPoint).toHaveLength(2);
|
|
});
|
|
|
|
test("[clip-track-web] tracks selected markers through the libmv engine", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await runTrackMarkers(page);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-track", result);
|
|
expect(result.pythonState).toBe("DONE");
|
|
expect(result.trackId).toMatch(/^track:\d+:\d+$/);
|
|
expect(result.single.tracks).toBeGreaterThan(0);
|
|
expect(result.single.lastFrame).toBe(result.startFrame + 1);
|
|
expect(result.single.afterCount).toBeGreaterThan(0);
|
|
expect(result.single.hasNext).toBe(true);
|
|
expect(result.sequence.lastFrame).toBeGreaterThan(result.startFrame);
|
|
});
|
|
|
|
test("[clip-solve-command-web] solves the camera through the engine", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await runSolveCommand(page);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-solve-command", result);
|
|
expect(result.clipId).toMatch(/^movieclip:/);
|
|
expect(result.solvedFrames).toBeGreaterThan(0);
|
|
expect(result.reprojectionError).toBeGreaterThanOrEqual(0);
|
|
expect(result.reprojectionError).toBeLessThan(10);
|
|
expect(result.snapshotStatus).toBe("SOLVED");
|
|
});
|
|
|
|
test("[clip-proxy-web] builds a proxy and decodes a proxy-sized frame", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await runProxy(page);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-proxy", result);
|
|
expect(result.sizes).toEqual([25]);
|
|
expect(result.proxy).toMatchObject({ enabled: true, buildSizes: 1, quality: 75 });
|
|
expect(result.decoded.width).toBeGreaterThan(0);
|
|
expect(result.decoded.width).toBeLessThanOrEqual(Math.ceil(result.sourceWidth / 2));
|
|
expect(result.decoded.byteLength).toBe(result.decoded.width * result.decoded.height * 4);
|
|
expect(result.decoded.maximum).toBeGreaterThan(result.decoded.minimum);
|
|
});
|
|
|
|
test("[clip-plane-web] creates and edits a plane track through the engine", async ({ page }, testInfo) => {
|
|
const readResult = await runClip(page, "read");
|
|
expect((readResult as any).failed ?? false, (readResult as any).message).toBe(false);
|
|
const clip = readResult.clip;
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const indices = parseTrackIndices(clip.trackIds[0]);
|
|
if (!indices) throw new Error("track id cannot be resolved");
|
|
const writeFrame = clip.frameStart + 10;
|
|
const writeSource = planeMarkerWriteSource({
|
|
clipName: clip.name,
|
|
objectIndex: indices.objectIndex,
|
|
planeIndex: 0,
|
|
frame: writeFrame,
|
|
corners: [[0.2, 0.2], [0.8, 0.2], [0.8, 0.8], [0.2, 0.8]],
|
|
});
|
|
const result = await runPlane(page, writeSource, writeFrame);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-plane", result);
|
|
expect(result.beforeCount).toBe(0);
|
|
expect(result.afterCount).toBe(1);
|
|
expect(typeof result.createdName).toBe("string");
|
|
expect(result.createdName.length).toBeGreaterThan(0);
|
|
const plane = result.plane as { id: string; pointTrackIds: string[]; keyframes: Array<{ frame: number; corners: number[][] }> } | null;
|
|
expect(plane).toBeTruthy();
|
|
expect(plane!.pointTrackIds).toHaveLength(4);
|
|
expect(plane!.keyframes.find((item) => item.frame === result.frame)).toBeTruthy();
|
|
const keyframe = (source: typeof plane) => source?.keyframes.find((item) => item.frame === result.writeFrame) ?? null;
|
|
const edited = keyframe(result.edited as typeof plane);
|
|
expect(edited).toBeTruthy();
|
|
expect(edited!.corners[0][0]).toBeCloseTo(0.2, 3);
|
|
expect(edited!.corners[0][1]).toBeCloseTo(0.2, 3);
|
|
expect(edited!.corners[2][0]).toBeCloseTo(0.8, 3);
|
|
expect(edited!.corners[2][1]).toBeCloseTo(0.8, 3);
|
|
const persisted = keyframe(result.persisted as typeof plane);
|
|
expect(persisted).toBeTruthy();
|
|
expect(persisted!.corners[0][0]).toBeCloseTo(0.2, 3);
|
|
expect(persisted!.corners[2][0]).toBeCloseTo(0.8, 3);
|
|
});
|
|
|
|
test("[clip-plane-drag-web] drags a plane corner in the Clip editor and writes it", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
await page.goto("/?ui=web");
|
|
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
|
|
await page.getByTestId("blend-file-input").setInputFiles(blendPath);
|
|
await expect(page.locator("main.blender-app")).toHaveAttribute("data-editor-workflow-status", "AVAILABLE", { timeout: 120_000 });
|
|
|
|
const area = page.locator(".viewport-area");
|
|
await expect(area.locator(".area-type-switch select")).toBeVisible({ timeout: 30_000 });
|
|
await area.locator(".area-type-switch select").selectOption("Clip");
|
|
await expect(area).toHaveAttribute("data-editor", "Clip", { timeout: 30_000 });
|
|
const surface = area.getByTestId("clip-editor-surface");
|
|
await expect(surface).toBeVisible({ timeout: 30_000 });
|
|
|
|
await surface.getByTestId("clip-list-item").first().click();
|
|
const checks = surface.getByTestId("clip-track-check");
|
|
for (let index = 0; index < 4; index++) await checks.nth(index).check();
|
|
await surface.getByTestId("clip-plane-create").click();
|
|
const planeItem = surface.getByTestId("clip-plane-item").first();
|
|
await expect(planeItem).toBeVisible({ timeout: 30_000 });
|
|
await planeItem.click();
|
|
|
|
const canvas = surface.getByTestId("clip-frame-canvas");
|
|
await expect(canvas).toHaveAttribute("data-plane-corners", /\[\[/, { timeout: 30_000 });
|
|
const before = JSON.parse((await canvas.getAttribute("data-plane-corners")) ?? "null") as number[][];
|
|
const box = await canvas.boundingBox();
|
|
if (!box) throw new Error("clip canvas has no layout box");
|
|
const target = [0.15, 0.15];
|
|
await page.mouse.move(box.x + before[0][0] * box.width, box.y + (1 - before[0][1]) * box.height);
|
|
await page.mouse.down();
|
|
await page.mouse.move(box.x + target[0] * box.width, box.y + (1 - target[1]) * box.height, { steps: 6 });
|
|
const cornersNow = async () => {
|
|
const raw = await canvas.getAttribute("data-plane-corners");
|
|
return raw ? (JSON.parse(raw) as number[][]) : null;
|
|
};
|
|
const draft = await cornersNow();
|
|
await page.mouse.up();
|
|
await page.waitForTimeout(3000);
|
|
const errorCount = await surface.getByTestId("clip-edit-error").count();
|
|
const editError = errorCount ? await surface.getByTestId("clip-edit-error").innerText() : null;
|
|
await attach(testInfo, "clip-plane-drag-draft", { before, draft, afterUp: await cornersNow(), editError, target });
|
|
await expect.poll(async () => {
|
|
const corners = await cornersNow();
|
|
return corners ? Math.abs(corners[0][0] - target[0]) < 0.02 && Math.abs(corners[0][1] - target[1]) < 0.02 : false;
|
|
}, { timeout: 60_000, message: "dragged plane corner did not reach the pointer target" }).toBe(true);
|
|
const after = await cornersNow();
|
|
await attach(testInfo, "clip-plane-drag", { before, after, target });
|
|
expect(after![0][0]).toBeCloseTo(target[0], 2);
|
|
expect(after![0][1]).toBeCloseTo(target[1], 2);
|
|
expect(after![1]).toEqual(before[1]);
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
async function openClipEditor(page: import("@playwright/test").Page, blendFile: string) {
|
|
await page.goto("/?ui=web");
|
|
await page.locator("main.blender-app").waitFor({ timeout: 120_000 });
|
|
await page.getByTestId("blend-file-input").setInputFiles(blendFile);
|
|
await expect(page.locator("main.blender-app")).toHaveAttribute("data-editor-workflow-status", "AVAILABLE", { timeout: 120_000 });
|
|
const area = page.locator(".viewport-area");
|
|
await expect(area.locator(".area-type-switch select")).toBeVisible({ timeout: 30_000 });
|
|
await area.locator(".area-type-switch select").selectOption("Clip");
|
|
await expect(area).toHaveAttribute("data-editor", "Clip", { timeout: 30_000 });
|
|
const surface = area.getByTestId("clip-editor-surface");
|
|
await expect(surface).toBeVisible({ timeout: 30_000 });
|
|
await surface.getByTestId("clip-list-item").first().click();
|
|
return surface;
|
|
}
|
|
|
|
/* Controlled range inputs ignore a plain value assignment; React tracks the
|
|
* native setter, so drive it through the prototype descriptor. */
|
|
async function setRangeValue(locator: import("@playwright/test").Locator, value: number) {
|
|
await locator.evaluate((element, next) => {
|
|
const input = element as HTMLInputElement;
|
|
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
|
|
setter?.call(input, String(next));
|
|
input.dispatchEvent(new Event("input", { bubbles: true }));
|
|
input.dispatchEvent(new Event("change", { bubbles: true }));
|
|
}, value);
|
|
}
|
|
|
|
/* The engine persists each mask edit, and while it does the renderer's DOM
|
|
* queries can stall; expect.poll drops the whole run when one sample blocks
|
|
* past its deadline, so the mask status phases poll on a plain loop. */
|
|
async function waitForMaskStatus(status: import("@playwright/test").Locator, expected: string, label: string, timeoutMs = 120_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
let last = "absent";
|
|
while (Date.now() < deadline) {
|
|
const texts = await status.allInnerTexts().catch((error: unknown) => { last = `error:${String(error)}`; return [] as string[]; });
|
|
if (texts.includes(expected)) return;
|
|
if (texts.length > 0) last = JSON.stringify(texts);
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
throw new Error(`${label}: status never reported "${expected}" (last ${last})`);
|
|
}
|
|
|
|
/* Status, value and checked waits after engine work all need their own loop:
|
|
* expect.poll drops the run when one stalled sample eats the deadline. */
|
|
async function waitForText(locator: import("@playwright/test").Locator, expected: string, label: string, timeoutMs = 120_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
let last = "absent";
|
|
while (Date.now() < deadline) {
|
|
const texts = await locator.allInnerTexts().catch(() => [] as string[]);
|
|
/* A status block renders its fields as one inner text, so match inside an
|
|
* element rather than against whole-element equality. */
|
|
if (texts.some((text) => text.includes(expected))) return;
|
|
if (texts.length > 0) last = JSON.stringify(texts);
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
throw new Error(`${label}: never read "${expected}" (last ${last})`);
|
|
}
|
|
|
|
async function waitForInputValue(locator: import("@playwright/test").Locator, expected: string, label: string, timeoutMs = 120_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
let last: string | null = "absent";
|
|
while (Date.now() < deadline) {
|
|
last = await locator.inputValue().catch(() => null);
|
|
if (last === expected) return;
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
throw new Error(`${label}: value never became ${expected} (last ${last})`);
|
|
}
|
|
|
|
async function waitForChecked(locator: import("@playwright/test").Locator, expected: boolean, label: string, timeoutMs = 120_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
let last: boolean | null = null;
|
|
while (Date.now() < deadline) {
|
|
last = await locator.isChecked().catch(() => null);
|
|
if (last === expected) return;
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
throw new Error(`${label}: checked never became ${expected} (last ${last})`);
|
|
}
|
|
|
|
async function waitForPressed(locator: import("@playwright/test").Locator, expected: boolean[], label: string, timeoutMs = 120_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
let last: (string | null)[] = [];
|
|
while (Date.now() < deadline) {
|
|
last = [];
|
|
for (let index = 0; index < expected.length; index++) last.push(await locator.nth(index).getAttribute("aria-pressed").catch(() => null));
|
|
if (last.every((value, index) => (value === "true") === expected[index])) return;
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
throw new Error(`${label}: aria-pressed never became ${JSON.stringify(expected)} (last ${JSON.stringify(last)})`);
|
|
}
|
|
|
|
const trackingFixture = (relative: string) => path.join(root, "blender-5.2.0/tests/files/tracking", relative);
|
|
const stabBlendPath = process.env.CLIP_STAB_BLEND_FIXTURE ?? trackingFixture("stabilization-test.blend");
|
|
const locrotBlendPath = process.env.CLIP_LOCROT_BLEND_FIXTURE ?? trackingFixture("synthetic-locrotscale.blend");
|
|
const pointBlendPath = process.env.CLIP_POINT_BLEND_FIXTURE ?? trackingFixture("synthetic-point-motion.blend");
|
|
const undistortBlendPath = process.env.CLIP_UNDISTORT_BLEND_FIXTURE ?? trackingFixture("undistortion-test.blend");
|
|
const undistortGridPath = trackingFixture("footage/distorted-grid.png");
|
|
const bundleBlendPath = process.env.CLIP_BUNDLE_BLEND_FIXTURE ?? trackingFixture("bundle-adjustment.blend");
|
|
const locrotFootageNames = ["01.png", "02.png"];
|
|
|
|
test("[clip-wiring] steps, jumps and tracks from the Clip editor controls", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const surface = await openClipEditor(page, blendPath);
|
|
const slider = surface.getByTestId("clip-frame-slider");
|
|
const bounds = await slider.evaluate((element) => ({
|
|
min: Number((element as HTMLInputElement).min),
|
|
max: Number((element as HTMLInputElement).max),
|
|
value: Number((element as HTMLInputElement).value),
|
|
}));
|
|
const target = Math.min(bounds.min + 2, bounds.max);
|
|
await setRangeValue(slider, target);
|
|
await expect.poll(async () => Number(await slider.inputValue()), { timeout: 60_000, message: "frame slider did not move the scene frame" }).toBe(target);
|
|
|
|
await expect(surface.getByTestId("clip-track-check").first()).toBeVisible({ timeout: 30_000 });
|
|
await surface.getByTestId("clip-track-check").first().check();
|
|
await expect(surface.getByTestId("clip-track-forward")).toBeEnabled({ timeout: 60_000 });
|
|
await expect(surface.getByTestId("clip-track-back")).toBeEnabled();
|
|
await expect(surface.getByTestId("clip-jump-keyframe-next")).toBeEnabled();
|
|
await expect(surface.getByTestId("clip-solve-camera")).toBeVisible();
|
|
|
|
const beforeStep = Number(await slider.inputValue());
|
|
await surface.getByTestId("clip-frame-next").click();
|
|
await expect.poll(async () => Number(await slider.inputValue()), { timeout: 60_000, message: "frame step did not advance the scene frame" }).toBe(beforeStep + 1);
|
|
|
|
const beforeJump = Number(await slider.inputValue());
|
|
await surface.getByTestId("clip-jump-keyframe-next").click();
|
|
await page.waitForTimeout(1500);
|
|
const afterJump = Number(await slider.inputValue());
|
|
await surface.getByTestId("clip-frame-prev").click();
|
|
await expect.poll(async () => Number(await slider.inputValue()), { timeout: 60_000 }).toBe(Math.max(afterJump - 1, bounds.min));
|
|
|
|
/* Checking the track already makes it the active track (desktop single
|
|
* active track), so the settings panel binds without a second click. */
|
|
await expect(surface.getByTestId("clip-track-weight-stab")).toBeEnabled({ timeout: 30_000 });
|
|
await surface.getByTestId("clip-track-weight-stab").fill("0.8");
|
|
await surface.getByTestId("clip-track-custom-color").check();
|
|
await expect(surface.getByTestId("clip-track-color")).toBeEnabled();
|
|
await surface.getByTestId("clip-track-red-channel").uncheck();
|
|
await surface.getByTestId("clip-track-grayscale-preview").check();
|
|
await surface.getByTestId("clip-track-apply-settings").click();
|
|
await page.waitForTimeout(800);
|
|
await expect(surface.getByTestId("clip-track-weight-stab")).toHaveValue("0.8");
|
|
await expect(surface.getByTestId("clip-track-custom-color")).toBeChecked();
|
|
await expect(surface.getByTestId("clip-track-red-channel")).not.toBeChecked();
|
|
await expect(surface.getByTestId("clip-track-grayscale-preview")).toBeChecked();
|
|
|
|
await attach(testInfo, "clip-wiring", { bounds, target, beforeStep, beforeJump, afterJump, value: await slider.inputValue() });
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-track-lifecycle] adds, keys, clears, flags and deletes a track through the engine", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const trackOf = (project: any, trackId: string) => ((clipOf(project)?.tracks ?? []) as any[]).find((track) => track.id === trackId) ?? null;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const beforeCount = (clip.tracks ?? []).length as number;
|
|
const frame = clip.frameStart + 5;
|
|
const added = await client.clipTrackingEdit(clip.id, { op: "addTrack", frame, x: 0.5, y: 0.5 });
|
|
const addedTrack = trackOf(added.snapshot.trackingMasks, added.createdTrackId);
|
|
const afterAddCount = (clipOf(added.snapshot.trackingMasks)?.tracks ?? []).length as number;
|
|
const keyed = await client.clipTrackingEdit(clip.id, { op: "keyframe", trackId: added.createdTrackId, frame, keyed: true });
|
|
const keyedMarker = ((trackOf(keyed.snapshot.trackingMasks, added.createdTrackId)?.markers ?? []) as any[]).find((marker) => marker.frame === frame) ?? null;
|
|
const cleared = await client.clipTrackingEdit(clip.id, { op: "clearPath", trackId: added.createdTrackId, frame, mode: "ALL" });
|
|
const clearedMarkers = ((trackOf(cleared.snapshot.trackingMasks, added.createdTrackId)?.markers ?? []) as any[]).length;
|
|
const hidden = await client.clipTrackingEdit(clip.id, { op: "flag", trackId: added.createdTrackId, flag: "HIDDEN", value: true });
|
|
const hiddenTrack = trackOf(hidden.snapshot.trackingMasks, added.createdTrackId);
|
|
const shown = await client.clipTrackingEdit(clip.id, { op: "flag", trackId: added.createdTrackId, flag: "HIDDEN", value: false });
|
|
const shownTrack = trackOf(shown.snapshot.trackingMasks, added.createdTrackId);
|
|
const objAdded = await client.clipTrackingEdit(clip.id, { op: "objectAdd", objectName: "E2E_Object" });
|
|
const objActive = await client.clipTrackingEdit(clip.id, { op: "objectSetActive", objectName: "E2E_Object" });
|
|
const activeObject = clipOf(objActive.snapshot.trackingMasks)?.activeObject as string | undefined;
|
|
const objRemoved = await client.clipTrackingEdit(clip.id, { op: "objectRemove", objectName: "E2E_Object" });
|
|
const deleted = await client.clipTrackingEdit(clip.id, { op: "deleteTrack", trackId: added.createdTrackId });
|
|
const afterDeleteCount = (clipOf(deleted.snapshot.trackingMasks)?.tracks ?? []).length as number;
|
|
return {
|
|
clipId: clip.id as string, beforeCount, frame, createdTrackId: added.createdTrackId, afterAddCount,
|
|
addedMarkers: ((addedTrack?.markers ?? []) as any[]).length, addedSelected: addedTrack?.selected === true,
|
|
keyedFlag: keyedMarker?.keyframe === true, clearedMarkers,
|
|
hiddenFlag: hiddenTrack?.hidden === true, shownFlag: shownTrack?.hidden === true,
|
|
opAdded: added.op, opDeleted: deleted.op, deletedAffected: deleted.affected,
|
|
activeObject, objectRemoveOp: objRemoved.op, afterDeleteCount,
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64") });
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-track-lifecycle", result);
|
|
expect(result.createdTrackId).toMatch(/^track:\d+:\d+$/);
|
|
expect(result.opAdded).toBe("addTrack");
|
|
expect(result.afterAddCount).toBe(result.beforeCount + 1);
|
|
expect(result.addedMarkers).toBeGreaterThan(0);
|
|
expect(result.addedSelected).toBe(true);
|
|
expect(result.keyedFlag).toBe(true);
|
|
/* path_clear_all keeps the reference-frame marker and inserts one disabled
|
|
* guard marker on each side (blenkernel/intern/tracking.cc, TRACK_CLEAR_ALL). */
|
|
expect(result.clearedMarkers).toBe(3);
|
|
expect(result.hiddenFlag).toBe(true);
|
|
expect(result.shownFlag).toBe(false);
|
|
expect(result.activeObject).toBe("E2E_Object");
|
|
expect(result.objectRemoveOp).toBe("objectRemove");
|
|
expect(result.opDeleted).toBe("deleteTrack");
|
|
expect(result.afterDeleteCount).toBe(result.beforeCount);
|
|
});
|
|
|
|
test("[clip-boxes-settings] writes pattern/search boxes and tracker settings through bpy", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const { markerBoxSource, trackSettingsSource, applyTrackSettingsSource, trackingDefaultsSource } = await import("/src/tracking/clipEditorCommands.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const findMarker = (project: any, trackId: string, frame: number) => {
|
|
const track = ((clipOf(project)?.tracks ?? []) as any[]).find((item) => item.id === trackId);
|
|
return (track?.markers ?? []).find((marker: any) => marker.frame === frame) ?? null;
|
|
};
|
|
const settingsOf = (project: any, trackId: string) => ((clipOf(project)?.tracks ?? []) as any[]).find((item) => item.id === trackId)?.settings ?? null;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const track = ((clip.tracks ?? []) as any[]).find((item) => (item.markers ?? []).length > 0);
|
|
if (!track) throw new Error("no track with markers");
|
|
const marker = track.markers[0];
|
|
const frame = marker.frame as number;
|
|
const center: [number, number] = [marker.position[0], marker.position[1]];
|
|
const patternMin: [number, number] = [Math.max(0, center[0] - 0.04), Math.max(0, center[1] - 0.03)];
|
|
const patternMax: [number, number] = [Math.min(1, center[0] + 0.04), Math.min(1, center[1] + 0.03)];
|
|
const searchMin: [number, number] = [Math.max(0, center[0] - 0.08), Math.max(0, center[1] - 0.07)];
|
|
const searchMax: [number, number] = [Math.min(1, center[0] + 0.08), Math.min(1, center[1] + 0.07)];
|
|
const { parseTrackIndices } = await import("/src/tracking/clipEditorCommands.ts");
|
|
const indices = parseTrackIndices(track.id);
|
|
if (!indices) throw new Error("track id cannot be resolved");
|
|
const boxed = await client.executeEmbeddedPython(markerBoxSource({ clipName: clip.name, ...indices, frame, center, patternMin, patternMax, searchMin, searchMax }), "ClipMarkerBox.py", false);
|
|
const boxedMarker = findMarker(boxed.snapshot.trackingMasks, track.id, frame);
|
|
|
|
const trackIds = ((clip.tracks ?? []) as any[]).slice(0, 2).map((item) => item.id as string);
|
|
const settings = { motionModel: 3, algorithm: 9, minimumCorrelation: 0.85, framesLimit: 60, patternMatch: 1, margin: 20, weight: 0.5, weightStab: 0.9, useCustomColor: true, color: [0.25, 0.5, 0.75, 1] as [number, number, number, number], useRedChannel: false, useGrayscalePreview: true, useAlphaPreview: true };
|
|
const written = await client.executeEmbeddedPython(trackSettingsSource(clip.name, trackIds[0], settings), "ClipTrackSettings.py", false);
|
|
const writtenSettings = settingsOf(written.snapshot.trackingMasks, trackIds[0]);
|
|
const applied = await client.executeEmbeddedPython(applyTrackSettingsSource(clip.name, trackIds, { motionModel: 2, minimumCorrelation: 0.7 }), "ClipTrackSettingsApply.py", false);
|
|
const appliedSettings = trackIds.map((trackId) => settingsOf(applied.snapshot.trackingMasks, trackId));
|
|
const defaults = await client.executeEmbeddedPython(trackingDefaultsSource(clip.name, {
|
|
defaultMotionModel: 2, defaultAlgorithm: 5, defaultMinimumCorrelation: 0.8, defaultPatternSize: 64,
|
|
defaultSearchSize: 80, defaultFramesLimit: 30, defaultMargin: 12, defaultPatternMatch: 1, defaultWeight: 10,
|
|
}), "ClipTrackingDefaults.py", false);
|
|
return {
|
|
clipName: clip.name as string, trackId: track.id as string, frame, center, patternMin, patternMax, searchMin, searchMax,
|
|
boxed: boxedMarker ? { patternMin: boxedMarker.patternMin, patternMax: boxedMarker.patternMax, searchMin: boxedMarker.searchMin, searchMax: boxedMarker.searchMax } : null,
|
|
writtenSettings, appliedSettings, defaults: clipOf(defaults.snapshot.trackingMasks)?.settings ?? null,
|
|
states: [boxed.python.state, written.python.state, applied.python.state, defaults.python.state],
|
|
pythonErrors: [boxed.python.error ?? null, written.python.error ?? null, applied.python.error ?? null, defaults.python.error ?? null],
|
|
pythonOutputs: [boxed.python.output, written.python.output, applied.python.output, defaults.python.output].map((output) => (output ?? "").slice(0, 1200)),
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64") });
|
|
await attach(testInfo, "clip-boxes-settings", result);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
expect(result.states).toEqual(["DONE", "DONE", "DONE", "DONE"]);
|
|
expect(result.boxed?.patternMin[0]).toBeCloseTo(result.patternMin[0], 3);
|
|
expect(result.boxed?.patternMin[1]).toBeCloseTo(result.patternMin[1], 3);
|
|
expect(result.boxed?.patternMax[0]).toBeCloseTo(result.patternMax[0], 3);
|
|
expect(result.boxed?.patternMax[1]).toBeCloseTo(result.patternMax[1], 3);
|
|
expect(result.boxed?.searchMin[0]).toBeCloseTo(result.searchMin[0], 3);
|
|
expect(result.boxed?.searchMax[1]).toBeCloseTo(result.searchMax[1], 3);
|
|
expect(result.writtenSettings?.motionModel).toBe(3);
|
|
expect(result.writtenSettings?.minimumCorrelation).toBeCloseTo(0.85, 3);
|
|
expect(result.writtenSettings?.framesLimit).toBe(60);
|
|
expect(result.writtenSettings?.margin).toBe(20);
|
|
expect(result.writtenSettings?.weight).toBeCloseTo(0.5, 3);
|
|
expect(result.writtenSettings?.weightStab).toBeCloseTo(0.9, 3);
|
|
expect(result.writtenSettings?.useCustomColor).toBe(true);
|
|
expect(result.writtenSettings?.color?.[0]).toBeCloseTo(0.25, 3);
|
|
expect(result.writtenSettings?.color?.[2]).toBeCloseTo(0.75, 3);
|
|
expect(result.writtenSettings?.useRedChannel).toBe(false);
|
|
expect(result.writtenSettings?.useGreenChannel).toBe(true);
|
|
expect(result.writtenSettings?.useGrayscalePreview).toBe(true);
|
|
expect(result.writtenSettings?.useAlphaPreview).toBe(true);
|
|
for (const settingsValue of result.appliedSettings) {
|
|
expect(settingsValue?.motionModel).toBe(2);
|
|
expect(settingsValue?.minimumCorrelation).toBeCloseTo(0.7, 3);
|
|
}
|
|
expect(result.defaults?.defaultMotionModel).toBe(2);
|
|
expect(result.defaults?.defaultPatternSize).toBe(64);
|
|
expect(result.defaults?.defaultSearchSize).toBe(80);
|
|
expect(result.defaults?.defaultMinimumCorrelation).toBeCloseTo(0.8, 3);
|
|
expect(result.defaults?.defaultFramesLimit).toBe(30);
|
|
});
|
|
|
|
test("[clip-track-panel] previews the pattern, applies color presets and shows the average error", async ({ page }, testInfo) => {
|
|
test.setTimeout(300_000);
|
|
const panelBlend = fs.readFileSync(solveBlendPath);
|
|
const panelFootage = fs.readFileSync(solveFootagePath);
|
|
/* The pattern preview and the average error are desktop Track-panel widgets;
|
|
* derive their ground truth from the same fixture bytes the app opens. */
|
|
const reference = await page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/synthetic-tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const localEnd = clip.frameEnd - clip.frameStart + 1;
|
|
const usable = (marker: any) => marker.frame >= 1 && marker.frame <= localEnd && Array.isArray(marker.patternCorners) && marker.patternCorners.length === 4;
|
|
const track = (clip.tracks ?? []).find((item: any) => item.hasBundle === true && (item.markers ?? []).some(usable));
|
|
if (!track) throw new Error("no bundled track with a pattern marker inside the clip range");
|
|
const marker = track.markers.find(usable);
|
|
const sceneFrame = marker.frame + clip.frameStart - 1;
|
|
const decoded = await client.movieClipFrame(clip.id, sceneFrame);
|
|
const pixels = Uint8Array.from(atob(decoded.pixelsBase64), (character) => character.charCodeAt(0));
|
|
/* A rectangle's centre maps onto the crossing of its image quad's diagonals. */
|
|
const cross = (a: number[], b: number[], c: number[], d: number[]) => {
|
|
const rx = b[0] - a[0], ry = b[1] - a[1];
|
|
const sx = d[0] - c[0], sy = d[1] - c[1];
|
|
const denominator = rx * sy - ry * sx;
|
|
const t = ((c[0] - a[0]) * sy - (c[1] - a[1]) * sx) / (Math.abs(denominator) < 1e-12 ? 1e-12 : denominator);
|
|
return [a[0] + rx * t, a[1] + ry * t];
|
|
};
|
|
const [c0, c1, c2, c3] = marker.patternCorners as number[][];
|
|
const [u, v] = cross(c0, c2, c1, c3);
|
|
const sample = (x: number, y: number, channel: number) => {
|
|
const clampX = Math.max(0, Math.min(decoded.width - 1, x));
|
|
const clampY = Math.max(0, Math.min(decoded.height - 1, y));
|
|
const x0 = Math.floor(clampX), y0 = Math.floor(clampY);
|
|
const x1 = Math.min(decoded.width - 1, x0 + 1), y1 = Math.min(decoded.height - 1, y0 + 1);
|
|
const fx = clampX - x0, fy = clampY - y0;
|
|
const at = (px: number, py: number) => pixels[(py * decoded.width + px) * 4 + channel];
|
|
return at(x0, y0) * (1 - fx) * (1 - fy) + at(x1, y0) * fx * (1 - fy) + at(x0, y1) * (1 - fx) * fy + at(x1, y1) * fx * fy;
|
|
};
|
|
/* Blender tracks store a bottom-left origin; decoded rows start at the top. */
|
|
const px = u * decoded.width, py = (1 - v) * decoded.height;
|
|
/* Desktop CLIP_OT_track_copy_color (tracking_ops.cc): the active track's
|
|
* custom colour is copied onto every other view-selected track. */
|
|
const { copyTrackColorSource, trackSettingsSource } = await import("/src/tracking/clipEditorCommands.ts");
|
|
const activeIndices = (track.id as string).split(":").map(Number);
|
|
const other = (clip.tracks ?? []).find((item: any) => item.id !== track.id);
|
|
if (!other) throw new Error("no second track for the copy-colour check");
|
|
const otherIndex = Number((other.id as string).split(":")[2]);
|
|
const paintedTrack = await client.executeEmbeddedPython(trackSettingsSource(clip.name, track.id, { useCustomColor: true, color: [0, 0, 1, 1] }), "ClipTrackColor.py", false);
|
|
const copied = await client.executeEmbeddedPython(copyTrackColorSource(clip.name, activeIndices[1], activeIndices[2], [otherIndex]), "ClipTrackCopyColor.py", false);
|
|
const tracksAfter = ((copied.snapshot.trackingMasks?.clips?.[0]?.tracks ?? []) as any[]);
|
|
const activeAfter = tracksAfter.find((item) => item.id === track.id);
|
|
const otherAfter = tracksAfter.find((item) => item.id === other.id);
|
|
return {
|
|
trackId: track.id as string,
|
|
averageError: track.averageError as number,
|
|
muted: marker.muted === true,
|
|
frameStart: clip.frameStart as number,
|
|
sceneFrame,
|
|
markerFrame: marker.frame as number,
|
|
width: decoded.width as number,
|
|
height: decoded.height as number,
|
|
expected: [sample(px, py, 0), sample(px, py, 1), sample(px, py, 2)],
|
|
copyColor: {
|
|
paintState: paintedTrack.python.state,
|
|
state: copied.python.state,
|
|
otherIndex,
|
|
activeCustom: activeAfter?.settings?.useCustomColor === true,
|
|
activeColor: activeAfter?.settings?.color ?? null,
|
|
otherCustom: otherAfter?.settings?.useCustomColor === true,
|
|
otherColor: otherAfter?.settings?.color ?? null,
|
|
},
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error) }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: panelBlend.toString("base64"), footageBase64: panelFootage.toString("base64") });
|
|
await attach(testInfo, "clip-track-panel-reference", reference);
|
|
expect((reference as any).failed ?? false, (reference as any).message).toBe(false);
|
|
expect(reference.width).toBeGreaterThan(0);
|
|
expect(Number.isFinite(reference.averageError)).toBe(true);
|
|
expect(reference.copyColor.paintState).toBe("DONE");
|
|
expect(reference.copyColor.state).toBe("DONE");
|
|
expect(reference.copyColor.activeCustom).toBe(true);
|
|
expect(reference.copyColor.otherCustom).toBe(true);
|
|
expect(reference.copyColor.otherColor).toEqual([0, 0, 1, 1]);
|
|
|
|
const surface = await openClipEditor(page, solveBlendPath);
|
|
await surface.getByTestId("clip-relink-input").setInputFiles(solveFootagePath);
|
|
const sourceStatus = surface.getByTestId("clip-list-item").first().locator("em[data-status]");
|
|
await waitForText(sourceStatus, "可用", "relinked clip source never became available");
|
|
|
|
const slider = surface.getByTestId("clip-frame-slider");
|
|
await setRangeValue(slider, reference.sceneFrame);
|
|
await waitForInputValue(slider, String(reference.sceneFrame), "frame slider");
|
|
|
|
const trackButton = surface.locator(`[data-testid="clip-track-item"][data-track-id="${reference.trackId}"]`);
|
|
await trackButton.click();
|
|
await expect(trackButton).toHaveAttribute("aria-pressed", "true", { timeout: 60_000 });
|
|
|
|
/* Solved fixtures open with muted markers; the desktop preview tints muted
|
|
* patterns, so clear the mute through the panel before sampling pixels. */
|
|
const mute = surface.getByTestId("clip-marker-mute");
|
|
if (await mute.isChecked()) {
|
|
await mute.uncheck();
|
|
await waitForChecked(mute, false, "marker mute toggle");
|
|
}
|
|
|
|
const scopesCanvas = surface.getByTestId("clip-track-scopes").locator("canvas");
|
|
const readScopes = async (height: number) => scopesCanvas.evaluate((element, expectedHeight) => {
|
|
const canvas = element as HTMLCanvasElement;
|
|
const context = canvas.getContext("2d");
|
|
if (!context) return null;
|
|
const width = canvas.width;
|
|
const data = context.getImageData(0, 0, width, expectedHeight).data;
|
|
let opaque = true;
|
|
for (let index = 3; index < data.length; index += 4) if (data[index] !== 255) { opaque = false; break; }
|
|
const distinct = new Set<string>();
|
|
for (let index = 0; index < data.length; index += 4 * 89) distinct.add(`${data[index]},${data[index + 1]},${data[index + 2]}`);
|
|
const offset = (Math.floor(expectedHeight / 2) * width + Math.floor(width / 2)) * 4;
|
|
return { width, height: canvas.height, opaque, distinct: distinct.size, center: [data[offset], data[offset + 1], data[offset + 2]] };
|
|
}, height);
|
|
const near = (first: number[], second: number[], tolerance = 4) =>
|
|
first.length === 3 && second.length === 3 && first.every((value, index) => Math.abs(value - second[index]) <= tolerance);
|
|
const waitForScopes = async (height: number, label: string) => {
|
|
const deadline = Date.now() + 180_000;
|
|
let last: unknown = null;
|
|
while (Date.now() < deadline) {
|
|
last = await readScopes(height).catch(() => null);
|
|
const sample = last as { opaque?: boolean; distinct?: number; center?: number[]; height?: number; width?: number } | null;
|
|
if (sample && sample.width === 160 && sample.height === height && sample.opaque === true && (sample.distinct ?? 0) > 1
|
|
&& near(sample.center ?? [], reference.expected as number[])) return sample;
|
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
}
|
|
throw new Error(`${label}: pattern preview never sampled the marker pixel (last ${JSON.stringify(last)}, expected ${JSON.stringify(reference.expected)})`);
|
|
};
|
|
const painted = await waitForScopes(80, "pattern preview");
|
|
|
|
const heightSlider = surface.getByTestId("clip-track-scopes-height");
|
|
await setRangeValue(heightSlider, 8);
|
|
await waitForInputValue(heightSlider, "8", "preview height slider");
|
|
const tall = await waitForScopes(160, "resized pattern preview");
|
|
expect(tall.height).toBe(160);
|
|
|
|
const preset = surface.getByTestId("clip-track-color-preset");
|
|
const customColor = surface.getByTestId("clip-track-custom-color");
|
|
await preset.selectOption("Far_Plane");
|
|
await waitForChecked(customColor, true, "Far Plane preset");
|
|
await waitForInputValue(surface.getByTestId("clip-track-color"), "#0000ff", "Far Plane preset color");
|
|
await preset.selectOption("Default");
|
|
await waitForChecked(customColor, false, "Default preset");
|
|
|
|
/* CLIP_OT_track_copy_color copies the active track's custom colour onto the
|
|
* other view-selected tracks through the panel button. */
|
|
await preset.selectOption("Far_Plane");
|
|
await waitForChecked(customColor, true, "Far Plane preset for copy");
|
|
const rows = surface.getByTestId("clip-track-item");
|
|
const rowCount = await rows.count();
|
|
expect(rowCount).toBeGreaterThan(1);
|
|
const activeIndex = await rows.evaluateAll((list, trackId) => list.findIndex((row) => row.getAttribute("data-track-id") === trackId), reference.trackId);
|
|
expect(activeIndex).toBeGreaterThanOrEqual(0);
|
|
const otherIndex = (activeIndex + 1) % rowCount;
|
|
const copyChecks = surface.getByTestId("clip-track-check");
|
|
await copyChecks.nth(otherIndex).check();
|
|
await expect(copyChecks.nth(otherIndex)).toBeChecked();
|
|
/* Checking makes the track the active one, so re-select the painted track:
|
|
* desktop copies from the active track onto the other selected ones. */
|
|
await rows.nth(activeIndex).click();
|
|
await expect(rows.nth(activeIndex)).toHaveAttribute("aria-pressed", "true", { timeout: 60_000 });
|
|
await waitForChecked(customColor, true, "Far Plane preset on the copy source");
|
|
const copyButton = surface.getByTestId("clip-track-copy-color");
|
|
await expect(copyButton).toBeEnabled({ timeout: 60_000 });
|
|
await copyButton.click();
|
|
/* setBusy(true) lands with the click; re-enabled means the bpy write and the
|
|
* snapshot apply are done. */
|
|
await expect(copyButton).toBeEnabled({ timeout: 180_000 });
|
|
await rows.nth(otherIndex).click();
|
|
await expect(rows.nth(otherIndex)).toHaveAttribute("aria-pressed", "true", { timeout: 60_000 });
|
|
await waitForInputValue(surface.getByTestId("clip-track-color"), "#0000ff", "copied track color");
|
|
await waitForChecked(customColor, true, "copied track custom color");
|
|
|
|
/* The readout follows the selected track; go back to the reference track. */
|
|
await rows.nth(activeIndex).click();
|
|
await expect(rows.nth(activeIndex)).toHaveAttribute("aria-pressed", "true", { timeout: 60_000 });
|
|
|
|
const average = surface.getByTestId("clip-track-average-error");
|
|
await waitForText(average, `平均误差: ${(reference.averageError ?? 0).toFixed(2)} px`, "average error readout");
|
|
|
|
await attach(testInfo, "clip-track-panel", {
|
|
reference: { trackId: reference.trackId, markerFrame: reference.markerFrame, sceneFrame: reference.sceneFrame, averageError: reference.averageError, muted: reference.muted },
|
|
painted,
|
|
tall,
|
|
presetColor: await surface.getByTestId("clip-track-color").inputValue(),
|
|
});
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-point-motion] opens the synthetic point-motion clip and decodes its PNG sequence", async ({ page }, testInfo) => {
|
|
test.setTimeout(300_000);
|
|
const pointBlend = fs.readFileSync(pointBlendPath);
|
|
const pointSequence = [1, 2, 3, 4, 5].map((index) => {
|
|
const name = `0${index}.png`;
|
|
return { name, base64: fs.readFileSync(trackingFixture(`footage/synthetic-point-motion/${name}`)).toString("base64") };
|
|
});
|
|
/* The engine opens the fixture with its whole PNG sequence staged, so the
|
|
* clip decodes independently of the browser file picker. */
|
|
const engine = await page.evaluate(async ({ blendBase64, sequence }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const resources = sequence.map((frame: { name: string; base64: string }) => ({ path: `footage/synthetic-point-motion/${frame.name}`, buffer: bytes(frame.base64) }));
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], resources);
|
|
const clip = opened.snapshot.trackingMasks?.clips?.[0];
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const track = clip.tracks?.[0];
|
|
const digestOf = async (pixels: Uint8Array) => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", pixels))).map((value) => value.toString(16).padStart(2, "0")).join("");
|
|
const decoded = [];
|
|
for (const sceneFrame of [clip.frameStart, clip.frameStart + 2]) {
|
|
const frame = await client.movieClipFrame(clip.id, sceneFrame);
|
|
const pixels = Uint8Array.from(atob(frame.pixelsBase64), (character) => character.charCodeAt(0));
|
|
decoded.push({ sceneFrame, width: frame.width, height: frame.height, byteLength: pixels.length, digest: await digestOf(pixels) });
|
|
}
|
|
return {
|
|
clipId: clip.id as string,
|
|
name: clip.name as string,
|
|
width: clip.width as number,
|
|
height: clip.height as number,
|
|
frameStart: clip.frameStart as number,
|
|
sourceStatus: clip.sourceStatus as string,
|
|
track: track ? {
|
|
name: track.name as string,
|
|
markerCount: (track.markers ?? []).length as number,
|
|
markerFrames: (track.markers ?? []).map((marker: any) => marker.frame as number),
|
|
position: track.markers?.[0]?.position as number[] | undefined,
|
|
corners: track.markers?.[0]?.patternCorners as number[][] | undefined,
|
|
muted: track.markers?.[0]?.muted as boolean | undefined,
|
|
} : null,
|
|
decoded,
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error) }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: pointBlend.toString("base64"), sequence: pointSequence });
|
|
await attach(testInfo, "clip-point-motion-engine", engine);
|
|
expect((engine as any).failed ?? false, (engine as any).message).toBe(false);
|
|
/* Desktop probing of the same fixture: one track with 7 markers on frames
|
|
* 0..6, first marker centred, pattern half-extent 7.5 px of 51. */
|
|
expect(engine.name).toBe("01.png");
|
|
expect(engine.width).toBe(51);
|
|
expect(engine.height).toBe(51);
|
|
expect(engine.sourceStatus).toBe("AVAILABLE");
|
|
expect(engine.track?.name).toBe("Track");
|
|
expect(engine.track?.markerCount).toBe(7);
|
|
expect(engine.track?.markerFrames).toEqual([0, 1, 2, 3, 4, 5, 6]);
|
|
expect(engine.track?.position?.[0]).toBeCloseTo(0.5, 4);
|
|
expect(engine.track?.position?.[1]).toBeCloseTo(0.5, 4);
|
|
expect(engine.track?.corners?.[0]?.[0]).toBeCloseTo(0.5 - 7.5 / 51, 4);
|
|
expect(engine.track?.corners?.[2]?.[0]).toBeCloseTo(0.5 + 7.5 / 51, 4);
|
|
expect(engine.decoded).toHaveLength(2);
|
|
expect(engine.decoded[0].width).toBe(51);
|
|
expect(engine.decoded[0].byteLength).toBe(51 * 51 * 4);
|
|
expect(engine.decoded[0].digest).not.toBe(engine.decoded[1].digest);
|
|
|
|
/* The browser entry: open the blend, point the clip at the staged first frame
|
|
* and wait for the decoded image to replace the placeholder. */
|
|
const surface = await openClipEditor(page, pointBlendPath);
|
|
await waitForText(surface.getByTestId("clip-status"), "1 条跟踪 · 7 个标记", "point-motion clip status");
|
|
await expect(surface.getByTestId("clip-track-item")).toHaveCount(1, { timeout: 30_000 });
|
|
await surface.getByTestId("clip-relink-input").setInputFiles(trackingFixture("footage/synthetic-point-motion/01.png"));
|
|
await waitForText(surface.getByTestId("clip-list-item").first().locator("em[data-status]"), "可用", "point-motion clip source");
|
|
const slider = surface.getByTestId("clip-frame-slider");
|
|
await setRangeValue(slider, engine.frameStart);
|
|
await waitForInputValue(slider, String(engine.frameStart), "frame slider");
|
|
const placeholder = surface.locator(".clip-editor-placeholder");
|
|
const deadline = Date.now() + 120_000;
|
|
let remaining = -1;
|
|
let message = "";
|
|
while (Date.now() < deadline) {
|
|
const texts = await placeholder.allInnerTexts().catch(() => ["error"] as string[]);
|
|
remaining = texts.length;
|
|
message = texts[0] ?? "";
|
|
if (remaining === 0) break;
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
await attach(testInfo, "clip-point-motion", { engine, placeholder: { remaining, message } });
|
|
expect(remaining, `decoded frame never replaced the placeholder (${message})`).toBe(0);
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-undistort] renders the undistorted frame and exposes the camera data", async ({ page }, testInfo) => {
|
|
test.setTimeout(300_000);
|
|
const undistortBlend = fs.readFileSync(undistortBlendPath);
|
|
const gridImage = fs.readFileSync(undistortGridPath);
|
|
const engine = await page.evaluate(async ({ blendBase64, imageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const { cameraSettingsSource } = await import("/src/tracking/clipEditorCommands.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const decode = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
|
|
/* Undistortion is radial: the principal point stays put and displacement
|
|
* grows towards the frame border, so the difference is split into a centre
|
|
* disc and a border band instead of one global mean. */
|
|
const compare = (left: Uint8Array, right: Uint8Array, width: number, height: number) => {
|
|
let centreSum = 0, centreCount = 0, borderSum = 0, borderCount = 0, totalSum = 0;
|
|
for (let y = 0; y < height; y++) {
|
|
for (let x = 0; x < width; x++) {
|
|
const offset = (y * width + x) * 4;
|
|
let delta = 0;
|
|
for (let channel = 0; channel < 3; channel++) delta += Math.abs(left[offset + channel] - right[offset + channel]);
|
|
delta /= 3;
|
|
totalSum += delta;
|
|
const nx = (x + 0.5) / width - 0.5;
|
|
const ny = (y + 0.5) / height - 0.5;
|
|
const radius = nx * nx + ny * ny;
|
|
if (radius <= 0.1 * 0.1) {
|
|
centreSum += delta;
|
|
centreCount++;
|
|
}
|
|
else if (radius >= 0.35 * 0.35) {
|
|
borderSum += delta;
|
|
borderCount++;
|
|
}
|
|
}
|
|
}
|
|
return { total: totalSum / (width * height), centre: centreCount ? centreSum / centreCount : 0, border: borderCount ? borderSum / borderCount : 0 };
|
|
};
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/distorted-grid.png", buffer: bytes(imageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const raw = await client.movieClipFrame(clip.id, clip.frameStart);
|
|
const undistorted = await client.movieClipFrame(clip.id, clip.frameStart, 0, false, true);
|
|
const rawPixels = decode(raw.pixelsBase64);
|
|
const undistortedPixels = decode(undistorted.pixelsBase64);
|
|
const distortion = compare(rawPixels, undistortedPixels, raw.width, raw.height);
|
|
/* With every polynomial coefficient zeroed the on-the-fly undistortion
|
|
* must be the identity mapping again. */
|
|
const zeroed = await client.executeEmbeddedPython(cameraSettingsSource(clip.name, { k1: 0, k2: 0, k3: 0 }), "ClipCamera.py", false);
|
|
const settled = await client.movieClipFrame(clip.id, clip.frameStart, 0, false, true);
|
|
const settledPixels = decode(settled.pixelsBase64);
|
|
const remainder = compare(rawPixels, settledPixels, raw.width, raw.height);
|
|
const zeroedClip = clipOf(zeroed.snapshot.trackingMasks);
|
|
return {
|
|
clip: { id: clip.id as string, name: clip.name as string, width: clip.width as number, height: clip.height as number, frameStart: clip.frameStart as number, sourceStatus: clip.sourceStatus as string },
|
|
settings: clip.settings ?? null,
|
|
zeroedSettings: zeroedClip?.settings ?? null,
|
|
pythonState: zeroed.python.state as string,
|
|
raw: { width: raw.width, height: raw.height },
|
|
undistorted: { width: undistorted.width, height: undistorted.height },
|
|
distortion,
|
|
remainder,
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error) }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: undistortBlend.toString("base64"), imageBase64: gridImage.toString("base64") });
|
|
await attach(testInfo, "clip-undistort-engine", engine);
|
|
expect((engine as any).failed ?? false, (engine as any).message).toBe(false);
|
|
/* Desktop probe of undistortion-test.blend: distorted-grid.png at 1920x1080,
|
|
* camera focal 24 mm on a 35 mm sensor, polynomial k1/k2/k3 = -0.1/-0.05/-0.08.
|
|
* RNA Camera.focal is stored in pixels: 24 mm * 1920 px / 35 mm. */
|
|
expect(engine.clip.width).toBe(1920);
|
|
expect(engine.clip.height).toBe(1080);
|
|
expect(engine.clip.sourceStatus).toBe("AVAILABLE");
|
|
expect(engine.settings?.distortionModel).toBe(0);
|
|
expect(engine.settings?.focal).toBeCloseTo((24 * 1920) / 35, 1);
|
|
expect(engine.settings?.sensorWidth).toBeCloseTo(35, 3);
|
|
expect(engine.settings?.k1).toBeCloseTo(-0.1, 4);
|
|
expect(engine.settings?.k2).toBeCloseTo(-0.05, 4);
|
|
expect(engine.settings?.k3).toBeCloseTo(-0.08, 4);
|
|
expect(engine.undistorted.width).toBe(engine.raw.width);
|
|
expect(engine.undistorted.height).toBe(engine.raw.height);
|
|
expect(engine.distortion.total).toBeGreaterThan(1);
|
|
expect(engine.distortion.border).toBeGreaterThan(engine.distortion.centre * 4);
|
|
expect(engine.pythonState).toBe("DONE");
|
|
expect(engine.zeroedSettings?.k1).toBe(0);
|
|
expect(engine.remainder.total).toBeLessThan(Math.max(0.5, engine.distortion.total / 10));
|
|
|
|
/* The browser entry: the camera data panel shows the file's coefficients and
|
|
* the proxy panel's Render Undistorted toggle re-decodes through them. */
|
|
const surface = await openClipEditor(page, undistortBlendPath);
|
|
await surface.getByTestId("clip-relink-input").setInputFiles(undistortGridPath);
|
|
await waitForText(surface.getByTestId("clip-list-item").first().locator("em[data-status]"), "可用", "undistortion clip source");
|
|
await expect(surface.getByTestId("clip-camera-k1")).toHaveValue("-0.1");
|
|
await expect(surface.getByTestId("clip-camera-k2")).toHaveValue("-0.05");
|
|
await expect(surface.getByTestId("clip-camera-k3")).toHaveValue("-0.08");
|
|
const canvas = surface.getByTestId("clip-frame-canvas");
|
|
const placeholder = surface.locator(".clip-editor-placeholder");
|
|
let baseline = "";
|
|
const decodeDeadline = Date.now() + 120_000;
|
|
while (Date.now() < decodeDeadline) {
|
|
if ((await placeholder.allInnerTexts().catch(() => ["error"])).length === 0) {
|
|
baseline = await canvas.evaluate((element) => (element as HTMLCanvasElement).toDataURL());
|
|
break;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
expect(baseline.length, "first frame never decoded").toBeGreaterThan(0);
|
|
await surface.getByTestId("clip-proxy-undistort").check();
|
|
const toggleDeadline = Date.now() + 120_000;
|
|
let changed = false;
|
|
while (Date.now() < toggleDeadline) {
|
|
const current = await canvas.evaluate((element) => (element as HTMLCanvasElement).toDataURL());
|
|
if (current !== baseline) {
|
|
changed = true;
|
|
break;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
}
|
|
await attach(testInfo, "clip-undistort", { engine, baselineLength: baseline.length, changed });
|
|
expect(changed, "toggling Render Undistorted never changed the canvas").toBe(true);
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-detect] detects Harris features on the current frame", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const locrotBlend = fs.readFileSync(locrotBlendPath);
|
|
const locrotFootage = locrotFootageNames.map((name) => ({ name, base64: fs.readFileSync(trackingFixture(`footage/synthetic-locrotscale/${name}`)).toString("base64") }));
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64, locrotBlendBase64, locrotFootage }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const countSelected = (project: any) => ((clipOf(project)?.tracks ?? []) as any[]).filter((track) => track.selected).length;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
let stage = "open";
|
|
let locrotInfo: unknown = null;
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const frame = clip.frameStart + 3;
|
|
const before = (clip.tracks ?? []).length as number;
|
|
stage = "detect-tripod";
|
|
const detected = await client.detectFeatures(clip.id, frame, 16, 0.5, 120);
|
|
const afterClip = clipOf(detected.snapshot.trackingMasks);
|
|
const after = (afterClip?.tracks ?? []).length as number;
|
|
const localFrame = frame - clip.frameStart + 1;
|
|
const newTrackIds = ((afterClip?.tracks ?? []) as any[]).filter((track) => (track.markers ?? []).some((marker: any) => marker.frame === localFrame)).map((track) => track.id as string);
|
|
client.terminate();
|
|
|
|
const locrotClient = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
stage = "open-locrot";
|
|
try {
|
|
const locrot = await locrotClient.openBlend(bytes(locrotBlendBase64), undefined, undefined, [], [], locrotFootage.map((entry: { name: string; base64: string }) => ({ path: `footage/synthetic-locrotscale/${entry.name}`, buffer: bytes(entry.base64) })));
|
|
const locrotClip = clipOf(locrot.snapshot.trackingMasks);
|
|
if (!locrotClip) throw new Error("synthetic-locrotscale clip is missing");
|
|
locrotInfo = { sourceStatus: locrotClip.sourceStatus, sourcePath: locrotClip.sourcePath, width: locrotClip.width, height: locrotClip.height, frameStart: locrotClip.frameStart, frameEnd: locrotClip.frameEnd };
|
|
const locrotBefore = (locrotClip.tracks ?? []).length as number;
|
|
stage = "detect-locrot";
|
|
const locrotDetected = await locrotClient.detectFeatures(locrotClip.id, locrotClip.frameStart, 16, 0.5, 120);
|
|
const locrotAfter = clipOf(locrotDetected.snapshot.trackingMasks);
|
|
return {
|
|
clipId: clip.id as string, frame, localFrame, before, after, createdTracks: detected.createdTracks,
|
|
selected: countSelected(detected.snapshot.trackingMasks), withMarker: newTrackIds.length,
|
|
locrot: {
|
|
sourceStatus: locrotClip.sourceStatus as string,
|
|
before: locrotBefore,
|
|
after: (locrotAfter?.tracks ?? []).length as number,
|
|
createdTracks: locrotDetected.createdTracks,
|
|
selected: countSelected(locrotDetected.snapshot.trackingMasks),
|
|
},
|
|
};
|
|
}
|
|
finally { locrotClient.terminate(); }
|
|
}
|
|
catch (error) { return { failed: true, stage, locrotInfo, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64"), locrotBlendBase64: locrotBlend.toString("base64"), locrotFootage });
|
|
await attach(testInfo, "clip-detect", result);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
expect(result.createdTracks).toBeGreaterThan(0);
|
|
expect(result.after).toBe(result.before + result.createdTracks);
|
|
expect(result.selected).toBe(result.createdTracks);
|
|
expect(result.withMarker).toBeGreaterThan(0);
|
|
expect(result.locrot.sourceStatus).toBe("AVAILABLE");
|
|
expect(result.locrot.createdTracks).toBeGreaterThan(0);
|
|
expect(result.locrot.after).toBe(result.locrot.before + result.locrot.createdTracks);
|
|
});
|
|
|
|
test("[clip-solve-settings] edits solve keyframes, scale and clears the solution", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/synthetic-tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const selectSource = `import bpy\nclip = bpy.data.movieclips.get(${JSON.stringify(clip.name)})\nbundled = 0\nfor tracking_object in clip.tracking.objects:\n for track in tracking_object.tracks:\n track.select = bool(track.has_bundle) and bundled < 2\n bundled += 1 if track.select else 0\n`;
|
|
const selected = await client.executeEmbeddedPython(selectSource, "ClipSolveSelect.py", false);
|
|
const frameA = clip.frameStart + 2;
|
|
const frameB = clip.frameStart + 20;
|
|
const keyedA = await client.clipSolveEdit(clip.id, { op: "setKeyframe", frame: frameA, which: "A" });
|
|
const keyedB = await client.clipSolveEdit(clip.id, { op: "setKeyframe", frame: frameB, which: "B" });
|
|
const afterKeys = clipOf(keyedB.snapshot.trackingMasks)?.cameraSolve ?? null;
|
|
const scaled = await client.clipSolveEdit(clip.id, { op: "setScale", distance: 2 });
|
|
const applied = await client.clipSolveEdit(clip.id, { op: "applyScale", distance: 3 });
|
|
const afterScale = clipOf(applied.snapshot.trackingMasks)?.cameraSolve ?? null;
|
|
const cleared = await client.clipSolveEdit(clip.id, { op: "clearSolution" });
|
|
const afterClear = clipOf(cleared.snapshot.trackingMasks)?.cameraSolve ?? null;
|
|
return {
|
|
clipId: clip.id as string, frameStart: clip.frameStart as number, frameA, frameB,
|
|
selectState: selected.python.state,
|
|
expectedA: frameA - clip.frameStart + 1, expectedB: frameB - clip.frameStart + 1,
|
|
keyframeA: afterKeys?.keyframeA ?? null, keyframeB: afterKeys?.keyframeB ?? null,
|
|
beforeStatus: clip.cameraSolve?.status ?? null,
|
|
scaleAffected: scaled.affected, applyAffected: applied.affected, scaleValue: afterScale?.scale ?? null,
|
|
clearAffected: cleared.affected,
|
|
status: afterClear?.status ?? null, solvedFrames: (afterClear?.solvedFrames ?? []).length,
|
|
ops: [keyedA.op, keyedB.op, scaled.op, applied.op, cleared.op],
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: solveBlend.toString("base64"), footageBase64: solveFootage.toString("base64") });
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-solve-settings", result);
|
|
expect(result.selectState).toBe("DONE");
|
|
expect(result.beforeStatus).toBe("SOLVED");
|
|
expect(result.ops).toEqual(["setKeyframe", "setKeyframe", "setScale", "applyScale", "clearSolution"]);
|
|
expect(result.keyframeA).toBe(result.expectedA);
|
|
expect(result.keyframeB).toBe(result.expectedB);
|
|
expect(result.scaleAffected).toBeGreaterThan(0);
|
|
expect(result.applyAffected).toBeGreaterThan(0);
|
|
expect(result.clearAffected).toBeGreaterThan(0);
|
|
expect(result.status).toBe("NONE");
|
|
expect(result.solvedFrames).toBe(0);
|
|
});
|
|
|
|
test("[clip-plane-complete] keys, retracks, images and deletes a plane track", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const planesOf = (project: any) => (clipOf(project)?.planeTracks ?? []) as any[];
|
|
const planeOf = (project: any, planeId: string) => planesOf(project).find((plane) => plane.id === planeId) ?? null;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const beforeCount = planesOf(opened.snapshot.trackingMasks).length;
|
|
const frame = clip.frameStart + 10;
|
|
const created = await client.createPlaneTrack(clip.id, ((clip.tracks ?? []) as any[]).slice(0, 4).map((track) => track.id), frame);
|
|
const afterCreate = planesOf(created.snapshot.trackingMasks);
|
|
const plane = afterCreate[afterCreate.length - 1];
|
|
if (!plane) throw new Error("plane track was not created");
|
|
/* PLANE_TRACK_AUTOKEY (rna_tracking.cc use_auto_keying) round-trips. */
|
|
const { planeAutoKeyingSource } = await import("/src/tracking/clipEditorCommands.ts");
|
|
const [, planeObject, planeIndex] = (plane.id as string).split(":");
|
|
const autoKeyOn = await client.executeEmbeddedPython(planeAutoKeyingSource(clip.name, Number(planeObject), Number(planeIndex), true), "ClipPlaneAutoKey.py", false);
|
|
const autoKeyOff = await client.executeEmbeddedPython(planeAutoKeyingSource(clip.name, Number(planeObject), Number(planeIndex), false), "ClipPlaneAutoKey.py", false);
|
|
const autoKeyedPlane = planeOf(autoKeyOn.snapshot.trackingMasks, plane.id);
|
|
const autoClearedPlane = planeOf(autoKeyOff.snapshot.trackingMasks, plane.id);
|
|
const beforeKeys = (plane.keyframes ?? []).length as number;
|
|
const keyed = await client.planeTrackEdit(clip.id, { op: "keyframe", planeId: plane.id, frame: frame + 1, keyed: true });
|
|
const keyedPlane = planeOf(keyed.snapshot.trackingMasks, plane.id);
|
|
const inserted = ((keyedPlane?.keyframes ?? []) as any[]).find((item) => item.frame === frame + 1) ?? null;
|
|
const retracked = await client.planeTrackEdit(clip.id, { op: "retrack", planeId: plane.id, frame: frame + 2 });
|
|
const imaged = await client.planeTrackEdit(clip.id, { op: "createImage", planeId: plane.id, frame, opacity: 0.5 });
|
|
const imagePlane = planeOf(imaged.snapshot.trackingMasks, plane.id);
|
|
const deleted = await client.planeTrackEdit(clip.id, { op: "deletePlane", planeId: plane.id });
|
|
const afterDelete = planesOf(deleted.snapshot.trackingMasks).length;
|
|
return {
|
|
clipId: clip.id as string, frame, planeId: plane.id as string, planeName: plane.name as string,
|
|
beforeCount, afterCreateCount: afterCreate.length, beforeKeys,
|
|
keyedKeys: (keyedPlane?.keyframes ?? []).length as number,
|
|
insertedCorners: inserted ? (inserted.corners ?? []).length : 0,
|
|
retrackAffected: retracked.affected, imageAffected: imaged.affected,
|
|
imagePlaneKeys: (imagePlane?.keyframes ?? []).length as number,
|
|
deleteAffected: deleted.affected, afterDelete,
|
|
ops: [keyed.op, retracked.op, imaged.op, deleted.op],
|
|
autoKey: {
|
|
onState: autoKeyOn.python.state, offState: autoKeyOff.python.state,
|
|
on: autoKeyedPlane?.useAutoKeying === true, off: autoClearedPlane?.useAutoKeying === false,
|
|
},
|
|
};
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64") });
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
await attach(testInfo, "clip-plane-complete", result);
|
|
expect(result.beforeCount).toBe(0);
|
|
expect(result.afterCreateCount).toBe(1);
|
|
expect(result.ops).toEqual(["keyframe", "retrack", "createImage", "deletePlane"]);
|
|
expect(result.keyedKeys).toBe(result.beforeKeys + 1);
|
|
expect(result.insertedCorners).toBe(4);
|
|
expect(result.retrackAffected).toBeGreaterThan(0);
|
|
expect(result.imageAffected).toBeGreaterThan(0);
|
|
expect(result.deleteAffected).toBe(1);
|
|
expect(result.afterDelete).toBe(result.beforeCount);
|
|
expect(result.autoKey.onState).toBe("DONE");
|
|
expect(result.autoKey.offState).toBe("DONE");
|
|
expect(result.autoKey.on).toBe(true);
|
|
expect(result.autoKey.off).toBe(true);
|
|
});
|
|
|
|
test("[clip-stab] writes 2D stabilization settings and returns a stabilization matrix", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const stabBlend = fs.readFileSync(stabBlendPath);
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64, stabBlendBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const { stabilizationSource } = await import("/src/tracking/clipEditorCommands.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const trackOf = (project: any, trackId: string) => ((clipOf(project)?.tracks ?? []) as any[]).find((track) => track.id === trackId) ?? null;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
const source = stabilizationSource(clip.name, {
|
|
enabled: true, autoscale: true, useRotation: true, useScale: true, showStabTracks: true,
|
|
anchorFrame: 12, targetPos: [0.5, 0.5], targetRot: 0.1, scale: 1.0,
|
|
locinf: 0.8, scaleinf: 0.5, rotinf: 0.5, filter: 1, maxscale: 1.5,
|
|
});
|
|
const written = await client.executeEmbeddedPython(source, "ClipStabilization.py", false);
|
|
const writtenClip = clipOf(written.snapshot.trackingMasks);
|
|
const track = ((clip.tracks ?? []) as any[]).slice().sort((a, b) => (b.markers ?? []).length - (a.markers ?? []).length)[0];
|
|
/* Rotation stabilization must use a second track: with the translation
|
|
* pivot taken from a single track, that same track sits exactly on the
|
|
* pivot and its rotation weight collapses to zero. */
|
|
const rotTrack = ((clip.tracks ?? []) as any[]).filter((item) => item.id !== track.id).sort((a, b) => (b.markers ?? []).length - (a.markers ?? []).length)[0];
|
|
if (!track || !rotTrack) throw new Error("no track pair available for stabilization flags");
|
|
const flagged = await client.clipTrackingEdit(clip.id, { op: "flag", trackId: track.id, flag: "STAB", value: true });
|
|
const flaggedRot = await client.clipTrackingEdit(clip.id, { op: "flag", trackId: rotTrack.id, flag: "STAB_ROT", value: true });
|
|
const flaggedClip = clipOf(flaggedRot.snapshot.trackingMasks);
|
|
let decoded: any = null;
|
|
let decodeError: string | null = null;
|
|
let rawStabilization: unknown = null;
|
|
try {
|
|
decoded = await client.movieClipFrame(clip.id, clip.frameStart + 5, 0, true);
|
|
}
|
|
catch (error) {
|
|
decodeError = (error as Error)?.message ?? String(error);
|
|
const raw = await (client as any).request({ type: "jsonCommand", cmd: "clipFrame", params: { dataId: clip.id, frame: clip.frameStart + 5, stabilize: true } });
|
|
rawStabilization = (raw?.json as any)?.stabilization ?? null;
|
|
}
|
|
client.terminate();
|
|
|
|
const stabClient = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
const stabOpened = await stabClient.openBlend(bytes(stabBlendBase64), undefined, undefined, [], [], []);
|
|
const stabClip = clipOf(stabOpened.snapshot.trackingMasks);
|
|
if (!stabClip) throw new Error("stabilization-test clip is missing");
|
|
return {
|
|
clipId: clip.id as string,
|
|
pythonState: written.python.state,
|
|
settings: writtenClip?.stabilization ?? null,
|
|
flaggedTrack: { useStab: trackOf(flaggedRot.snapshot.trackingMasks, track.id)?.useStab === true, useStabRot: trackOf(flaggedRot.snapshot.trackingMasks, rotTrack.id)?.useStabRot === true },
|
|
counts: { totalTracks: flaggedClip?.stabilization?.totalTracks ?? 0, totalRotationTracks: flaggedClip?.stabilization?.totalRotationTracks ?? 0 },
|
|
stabilization: decoded?.stabilization ?? null,
|
|
decodeError,
|
|
rawStabilization,
|
|
decodedWidth: decoded?.width ?? 0,
|
|
fixture: {
|
|
sourceStatus: stabClip.sourceStatus as string,
|
|
width: stabClip.width as number,
|
|
anchorFrame: stabClip.stabilization?.anchorFrame ?? null,
|
|
hasSettings: stabClip.stabilization !== undefined,
|
|
},
|
|
};
|
|
}
|
|
finally { stabClient.terminate(); }
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64"), stabBlendBase64: stabBlend.toString("base64") });
|
|
await attach(testInfo, "clip-stab", result);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
expect(result.pythonState).toBe("DONE");
|
|
expect(result.settings?.enabled).toBe(true);
|
|
expect(result.settings?.autoscale).toBe(true);
|
|
expect(result.settings?.useRotation).toBe(true);
|
|
expect(result.settings?.useScale).toBe(true);
|
|
expect(result.settings?.anchorFrame).toBe(12);
|
|
expect(result.settings?.targetPos[0]).toBeCloseTo(0.5, 3);
|
|
expect(result.settings?.targetPos[1]).toBeCloseTo(0.5, 3);
|
|
expect(result.settings?.targetRot).toBeCloseTo(0.1, 3);
|
|
expect(result.settings?.locinf).toBeCloseTo(0.8, 3);
|
|
expect(result.settings?.filter).toBe(1);
|
|
expect(result.settings?.maxscale).toBeCloseTo(1.5, 3);
|
|
expect(result.flaggedTrack.useStab).toBe(true);
|
|
expect(result.flaggedTrack.useStabRot).toBe(true);
|
|
expect(result.counts.totalTracks).toBeGreaterThanOrEqual(1);
|
|
expect(result.counts.totalRotationTracks).toBeGreaterThanOrEqual(1);
|
|
expect(result.stabilization).toBeTruthy();
|
|
expect(result.stabilization.translation).toHaveLength(2);
|
|
expect(result.stabilization.matrix).toHaveLength(16);
|
|
expect(result.decodedWidth).toBeGreaterThan(0);
|
|
expect(result.fixture.sourceStatus).toBe("MISSING");
|
|
expect(result.fixture.hasSettings).toBe(true);
|
|
});
|
|
|
|
test("[clip-stab-composite] composites the canvas through the stabilization matrix", async ({ page }, testInfo) => {
|
|
test.setTimeout(300_000);
|
|
/* The reference frame and matrix come from the product's own engine worker,
|
|
* which observeNative captures before the app boots. */
|
|
await observeNative(page);
|
|
const surface = await openClipEditor(page, blendPath);
|
|
await surface.getByTestId("clip-relink-input").setInputFiles(trackingFixture("footage/tripod-motion.avi"));
|
|
await waitForText(surface.getByTestId("clip-list-item").first().locator("em[data-status]"), "可用", "stabilization clip source");
|
|
|
|
/* tripod-motion ships every marker muted; desktop stabilization ignores a
|
|
* muted marker, so the fixture would produce an identity matrix. Unmute the
|
|
* markers through the embedded Python channel the panel itself uses. */
|
|
const unmuted = await page.evaluate(async () => {
|
|
const worker = (window as unknown as { __nativeWorkflowEngine: Worker }).__nativeWorkflowEngine;
|
|
const source = [
|
|
"import bpy",
|
|
"for clip in bpy.data.movieclips:",
|
|
" for obj in clip.tracking.objects:",
|
|
" for track in obj.tracks:",
|
|
" for marker in track.markers:",
|
|
" marker.mute = False",
|
|
"",
|
|
].join("\n");
|
|
const requestId = `clip-stab-unmute-${crypto.randomUUID()}`;
|
|
const response = await new Promise<{ ok: boolean; error?: unknown }>((resolve, reject) => {
|
|
const timer = setTimeout(() => { worker.removeEventListener("message", receive); reject(new Error("marker unmute timed out")); }, 120_000);
|
|
const receive = ({ data }: MessageEvent<{ requestId: string; ok: boolean; error?: unknown }>) => {
|
|
if (data.requestId !== requestId) return;
|
|
clearTimeout(timer);
|
|
worker.removeEventListener("message", receive);
|
|
resolve(data);
|
|
};
|
|
worker.addEventListener("message", receive);
|
|
worker.postMessage({ requestId, command: { type: "jsonCommand", cmd: "pythonExec", params: { source, filename: "ClipStabUnmute.py", console: false } } });
|
|
});
|
|
if (!response.ok) throw new Error(`marker unmute failed: ${JSON.stringify(response.error)}`);
|
|
return true;
|
|
});
|
|
expect(unmuted).toBe(true);
|
|
|
|
/* Hide every track so the composite carries the frame alone: desktop draws
|
|
* the marker overlay before the stabilization warp, and those boxes would
|
|
* corrupt the sampled pixels. */
|
|
const hidden = surface.getByTestId("clip-track-hidden");
|
|
const trackCount = await surface.getByTestId("clip-track-item").count();
|
|
expect(trackCount).toBeGreaterThanOrEqual(3);
|
|
for (let index = 0; index < trackCount; index++) {
|
|
if ((await hidden.nth(index).getAttribute("aria-pressed")) !== "true") await hidden.nth(index).click();
|
|
}
|
|
await waitForPressed(hidden, Array.from({ length: trackCount }, () => true), "clip track hidden flags");
|
|
|
|
/* Translation from two full-coverage tracks, rotation from those plus the
|
|
* third: desktop derives the pivot from the translation tracks, and a single
|
|
* translation track makes its own rotation lever arm exactly zero, where
|
|
* tracking_stabilize.cc divides the rotation average by a zero quality sum
|
|
* and returns NaN. That is shared desktop code (compensate_rotation_center
|
|
* then poisons translation as well), so the case uses the two-track setup a
|
|
* desktop user would need for rotation. */
|
|
const stab = surface.getByTestId("clip-track-stab");
|
|
const stabRot = surface.getByTestId("clip-track-stab-rot");
|
|
await stab.nth(1).click();
|
|
await stab.nth(4).click();
|
|
await waitForPressed(stab, [false, true, false, false, true, false, false].slice(0, trackCount), "stabilization translation flag");
|
|
await stabRot.nth(1).click();
|
|
await stabRot.nth(2).click();
|
|
await stabRot.nth(4).click();
|
|
await waitForPressed(stabRot, [false, true, true, false, true, false, false].slice(0, trackCount), "stabilization rotation flags");
|
|
|
|
/* Autoscale and rotation live in the draft; the write button commits the
|
|
* draft, then the display toggle switches the composite on. */
|
|
await surface.getByTestId("clip-stab-autoscale").check();
|
|
await surface.getByTestId("clip-stab-rotation").check();
|
|
await surface.getByTestId("clip-stab-scale").check();
|
|
await surface.getByTestId("clip-stab-write").click();
|
|
await waitForText(surface.getByTestId("clip-stab-status"), "已写入稳定化设置", "stabilization settings write");
|
|
const enabled = surface.getByTestId("clip-stab-enabled");
|
|
await enabled.click();
|
|
await waitForChecked(enabled, true, "stabilization display");
|
|
|
|
/* One in-page pass per frame: ask the product's own engine for the raw frame
|
|
* and the stabilization matrix at that frame, rebuild the composite locally
|
|
* with the same column-vector affine the canvas uses, then compare against
|
|
* the canvas until it has rendered. Returning only metrics keeps the frame
|
|
* bytes off the Playwright channel. */
|
|
type StabMetrics = {
|
|
stableMae: number; identityMae: number; compared: number; skipped: number; frame: number;
|
|
width: number; height: number; canvas: { width: number; height: number };
|
|
matrix: number[]; translation: number[];
|
|
};
|
|
const measureFrame = async (targetFrame: number): Promise<StabMetrics> => page.evaluate(async ({ frame: targetFrame }) => {
|
|
const canvas = document.querySelector<HTMLCanvasElement>('[data-testid="clip-frame-canvas"]');
|
|
if (!canvas) throw new Error("clip frame canvas is missing");
|
|
const clipId = document.querySelector<HTMLElement>('[data-testid="clip-list-item"]')?.getAttribute("data-clip-id") ?? "";
|
|
if (!clipId) throw new Error("clip id is missing from the clip list");
|
|
const worker = (window as unknown as { __nativeWorkflowEngine: Worker }).__nativeWorkflowEngine;
|
|
const requestId = `clip-stab-composite-${crypto.randomUUID()}`;
|
|
const response = await new Promise<{ ok: boolean; error?: unknown; result?: { json?: unknown } }>((resolve, reject) => {
|
|
const timer = setTimeout(() => { worker.removeEventListener("message", receive); reject(new Error("clipFrame reference timed out")); }, 120_000);
|
|
const receive = ({ data }: MessageEvent<{ requestId: string; ok: boolean; error?: unknown; result?: { json?: unknown } }>) => {
|
|
if (data.requestId !== requestId) return;
|
|
clearTimeout(timer);
|
|
worker.removeEventListener("message", receive);
|
|
resolve(data);
|
|
};
|
|
worker.addEventListener("message", receive);
|
|
worker.postMessage({ requestId, command: { type: "jsonCommand", cmd: "clipFrame", params: { dataId: clipId, frame: targetFrame, stabilize: true } } });
|
|
});
|
|
if (!response.ok) throw new Error(`clipFrame failed for frame ${targetFrame}: ${JSON.stringify(response.error)}`);
|
|
const json = response.result?.json as { width?: unknown; height?: unknown; pixelsBase64?: unknown; stabilization?: { matrix?: unknown } } | undefined;
|
|
const width = json?.width;
|
|
const height = json?.height;
|
|
const pixelsBase64 = json?.pixelsBase64;
|
|
const matrix = json?.stabilization?.matrix as number[] | undefined;
|
|
if (typeof width !== "number" || typeof height !== "number" || typeof pixelsBase64 !== "string" || !Array.isArray(matrix) || matrix.length !== 16) {
|
|
throw new Error("clipFrame reference is incomplete");
|
|
}
|
|
const raw = Uint8Array.from(atob(pixelsBase64), (character) => character.charCodeAt(0));
|
|
const channelAt = (x: number, y: number, channel: number): number => raw[(y * width + x) * 4 + channel];
|
|
/* Bilinear sample at a pixel-centre coordinate of the decoded frame. */
|
|
const sample = (x: number, y: number, channel: number): number | null => {
|
|
const px = x - 0.5;
|
|
const py = y - 0.5;
|
|
const x0 = Math.floor(px);
|
|
const y0 = Math.floor(py);
|
|
if (x0 < 1 || y0 < 1 || x0 >= width - 2 || y0 >= height - 2) return null;
|
|
const fx = px - x0;
|
|
const fy = py - y0;
|
|
const top = channelAt(x0, y0, channel) * (1 - fx) + channelAt(x0 + 1, y0, channel) * fx;
|
|
const bottom = channelAt(x0, y0 + 1, channel) * (1 - fx) + channelAt(x0 + 1, y0 + 1, channel) * fx;
|
|
return top * (1 - fy) + bottom * fy;
|
|
};
|
|
const measure = () => {
|
|
const context = canvas.getContext("2d");
|
|
if (!context) throw new Error("clip frame canvas has no 2d context");
|
|
const image = context.getImageData(0, 0, canvas.width, canvas.height);
|
|
const scaleX = canvas.width / width;
|
|
const scaleY = canvas.height / height;
|
|
/* Blender's matrix is column-major: translation sits in m[3][0..1],
|
|
* i.e. flat slots 12 and 13. */
|
|
const a = scaleX * matrix[0], b = scaleY * matrix[1], c = scaleX * matrix[4], d = scaleY * matrix[5];
|
|
const e = scaleX * matrix[12], f = scaleY * matrix[13];
|
|
const det = a * d - b * c;
|
|
let stableSum = 0, identitySum = 0, compared = 0, skipped = 0;
|
|
for (let cy = 3; cy < canvas.height - 3; cy += 11) {
|
|
for (let cx = 3; cx < canvas.width - 3; cx += 11) {
|
|
const offset = (cy * canvas.width + cx) * 4;
|
|
const sx = (d * (cx + 0.5 - e) - c * (cy + 0.5 - f)) / det;
|
|
const sy = (-b * (cx + 0.5 - e) + a * (cy + 0.5 - f)) / det;
|
|
/* A stabilized frame leaves black borders: canvas points whose
|
|
* inverse map falls outside the source are not comparable, so they
|
|
* are skipped rather than failing the whole frame. */
|
|
if (sample(sx, sy, 0) === null) {
|
|
skipped++;
|
|
continue;
|
|
}
|
|
let stableError = 0, identityError = 0;
|
|
for (let channel = 0; channel < 3; channel++) {
|
|
const observed = image.data[offset + channel];
|
|
stableError += Math.abs(observed - sample(sx, sy, channel)!);
|
|
identityError += Math.abs(observed - sample(cx + 0.5, cy + 0.5, channel)!);
|
|
}
|
|
stableSum += stableError / 3;
|
|
identitySum += identityError / 3;
|
|
compared++;
|
|
}
|
|
}
|
|
return { stableMae: compared ? stableSum / compared : Infinity, identityMae: compared ? identitySum / compared : Infinity, compared, skipped };
|
|
};
|
|
const deadline = Date.now() + 90_000;
|
|
let current = measure();
|
|
while (Date.now() < deadline && current.stableMae > 6) {
|
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
current = measure();
|
|
}
|
|
return {
|
|
...current,
|
|
frame: targetFrame,
|
|
width,
|
|
height,
|
|
canvas: { width: canvas.width, height: canvas.height },
|
|
matrix,
|
|
translation: [matrix[12], matrix[13]],
|
|
};
|
|
}, { frame: targetFrame });
|
|
/* Sample four frames spread over the clip so the composite is checked where
|
|
* the matrix carries translation, rotation and the autoscale's scale, not
|
|
* just at one hand-picked frame. */
|
|
const slider = surface.getByTestId("clip-frame-slider");
|
|
const sliderMin = Number(await slider.getAttribute("min"));
|
|
const sliderMax = Number(await slider.getAttribute("max"));
|
|
expect(Number.isFinite(sliderMin) && Number.isFinite(sliderMax) && sliderMax > sliderMin).toBe(true);
|
|
const frames = [...new Set([0.25, 0.5, 0.75, 0.95].map((ratio) => Math.round(sliderMin + (sliderMax - sliderMin) * ratio)))];
|
|
const measured: StabMetrics[] = [];
|
|
for (const frame of frames) {
|
|
await setRangeValue(slider, frame);
|
|
await waitForInputValue(slider, String(frame), `stabilization frame ${frame}`);
|
|
const metrics = await measureFrame(frame);
|
|
measured.push(metrics);
|
|
expect(metrics.canvas.width, `frame ${frame}: canvas width`).toBe(metrics.width);
|
|
expect(metrics.canvas.height, `frame ${frame}: canvas height`).toBe(metrics.height);
|
|
expect(metrics.compared, `frame ${frame}: compared samples`).toBeGreaterThan(1000);
|
|
expect(metrics.stableMae, `frame ${frame}: stabilized mae`).toBeLessThanOrEqual(6);
|
|
expect(metrics.identityMae, `frame ${frame}: identity mae`).toBeGreaterThanOrEqual(metrics.stableMae);
|
|
}
|
|
/* At least one sampled frame must travel far enough that the matrix visibly
|
|
* beats the identity, and the linear part must be non-trivial (the autoscale
|
|
* and rotation toggles were committed above). */
|
|
const distant = measured.filter((metrics) => Math.hypot(metrics.translation[0], metrics.translation[1]) > 50);
|
|
expect(distant.length, "no sampled frame moved more than 50 px").toBeGreaterThan(0);
|
|
const discriminating = measured.filter((metrics) => metrics.identityMae > metrics.stableMae * 3);
|
|
expect(discriminating.length, "the stabilized composite never beat the identity").toBeGreaterThan(0);
|
|
expect(measured.some((metrics) => Math.abs(metrics.matrix[0] - 1) > 0.02 || Math.abs(metrics.matrix[4]) > 0.02), "matrix linear part stayed identity").toBe(true);
|
|
await attach(testInfo, "clip-stab-composite", { frames: measured });
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-source] reloads, sets the scene range and relinks the clip source", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const bundleBlend = fs.readFileSync(bundleBlendPath);
|
|
const result = await page.evaluate(async ({ blendBase64, footageBase64, bundleBlendBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const clipOf = (project: any) => project?.clips?.[0] ?? null;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
let stage = "open";
|
|
try {
|
|
const opened = await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], [{ path: "footage/tripod-motion.avi", buffer: bytes(footageBase64) }]);
|
|
const clip = clipOf(opened.snapshot.trackingMasks);
|
|
if (!clip) throw new Error("trackingMasks.clips is empty");
|
|
stage = "reload";
|
|
const reloaded = await client.manageMovieClip(clip.id, { op: "reload" });
|
|
stage = "setSceneFrames";
|
|
const setFrames = await client.manageMovieClip(clip.id, { op: "setSceneFrames" });
|
|
// SceneIR snapshots expose scenes as an array; renderSettings lives on the first scene.
|
|
const scene = setFrames.snapshot.scenes?.[0]?.renderSettings ?? null;
|
|
const frameClip = clipOf(setFrames.snapshot.trackingMasks);
|
|
stage = "relink-missing";
|
|
const missing = await client.manageMovieClip(clip.id, { op: "relink", filepath: "//footage/absent-clip.avi" });
|
|
const missingClip = clipOf(missing.snapshot.trackingMasks);
|
|
stage = "relink-restore";
|
|
const restored = await client.manageMovieClip(clip.id, { op: "relink", filepath: "//footage/tripod-motion.avi" });
|
|
const restoredClip = clipOf(restored.snapshot.trackingMasks);
|
|
client.terminate();
|
|
|
|
const bundleClient = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
stage = "bundle-open";
|
|
try {
|
|
const bundleOpened = await bundleClient.openBlend(bytes(bundleBlendBase64), undefined, undefined, [], [], []);
|
|
const bundleClip = clipOf(bundleOpened.snapshot.trackingMasks);
|
|
return {
|
|
clipId: clip.id as string,
|
|
initial: { sourceStatus: clip.sourceStatus as string, frameStart: clip.frameStart as number, frameEnd: clip.frameEnd as number },
|
|
reloadOp: reloaded.op, reloadAffected: reloaded.affected,
|
|
setFramesOp: setFrames.op,
|
|
sceneRange: scene ? { frameStart: scene.frameStart as number, frameEnd: scene.frameEnd as number } : null,
|
|
frameClipRange: frameClip ? { frameStart: frameClip.frameStart as number, frameEnd: frameClip.frameEnd as number } : null,
|
|
missingStatus: missingClip?.sourceStatus as string | undefined,
|
|
restoredStatus: restoredClip?.sourceStatus as string | undefined,
|
|
restoredSha: restoredClip?.sourceSha256 as string | undefined,
|
|
bundle: bundleClip ? {
|
|
sourceStatus: bundleClip.sourceStatus as string,
|
|
trackCount: (bundleClip.tracks ?? []).length as number,
|
|
} : null,
|
|
};
|
|
}
|
|
finally { bundleClient.terminate(); }
|
|
}
|
|
catch (error) { return { failed: true, stage, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64"), footageBase64: footage.toString("base64"), bundleBlendBase64: bundleBlend.toString("base64") });
|
|
await attach(testInfo, "clip-source", result);
|
|
expect((result as any).failed ?? false, (result as any).message).toBe(false);
|
|
expect(result.initial.sourceStatus).toBe("AVAILABLE");
|
|
expect(result.reloadOp).toBe("reload");
|
|
expect(result.setFramesOp).toBe("setSceneFrames");
|
|
expect(result.sceneRange).toBeTruthy();
|
|
expect(result.sceneRange!.frameStart).toBe(result.frameClipRange!.frameStart);
|
|
expect(result.sceneRange!.frameEnd).toBe(result.frameClipRange!.frameEnd);
|
|
expect(result.frameClipRange!.frameEnd - result.frameClipRange!.frameStart).toBe(result.initial.frameEnd - result.initial.frameStart);
|
|
expect(result.missingStatus).toBe("MISSING");
|
|
expect(result.restoredStatus).toBe("AVAILABLE");
|
|
expect(result.restoredSha).toBe(footageSha256);
|
|
expect(result.bundle).toBeTruthy();
|
|
expect(result.bundle!.sourceStatus).toBe("MISSING");
|
|
expect(result.bundle!.trackCount).toBeGreaterThan(0);
|
|
});
|
|
|
|
test("[clip-dopesheet] selects a track and jumps to a keyframe cell", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const surface = await openClipEditor(page, blendPath);
|
|
await surface.getByTestId("clip-mode-dopesheet").click();
|
|
const sheet = surface.getByTestId("clip-dopesheet");
|
|
await expect(sheet).toBeVisible({ timeout: 30_000 });
|
|
const rows = sheet.getByTestId("clip-dopesheet-row");
|
|
await expect.poll(async () => rows.count(), { timeout: 60_000, message: "dopesheet has no rows" }).toBeGreaterThan(0);
|
|
await rows.first().click();
|
|
const keys = sheet.locator("button.clip-dopesheet-key");
|
|
await expect.poll(async () => keys.count(), { timeout: 60_000, message: "dopesheet has no keyframe cells" }).toBeGreaterThan(0);
|
|
/* Key marks store clip-local frames; a key outside the clip range clamps on
|
|
* jump and can never become the current frame, so pick one inside it. */
|
|
const frameStart = Number(await sheet.getAttribute("data-frame-start"));
|
|
const frameEnd = Number(await sheet.getAttribute("data-frame-end"));
|
|
const maxLocal = frameEnd - frameStart + 1;
|
|
let key = keys.first();
|
|
let title = await key.getAttribute("title");
|
|
const total = await keys.count();
|
|
for (let index = 0; index < total; index++) {
|
|
const candidate = keys.nth(index);
|
|
const candidateTitle = await candidate.getAttribute("title");
|
|
const frame = Number(/帧\s*(-?\d+)/.exec(candidateTitle ?? "")?.[1]);
|
|
if (Number.isFinite(frame) && frame >= 1 && frame <= maxLocal) { key = candidate; title = candidateTitle; break; }
|
|
}
|
|
await key.click();
|
|
await expect.poll(async () => key.getAttribute("data-current"), { timeout: 60_000, message: `clicked keyframe ${title} did not become current` }).toBe("true");
|
|
await attach(testInfo, "clip-dopesheet", { title, rows: await rows.count(), keys: await keys.count(), current: await key.getAttribute("data-current") });
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-graph] draws the desktop graph view and jumps from a knot", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const surface = await openClipEditor(page, blendPath);
|
|
await surface.getByTestId("clip-relink-input").setInputFiles(trackingFixture("footage/tripod-motion.avi"));
|
|
await waitForText(surface.getByTestId("clip-list-item").first().locator("em[data-status]"), "可用", "graph clip source");
|
|
/* Desktop only draws knots for the active track, so select one first. */
|
|
await surface.getByTestId("clip-track-item").first().click();
|
|
await surface.getByTestId("clip-mode-graph").click();
|
|
const graph = surface.getByTestId("clip-graph");
|
|
await expect(graph).toBeVisible({ timeout: 30_000 });
|
|
await surface.getByTestId("clip-graph-refresh").click();
|
|
const points = graph.locator("circle.clip-graph-point");
|
|
await expect.poll(async () => points.count(), { timeout: 120_000, message: "graph has no samples" }).toBeGreaterThan(0);
|
|
|
|
/* Desktop View2D data rect (space_clip.cc init_preview_region): scene frames
|
|
* 0..efra horizontally, -10..10 graph units vertically. Every knot must sit
|
|
* at that mapping, which is what makes the drawing pixel-level comparable. */
|
|
const frameStart = Number(await graph.getAttribute("data-frame-start"));
|
|
const sceneEnd = Number(await graph.getAttribute("data-scene-frame-end"));
|
|
const viewWidth = Number(await graph.getAttribute("data-view-width"));
|
|
const viewHeight = Number(await graph.getAttribute("data-view-height"));
|
|
const viewXMin = Number(await graph.getAttribute("data-view-x-min"));
|
|
const viewXMax = Number(await graph.getAttribute("data-view-x-max"));
|
|
const viewYMin = Number(await graph.getAttribute("data-view-y-min"));
|
|
const viewYMax = Number(await graph.getAttribute("data-view-y-max"));
|
|
expect(viewXMin).toBe(0);
|
|
expect(viewXMax).toBe(sceneEnd);
|
|
expect(Number.isFinite(frameStart) && frameStart >= 0).toBe(true);
|
|
expect(Number.isFinite(sceneEnd) && sceneEnd > 0).toBe(true);
|
|
type Knot = { cx: number; cy: number; title: string };
|
|
const knots = (): Promise<Knot[]> => points.evaluateAll((items) => items.map((item) => ({
|
|
cx: Number(item.getAttribute("cx")),
|
|
cy: Number(item.getAttribute("cy")),
|
|
title: item.querySelector("title")?.textContent ?? "",
|
|
})));
|
|
const assertDesktopMapping = (items: Knot[], label: string) => {
|
|
expect(items.length, `${label}: no knots`).toBeGreaterThan(0);
|
|
for (const knot of items) {
|
|
const match = knot.title.match(/帧 (-?\d+) · (-?\d+(?:\.\d+)?)/);
|
|
expect(match, `${label}: knot title is unreadable (${knot.title})`).not.toBeNull();
|
|
const frame = Number(match![1]);
|
|
const value = Number(match![2]);
|
|
const expectedX = (frame + frameStart - 1 - viewXMin) / (viewXMax - viewXMin) * viewWidth;
|
|
const expectedY = viewHeight - (value - viewYMin) / (viewYMax - viewYMin) * viewHeight;
|
|
expect(Math.abs(knot.cx - expectedX), `${label}: x of ${knot.title} (${knot.cx} vs ${expectedX})`).toBeLessThanOrEqual(0.6);
|
|
expect(Math.abs(knot.cy - expectedY), `${label}: y of ${knot.title} (${knot.cy} vs ${expectedY})`).toBeLessThanOrEqual(0.6);
|
|
}
|
|
};
|
|
assertDesktopMapping(await knots(), "SPEED_X");
|
|
|
|
/* Unselected tracks draw at half alpha and 1 px, the active track at 2 px. */
|
|
const widths = await graph.locator("polyline").evaluateAll((items) => items.map((item) => Number(item.getAttribute("stroke-width"))));
|
|
expect(widths.some((width) => width === 2)).toBe(true);
|
|
|
|
/* View2D navigation: the wheel zooms around the cursor and 全部 restores the
|
|
* initial 0..efra / -10..10 rect, which the mapping check above relies on. */
|
|
const canvasBox = await graph.locator("svg").boundingBox();
|
|
expect(canvasBox).not.toBeNull();
|
|
await page.mouse.move(canvasBox!.x + canvasBox!.width / 2, canvasBox!.y + canvasBox!.height / 2);
|
|
await page.mouse.wheel(0, -240);
|
|
const zoomedDeadline = Date.now() + 15_000;
|
|
while (Date.now() < zoomedDeadline && Number(await graph.getAttribute("data-view-x-max")) === sceneEnd) {
|
|
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
}
|
|
const zoomedXMax = Number(await graph.getAttribute("data-view-x-max"));
|
|
expect(zoomedXMax, "wheel did not zoom the graph view").not.toBe(sceneEnd);
|
|
await surface.getByTestId("clip-graph-fit").click();
|
|
await expect.poll(async () => Number(await graph.getAttribute("data-view-x-max")), { timeout: 20_000 }).toBe(sceneEnd);
|
|
expect(Number(await graph.getAttribute("data-view-x-min"))).toBe(0);
|
|
expect(Number(await graph.getAttribute("data-view-y-min"))).toBe(-10);
|
|
expect(Number(await graph.getAttribute("data-view-y-max"))).toBe(10);
|
|
|
|
const sourceY = surface.getByTestId("clip-graph-source-SPEED_Y");
|
|
await sourceY.click();
|
|
await expect(sourceY).toHaveAttribute("data-active", "true");
|
|
await surface.getByTestId("clip-graph-refresh").click();
|
|
await expect.poll(async () => points.count(), { timeout: 120_000, message: "graph has no SPEED_Y samples" }).toBeGreaterThan(0);
|
|
assertDesktopMapping(await knots(), "SPEED_Y");
|
|
|
|
const slider = surface.getByTestId("clip-frame-slider");
|
|
const sliderMin = Number(await slider.getAttribute("min"));
|
|
if (Number.isFinite(sliderMin)) await setRangeValue(slider, sliderMin);
|
|
await expect.poll(async () => Number(await slider.inputValue()), { timeout: 30_000 }).toBe(sliderMin);
|
|
const before = Number(await slider.inputValue());
|
|
const sample = points.last();
|
|
const sampleTitle = await sample.locator("title").textContent().catch(() => null);
|
|
/* Desktop knots can sit outside the visible data rect; activate the node
|
|
* directly instead of aiming a pointer at a clipped circle. */
|
|
await sample.evaluate((element) => element.dispatchEvent(new MouseEvent("click", { bubbles: true })));
|
|
await expect.poll(async () => Number(await slider.inputValue()), { timeout: 60_000, message: "graph point did not jump the frame" }).not.toBe(before);
|
|
await attach(testInfo, "clip-graph", { points: await points.count(), before, after: Number(await slider.inputValue()), sampleTitle, frameStart, sceneEnd });
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("[clip-mask-edit] edits mask splines from the Clip editor canvas", async ({ page }, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
const fixtureResult = await page.evaluate(async ({ blendBase64 }) => {
|
|
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
|
const bytes = (base64: string) => Uint8Array.from(atob(base64), (character) => character.charCodeAt(0)).buffer;
|
|
const base64 = (buffer: ArrayBuffer) => {
|
|
const view = new Uint8Array(buffer);
|
|
let binary = "";
|
|
for (let index = 0; index < view.length; index += 0x8000) binary += String.fromCharCode(...view.subarray(index, index + 0x8000));
|
|
return btoa(binary);
|
|
};
|
|
const source = `import bpy\nmask = bpy.data.masks.new(name="E2E_Mask")\nlayer = mask.layers.new(name="Layer")\nspline = layer.splines.new()\nspline.points.add(2)\ncoords = [(0.3, 0.3), (0.7, 0.3), (0.5, 0.7)]\nfor point, coordinate in zip(spline.points, coords):\n point.co = coordinate\nspline.use_cyclic = True\n`;
|
|
const client = new WebEngineClient({ nativeFiles: false, timeoutMs: 240_000 });
|
|
try {
|
|
await client.openBlend(bytes(blendBase64), undefined, undefined, [], [], []);
|
|
const created = await client.executeEmbeddedPython(source, "ClipMaskFixture.py", false);
|
|
const masks = ((created.snapshot.trackingMasks?.masks ?? []) as any[]).map((mask) => ({
|
|
id: mask.id as string,
|
|
name: mask.name as string,
|
|
splines: (mask.layers ?? []).reduce((count: number, layer: any) => count + (layer.splines ?? []).length, 0),
|
|
points: (mask.layers ?? []).flatMap((layer: any) => (layer.splines ?? []).map((spline: any) => (spline.points ?? []).length)),
|
|
}));
|
|
const saved = await client.saveBlend();
|
|
return { pythonState: created.python.state, pythonError: created.python.error ?? null, pythonOutput: (created.python.output ?? "").slice(0, 2000), masks, blendBase64: base64(saved as ArrayBuffer) };
|
|
}
|
|
catch (error) { return { failed: true, message: (error as Error)?.message ?? String(error), code: (error as any)?.code ?? null }; }
|
|
finally { client.terminate(); }
|
|
}, { blendBase64: blend.toString("base64") });
|
|
await attach(testInfo, "clip-mask-fixture", {
|
|
pythonState: fixtureResult.pythonState,
|
|
pythonError: (fixtureResult as any).pythonError ?? null,
|
|
pythonOutput: (fixtureResult as any).pythonOutput ?? null,
|
|
});
|
|
expect((fixtureResult as any).failed ?? false, (fixtureResult as any).message).toBe(false);
|
|
expect(fixtureResult.pythonState).toBe("DONE");
|
|
expect(fixtureResult.masks.length).toBe(1);
|
|
expect(fixtureResult.masks[0].splines).toBe(1);
|
|
expect(fixtureResult.masks[0].points).toEqual([3]);
|
|
const maskBlendFile = testInfo.outputPath("clip-mask-fixture.blend");
|
|
fs.writeFileSync(maskBlendFile, Buffer.from(fixtureResult.blendBase64, "base64"));
|
|
const maskSha256 = crypto.createHash("sha256").update(fs.readFileSync(maskBlendFile)).digest("hex");
|
|
|
|
const surface = await openClipEditor(page, maskBlendFile);
|
|
await surface.getByTestId("clip-mask-mode").click();
|
|
const controls = surface.getByTestId("clip-mask-controls");
|
|
await expect(controls).toBeVisible({ timeout: 30_000 });
|
|
const select = surface.getByTestId("clip-mask-select");
|
|
await expect.poll(async () => select.inputValue(), { timeout: 30_000, message: "the mask fixture is not listed" }).toMatch(/^mask:/);
|
|
const maskValue = await select.inputValue();
|
|
|
|
await surface.getByTestId("clip-mask-create-spline").click();
|
|
const status = surface.getByTestId("clip-mask-status");
|
|
await waitForMaskStatus(status, "已新建蒙版样条", "phase=create");
|
|
const createdStatus = await status.innerText();
|
|
const canvas = surface.getByTestId("clip-frame-canvas");
|
|
const box = await canvas.boundingBox();
|
|
if (!box) throw new Error("clip canvas has no layout box");
|
|
const point: [number, number] = [0.3, 0.3];
|
|
await page.mouse.click(box.x + point[0] * box.width, box.y + (1 - point[1]) * box.height);
|
|
const cyclic = surface.getByTestId("clip-mask-cyclic");
|
|
await expect.poll(async () => cyclic.isEnabled(), { timeout: 30_000, message: "phase=select-point: clicking a control point did not select it" }).toBe(true);
|
|
await cyclic.click();
|
|
/* The fixture spline starts cyclic, and the click above selects its (0.3, 0.3)
|
|
point, so toggling necessarily reports the un-cyclic label. */
|
|
await waitForMaskStatus(status, "已取消循环", "phase=cyclic");
|
|
const toggledStatus = await status.innerText();
|
|
await surface.getByTestId("clip-mask-delete-spline").click();
|
|
await waitForMaskStatus(status, "已删除蒙版样条", "phase=delete");
|
|
await attach(testInfo, "clip-mask-edit", {
|
|
fixture: { path: maskBlendFile, sha256: maskSha256, masks: fixtureResult.masks },
|
|
ui: { maskValue, createdStatus, toggledStatus, deletedStatus: await status.innerText(), points: point },
|
|
});
|
|
await expect(surface.getByTestId("clip-edit-error")).toHaveCount(0);
|
|
});
|
|
|
|
test("fixture digests are bound", () => {
|
|
expect(blendSha256).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(footageSha256).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(solveFootageSha256).toMatch(/^[0-9a-f]{64}$/);
|
|
const fixtures = [
|
|
stabBlendPath, locrotBlendPath, pointBlendPath, bundleBlendPath,
|
|
undistortBlendPath, undistortGridPath,
|
|
...locrotFootageNames.map((name) => trackingFixture(`footage/synthetic-locrotscale/${name}`)),
|
|
];
|
|
for (const fixturePath of fixtures) {
|
|
expect(fs.existsSync(fixturePath), `missing fixture: ${fixturePath}`).toBe(true);
|
|
expect(crypto.createHash("sha256").update(fs.readFileSync(fixturePath)).digest("hex")).toMatch(/^[0-9a-f]{64}$/);
|
|
}
|
|
});
|