// The robot's brain runs here, off the page's thread: the world model, MPPI and the mission. The page only draws. import { loadModel } from "./core/model.js"; import { Mission } from "./core/mission.js"; let mis = null, running = false, speed = 1, timer = null; const post = (type, data = {}) => postMessage({ type, ...data }); const sendReach = () => post("reach", { n: 100, map: mis.reachMap(100) }); async function init() { const json = await (await fetch("./core/model.json")).json(); mis = new Mission(loadModel(json), 0); sendReach(); post("frame", mis.frame(null)); post("ready"); } function loop() { timer = null; if (!running || !mis) return; const t0 = performance.now(); const f = mis.step(); post("frame", f); if (f.phase === "idle" && f.toys.every(t => t.state !== "floor" || mis.placeable(t.x, t.y))) { running = false; post("done", { t: f.t, stats: f.stats }); return; } const wall = performance.now() - t0, budget = speed === 0 ? 0 : 200 / speed; // 0.2 s of robot time per tick timer = setTimeout(loop, Math.max(0, budget - wall)); } onmessage = ({ data: d }) => { if (d.type === "init") return void init(); if (!mis) return; switch (d.type) { case "run": running = d.on; if (running && !timer) loop(); break; case "speed": speed = d.v; break; case "furniture": mis.setFurniture(d.list); sendReach(); if (!running) post("frame", mis.frame(null)); break; case "addToy": { const r = mis.addToy(d.x, d.y); if (!r.ok) post("toast", { text: r.why }); post("frame", mis.frame(null)); if (r.ok && !running && d.autostart) { running = true; if (!timer) loop(); post("running", { on: true }); } break; } case "removeToy": mis.removeToy(d.id); post("frame", mis.frame(null)); break; case "reset": running = false; mis.reset(); post("running", { on: false }); post("frame", mis.frame(null)); break; } };