// Shared "build models -> save checkpoint -> precision" flow for line episodes. // Scene ids: S00 title (driver), S01 document/checkpoint, S02.. build chunks of // two parts, then S save. Episode scripts use the same ids. import fs from "node:fs"; import path from "node:path"; import { saveCheckpoint } from "../../carrier-course/lib/ui-actions.mjs"; import { createBuilder } from "./build.mjs"; import { newDocument, spec } from "./ui.mjs"; import { checkLineCheckpoint } from "./line-precision.mjs"; export async function buildEpisodeModels({ page, rec, webRoot, rawDir, stillsDir, scene, shot, logStep, log = [], episodeId, modelNames, freshDocument = false, }) { const course = JSON.parse(fs.readFileSync(path.join(webRoot, "tools", "line-course", "course.json"), "utf8")); const episode = course.episodes.find(item => item.id === episodeId); if (!episode) throw new Error(`course.json has no episode ${episodeId}`); const parts = modelNames.flatMap(name => { const model = spec().models.find(item => item.name === name); if (!model) throw new Error(`line-spec has no model ${name}`); return model.parts; }); const expectedNames = episode.checkpointObjects; const builder = createBuilder({ page, rec, logStep }); await scene("S01", async () => { if (freshDocument) { await newDocument(page); } else { // Checkpoint loading is asynchronous; wait for the expected number of // previous objects before creating anything, otherwise the new Box can // be confused with an existing object (seen with COURSE_FAST=1). const priorCount = expectedNames.length - parts.length; for (let attempt = 0; attempt < 120; attempt++) { const labels = await builder.labels(); if (labels.filter(label => expectedNames.includes(label)).length >= priorCount) break; await page.waitForTimeout(500); } } logStep({ step: "start", episode: episodeId, labels: await builder.labels(), freshDocument }); await shot("S01-start"); }); const buildPart = async part => { const dims = part.fcLocalDims; if (part.primitive === "cylinder") { // Use the average radius so slightly elliptical references stay inside // the 1.5 mm bbox tolerance on both axes (ABB_P03: 219.36 x 214.92). const radius = Math.max(0.1, (dims[0] + dims[1]) / 4); const position = [part.center[0], part.center[1], part.position[2]]; await builder.createCylinder(part.partName, radius, dims[2], position); } else { await builder.createBox(part.partName, dims, part.position); } await builder.setColor(part.partName, part.color); logStep({ step: "part", name: part.partName, dims, position: part.position, primitive: part.primitive, color: part.color }); }; const sceneIds = []; for (let index = 0; index < parts.length; index += 2) { const id = `S${String(2 + index / 2).padStart(2, "0")}`; sceneIds.push(id); const slice = parts.slice(index, index + 2); await scene(id, async () => { for (const part of slice) await buildPart(part); await shot(`${id}-parts`); }); } const saveId = `S${String(2 + sceneIds.length).padStart(2, "0")}`; await scene(saveId, async () => { const saved = await saveCheckpoint({ page, rec, webRoot, episode: episodeId, rawDir, checkpointDir: path.join(webRoot, "tools", "line-course", "checkpoints"), expectedLabels: expectedNames }); logStep({ step: "checkpoint", ...saved }); const checkpoint = path.join(webRoot, "tools", "line-course", "checkpoints", `${episodeId}.FCStd`); const precision = await checkLineCheckpoint(checkpoint, expectedNames); fs.writeFileSync(path.join(rawDir, `${episodeId}-precision.json`), `${JSON.stringify(precision, null, 2)}\n`); if (!precision.ok) throw new Error(`precision failed: ${JSON.stringify({ extra: precision.extra, models: precision.models.filter(item => !item.ok), failures: precision.results.filter(item => !item.ok) })}`); fs.writeFileSync(path.join(rawDir, `${episodeId}-state.json`), `${JSON.stringify({ schema: `freecad-web-line-course/${episodeId}/state/v1`, generatedAt: new Date().toISOString(), models: modelNames, parts: parts.map(part => part.partName), precision, log, }, null, 2)}\n`); await shot(`${saveId}-recap`); }); return { parts, expectedNames, sceneIds, saveId }; }