feat(moves): mount Academy moves by manifest kind (gait, trick on R, command script)
- ?move=<ref> boot parameter (?policy= alias, ?session=&round= sugar) - session:<id>[:<round>] refs fetch same-origin /api/play/* endpoints - episodic manifests mount in the roll slot as a one-shot on R - perpetual slot sitstand swaps the sit policy; walk unchanged - script manifests load move_script.json and drive the 13-D command vector on the walker (linear keyframes, loop), toggled by R - HUD chip: PLAYING <prompt or name> by <author> Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+11
-4
@@ -41,13 +41,20 @@ export default function App() {
|
||||
window.addEventListener("touchstart", armTouch, { once: true, passive: true });
|
||||
if (params.get("touch") === "1") armTouch();
|
||||
|
||||
// ?policy=<org/repo or .onnx URL>: request a community walk policy.
|
||||
// ?move=<ref>: request a community move (Academy D7). ref is an
|
||||
// "org/repo" Hub move, "session:<id>[:<round>]" (a private Academy run,
|
||||
// served same-origin) or a direct .onnx URL. ?policy= is the legacy
|
||||
// alias, and ?session=<id>[&round=<r>] is sugar for move=session:<id>:<r>.
|
||||
// Only the request is recorded here; the game loads it after boot
|
||||
// (never blocking it) and flips the status to active/error itself.
|
||||
const policyRef = params.get("policy");
|
||||
if (policyRef) {
|
||||
let moveRef = params.get("move") || params.get("policy");
|
||||
if (!moveRef && params.get("session")) {
|
||||
const round = params.get("round");
|
||||
moveRef = `session:${params.get("session")}${round ? `:${round}` : ""}`;
|
||||
}
|
||||
if (moveRef) {
|
||||
useGame.setState({
|
||||
customPolicy: { ref: policyRef, name: policyRef, status: "loading" },
|
||||
customPolicy: { ref: moveRef, name: moveRef, status: "loading" },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+218
-50
@@ -1,17 +1,40 @@
|
||||
// Community policy loading: resolve a Hub repo id (or a direct .onnx URL)
|
||||
// into a validated onnxruntime session the game can drop into its walk
|
||||
// slot. Mirrors the official publish pipeline's smoke run: shape checks,
|
||||
// a zeros inference and two noisy inferences that must produce finite,
|
||||
// non-constant actions before the session ever touches the duck.
|
||||
// Community move loading: resolve a move ref (Hub repo id, Academy session
|
||||
// ref or a direct .onnx URL) into a validated onnxruntime session (or a
|
||||
// command script) the game can drop into one of its slots. Mirrors the
|
||||
// official publish pipeline's smoke run: shape checks, a zeros inference
|
||||
// and two noisy inferences that must produce finite, non-constant actions
|
||||
// before the session ever touches the duck.
|
||||
//
|
||||
// Slots (manifest schema 2, Academy decision D7):
|
||||
// kind "perpetual" (gait) -> "walk" (default) or "sitstand" (slot field)
|
||||
// kind "episodic" (trick) -> "trick": a one-shot on the R key
|
||||
// kind "script" -> "script": a 13-D command timeline played on
|
||||
// the base walker while R is toggled on
|
||||
//
|
||||
// The module is deliberately framework-free (no game imports): the caller
|
||||
// hands in the `ort` namespace it already booted, and pure helpers like
|
||||
// manifestIncompatibility are reusable by standalone pages without pulling
|
||||
// the game bundle in.
|
||||
|
||||
import { OBS_SIZE, NUM_JOINTS } from "./constants.js";
|
||||
import { OBS_SIZE, NUM_JOINTS, CMD_SIZE } from "./constants.js";
|
||||
|
||||
const HUB_BASE = "https://huggingface.co";
|
||||
// Same-origin Academy endpoints (backend/play_api.py) for private moves.
|
||||
const PLAY_API = "/api/play";
|
||||
|
||||
export const SUPPORTED_KINDS = ["perpetual", "episodic", "script"];
|
||||
// Default one-shot length for an episodic trick without a duration claim.
|
||||
const DEFAULT_TRICK_S = 5.0;
|
||||
|
||||
// Game slot a manifest mounts into (see the header). A missing manifest is
|
||||
// a plain walk policy, exactly like v1.
|
||||
export function slotForManifest(manifest) {
|
||||
const kind = manifest?.kind ?? "perpetual";
|
||||
if (kind === "script") return "script";
|
||||
if (kind === "episodic") return "trick";
|
||||
const slot = String(manifest?.slot ?? "walk").toLowerCase();
|
||||
return slot === "sitstand" || slot === "sit" ? "sitstand" : "walk";
|
||||
}
|
||||
|
||||
// Manifest claims the sim cannot satisfy (schema 2). Only present-and-wrong
|
||||
// claims reject: an absent field is trusted to match the microduck defaults.
|
||||
@@ -24,59 +47,109 @@ export function manifestIncompatibility(manifest) {
|
||||
if (manifest.model_api != null && manifest.model_api > 2) {
|
||||
return `model_api ${manifest.model_api} is newer than this sim supports`;
|
||||
}
|
||||
const robotModel = manifest.robot?.model;
|
||||
if (robotModel != null && robotModel !== "microduck") {
|
||||
return `targets robot "${robotModel}", not microduck`;
|
||||
}
|
||||
const kind = manifest.kind ?? "perpetual";
|
||||
if (!SUPPORTED_KINDS.includes(kind)) {
|
||||
return `"${manifest.kind}" policies are not supported (kinds: ${SUPPORTED_KINDS.join(", ")})`;
|
||||
}
|
||||
// A script drives the built-in walker: no network claims to check.
|
||||
if (kind === "script") return null;
|
||||
if (manifest.obs_len != null && manifest.obs_len !== OBS_SIZE) {
|
||||
return `expects ${manifest.obs_len} observations (sim provides ${OBS_SIZE})`;
|
||||
}
|
||||
if (manifest.action_len != null && manifest.action_len !== NUM_JOINTS) {
|
||||
return `outputs ${manifest.action_len} actions (sim drives ${NUM_JOINTS})`;
|
||||
}
|
||||
const robotModel = manifest.robot?.model;
|
||||
if (robotModel != null && robotModel !== "microduck") {
|
||||
return `targets robot "${robotModel}", not microduck`;
|
||||
}
|
||||
// v1 only swaps the walk slot: perpetual, constant-command policies.
|
||||
if (manifest.kind != null && manifest.kind !== "perpetual") {
|
||||
return `"${manifest.kind}" policies are not supported yet (walk-slot only)`;
|
||||
}
|
||||
if (manifest.slot != null && manifest.slot !== "walk") {
|
||||
return `slot "${manifest.slot}" is not supported yet (walk-slot only)`;
|
||||
}
|
||||
const encoding = manifest.command?.encoding;
|
||||
if (encoding != null && encoding !== "constant") {
|
||||
return `command encoding "${encoding}" is not supported yet`;
|
||||
}
|
||||
if (manifest.mode != null && manifest.mode !== "walk") {
|
||||
return `mode "${manifest.mode}" is not supported yet (walk-slot only)`;
|
||||
if (kind === "perpetual") {
|
||||
const slot = manifest.slot != null ? String(manifest.slot).toLowerCase() : null;
|
||||
if (slot != null && !["walk", "sitstand", "sit"].includes(slot)) {
|
||||
return `perpetual slot "${manifest.slot}" is not supported (walk or sitstand)`;
|
||||
}
|
||||
const encoding = manifest.command?.encoding;
|
||||
if (encoding != null && encoding !== "constant") {
|
||||
return `command encoding "${encoding}" is not supported yet`;
|
||||
}
|
||||
if (manifest.mode != null && manifest.mode !== "walk" && slot !== "sitstand" && slot !== "sit") {
|
||||
return `mode "${manifest.mode}" is not supported yet (walk-slot only)`;
|
||||
}
|
||||
}
|
||||
// Episodic tricks: every slot (stand, roulade, kick_left, ground_pick,
|
||||
// R, ...) mounts on the R key as a zero-command one-shot.
|
||||
return null;
|
||||
}
|
||||
|
||||
// A policy ref is either an org/repo Hub id or a direct URL to a .onnx.
|
||||
// A direct URL may sit next to a manifest.json (the Academy's private-policy
|
||||
// handoff serves both under one capability URL): it is probed best-effort.
|
||||
// Parse the "session:<id>[:<round>]" ref form. Returns null when `r` is not
|
||||
// a session ref. `round` is null when absent.
|
||||
function parseSessionRef(r) {
|
||||
const m = /^session:([\w.-]+)(?::([\w.-]+))?$/i.exec(r);
|
||||
return m ? { id: m[1], round: m[2] ?? null } : null;
|
||||
}
|
||||
|
||||
// Build a same-origin Academy URL for a private session artifact.
|
||||
function sessionApiUrl(endpoint, { id, round }, extra = {}) {
|
||||
const q = new URLSearchParams({ session: id });
|
||||
if (round != null) q.set("round", String(round));
|
||||
for (const [k, v] of Object.entries(extra)) q.set(k, v);
|
||||
return `${PLAY_API}/${endpoint}?${q}`;
|
||||
}
|
||||
|
||||
// A move ref is one of:
|
||||
// "org/repo" a Hub move repo (manifest + policy.onnx)
|
||||
// "session:<id>[:<round>]" a private Academy run, served same-origin
|
||||
// "https://.../x.onnx" a direct URL (sibling manifest probed)
|
||||
// Resolves to the URLs of the three artifacts the loader may need.
|
||||
export function resolvePolicyRef(ref) {
|
||||
const r = String(ref || "").trim();
|
||||
if (/^https?:\/\//i.test(r)) {
|
||||
let manifestUrl = null;
|
||||
let scriptUrl = null;
|
||||
try {
|
||||
const u = new URL(r);
|
||||
const name = u.pathname.split("/").pop() || "";
|
||||
if (/\.onnx$/i.test(name)) {
|
||||
u.pathname = u.pathname.slice(0, -name.length) + "manifest.json";
|
||||
const dir = u.pathname.slice(0, -name.length);
|
||||
u.pathname = `${dir}manifest.json`;
|
||||
manifestUrl = u.href;
|
||||
u.pathname = `${dir}move_script.json`;
|
||||
scriptUrl = u.href;
|
||||
}
|
||||
} catch { /* unparsable: no manifest probe */ }
|
||||
return { kind: "url", name: r.split("/").pop()?.split("?")[0] || r, onnxUrl: r, manifestUrl, manifestOptional: true };
|
||||
return {
|
||||
kind: "url",
|
||||
name: r.split("/").pop()?.split("?")[0] || r,
|
||||
author: null,
|
||||
onnxUrl: r,
|
||||
manifestUrl,
|
||||
scriptUrl,
|
||||
manifestOptional: true,
|
||||
};
|
||||
}
|
||||
const sess = parseSessionRef(r);
|
||||
if (sess) {
|
||||
return {
|
||||
kind: "session",
|
||||
name: sess.round != null ? `session ${sess.id} (round ${sess.round})` : `session ${sess.id}`,
|
||||
author: null,
|
||||
onnxUrl: sessionApiUrl("policy", sess),
|
||||
manifestUrl: sessionApiUrl("manifest", sess),
|
||||
scriptUrl: sessionApiUrl("file", sess, { path: "move_script.json" }),
|
||||
manifestOptional: true,
|
||||
};
|
||||
}
|
||||
if (!/^[\w.-]+\/[\w.-]+$/.test(r)) {
|
||||
throw new Error(`invalid policy ref "${r}" (expected org/repo or a .onnx URL)`);
|
||||
throw new Error(`invalid move ref "${r}" (expected org/repo, session:<id> or a .onnx URL)`);
|
||||
}
|
||||
return {
|
||||
kind: "hub",
|
||||
name: r,
|
||||
author: r.split("/")[0],
|
||||
repoId: r,
|
||||
onnxUrl: `${HUB_BASE}/${r}/resolve/main/policy.onnx`,
|
||||
manifestUrl: `${HUB_BASE}/${r}/resolve/main/manifest.json`,
|
||||
scriptUrl: `${HUB_BASE}/${r}/resolve/main/move_script.json`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -93,6 +166,69 @@ export async function fetchPolicyManifest(repoId) {
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// Optional sibling manifest (direct URL / Academy session): 404 = none.
|
||||
// A 401 from the Academy means the visitor is not signed in - that one is
|
||||
// worth surfacing instead of silently playing nothing.
|
||||
async function fetchOptionalManifest(url) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (res.status === 401) throw new Error("sign in to the Academy to play a private move");
|
||||
if (!res.ok) return null;
|
||||
try {
|
||||
return await res.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Command script (kind "script"): {duration_s, loop, keyframes:[{t, cmd[13]}]}.
|
||||
// Keyframes are sorted by t and every cmd is padded/truncated to CMD_SIZE.
|
||||
export function normalizeMoveScript(raw) {
|
||||
if (!raw || typeof raw !== "object" || !Array.isArray(raw.keyframes) || !raw.keyframes.length) {
|
||||
throw new Error("move_script.json has no keyframes");
|
||||
}
|
||||
const keyframes = raw.keyframes.map((k, i) => {
|
||||
const t = Number(k?.t);
|
||||
if (!Number.isFinite(t) || t < 0) throw new Error(`keyframe ${i}: bad time`);
|
||||
const src = Array.isArray(k?.cmd) ? k.cmd : [];
|
||||
const cmd = new Float32Array(CMD_SIZE);
|
||||
for (let c = 0; c < CMD_SIZE; c++) {
|
||||
const v = Number(src[c] ?? 0);
|
||||
if (!Number.isFinite(v)) throw new Error(`keyframe ${i}: non-finite command`);
|
||||
cmd[c] = v;
|
||||
}
|
||||
return { t, cmd };
|
||||
});
|
||||
keyframes.sort((a, b) => a.t - b.t);
|
||||
const last = keyframes[keyframes.length - 1].t;
|
||||
const durationS = Number.isFinite(Number(raw.duration_s)) && Number(raw.duration_s) > 0
|
||||
? Math.max(Number(raw.duration_s), last)
|
||||
: Math.max(last, 0.02);
|
||||
return { keyframes, durationS, loop: raw.loop !== false, description: raw.description || "" };
|
||||
}
|
||||
|
||||
// Linearly interpolated command at time t (loop-aware), written into `out`.
|
||||
export function scriptCommandAt(script, t, out) {
|
||||
const { keyframes, durationS, loop } = script;
|
||||
let tt = t;
|
||||
if (loop && durationS > 0) tt = ((t % durationS) + durationS) % durationS;
|
||||
if (tt <= keyframes[0].t) { out.set(keyframes[0].cmd); return out; }
|
||||
for (let i = 0; i < keyframes.length - 1; i++) {
|
||||
const a = keyframes[i], b = keyframes[i + 1];
|
||||
if (tt >= a.t && tt <= b.t) {
|
||||
const u = (tt - a.t) / Math.max(b.t - a.t, 1e-6);
|
||||
for (let c = 0; c < CMD_SIZE; c++) out[c] = (1 - u) * a.cmd[c] + u * b.cmd[c];
|
||||
return out;
|
||||
}
|
||||
}
|
||||
out.set(keyframes[keyframes.length - 1].cmd);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Publish-pipeline smoke run: 1 input / 1 output, a zeros pass plus two
|
||||
// small-noise passes; every output must be [1,14], finite, and the noisy
|
||||
// passes must not produce identical actions (a constant net is a dud).
|
||||
@@ -126,25 +262,37 @@ async function validateSession(ort, session) {
|
||||
if (maxDiff < 1e-9) throw new Error("constant output in smoke run (dead policy)");
|
||||
}
|
||||
|
||||
// Load + validate a community policy. Resolves to everything the game needs
|
||||
// to swap its walk slot; throws with a clear message on any failure.
|
||||
async function fetchOrThrow(url, what) {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) throw new Error("sign in to the Academy to play a private move");
|
||||
throw new Error(
|
||||
res.status === 404 ? `no ${what} found at ${url}` : `${what} download failed (HTTP ${res.status})`,
|
||||
);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Load + validate a community move. Resolves to everything the game needs
|
||||
// to mount it in its slot; throws with a clear message on any failure.
|
||||
// onProgress receives coarse stages for the HUD loading line.
|
||||
//
|
||||
// Result: { kind, slot, name, title, author, academy, ref, actionScale,
|
||||
// durationS, session?, inputName?, outputName?, script? }
|
||||
export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {}) {
|
||||
const resolved = resolvePolicyRef(ref);
|
||||
let name = resolved.name;
|
||||
let author = resolved.author;
|
||||
let actionScale = 1.0;
|
||||
let manifest = null;
|
||||
|
||||
if (resolved.manifestUrl) {
|
||||
onProgress("manifest");
|
||||
let manifest = null;
|
||||
if (resolved.manifestOptional) {
|
||||
// Sibling manifest of a direct URL: any failure (404, CORS, bad JSON)
|
||||
// just means "no manifest", exactly like before the probe existed.
|
||||
// Only a present-and-incompatible manifest rejects below.
|
||||
try {
|
||||
const res = await fetch(resolved.manifestUrl);
|
||||
if (res.ok) manifest = await res.json();
|
||||
} catch { manifest = null; }
|
||||
// Sibling manifest of a direct URL / session: 404 or a network error
|
||||
// just means "no manifest" (a plain walk policy), exactly like before
|
||||
// the probe existed. Only present-and-incompatible manifests reject.
|
||||
manifest = await fetchOptionalManifest(resolved.manifestUrl);
|
||||
} else {
|
||||
try {
|
||||
manifest = await fetchPolicyManifest(resolved.repoId);
|
||||
@@ -159,18 +307,34 @@ export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {})
|
||||
if (reason) throw new Error(reason);
|
||||
if (typeof manifest.name === "string" && manifest.name) name = manifest.name;
|
||||
if (Number.isFinite(manifest.action_scale)) actionScale = manifest.action_scale;
|
||||
if (typeof manifest.academy?.author === "string" && manifest.academy.author) {
|
||||
author = manifest.academy.author;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onProgress("download");
|
||||
const res = await fetch(resolved.onnxUrl);
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
res.status === 404
|
||||
? `no policy.onnx found at ${resolved.name}`
|
||||
: `policy download failed (HTTP ${res.status})`,
|
||||
);
|
||||
const slot = slotForManifest(manifest);
|
||||
const kind = manifest?.kind ?? "perpetual";
|
||||
const academy = manifest?.academy && typeof manifest.academy === "object" ? manifest.academy : null;
|
||||
const title = academy?.prompt || manifest?.description || name;
|
||||
const base = { kind, slot, name, title, author, academy, ref: String(ref), actionScale };
|
||||
|
||||
if (slot === "script") {
|
||||
if (!resolved.scriptUrl) throw new Error("script moves need a manifest with a sibling move_script.json");
|
||||
onProgress("script");
|
||||
const res = await fetchOrThrow(resolved.scriptUrl, "move_script.json");
|
||||
let raw;
|
||||
try {
|
||||
raw = await res.json();
|
||||
} catch {
|
||||
throw new Error("move_script.json is not valid JSON");
|
||||
}
|
||||
const script = normalizeMoveScript(raw);
|
||||
return { ...base, script, durationS: script.durationS };
|
||||
}
|
||||
|
||||
onProgress("download");
|
||||
const res = await fetchOrThrow(resolved.onnxUrl, "policy.onnx");
|
||||
const bytes = new Uint8Array(await res.arrayBuffer());
|
||||
|
||||
onProgress("session");
|
||||
@@ -184,11 +348,15 @@ export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {})
|
||||
onProgress("validate");
|
||||
await validateSession(ort, session);
|
||||
|
||||
const claimed = Number(manifest?.duration_s ?? manifest?.episode_s ?? manifest?.episode?.duration_s);
|
||||
const durationS = slot === "trick"
|
||||
? (Number.isFinite(claimed) && claimed > 0 ? Math.min(claimed, 30) : DEFAULT_TRICK_S)
|
||||
: null;
|
||||
|
||||
return {
|
||||
...base,
|
||||
session,
|
||||
name,
|
||||
ref: String(ref),
|
||||
actionScale,
|
||||
durationS,
|
||||
inputName: session.inputNames[0],
|
||||
outputName: session.outputNames[0],
|
||||
};
|
||||
|
||||
+99
-22
@@ -57,7 +57,7 @@ import {
|
||||
playPropSweep, playLineBlip, setRumble,
|
||||
} from "./audio.js";
|
||||
import { createBallActor } from "./ball-actor.js";
|
||||
import { loadCustomPolicy as loadCustomPolicyModule } from "./custom-policy.js";
|
||||
import { loadCustomPolicy as loadCustomPolicyModule, scriptCommandAt } from "./custom-policy.js";
|
||||
import { initGhosts } from "./ghosts.js";
|
||||
import { makeInfiniteGrid, makeArenaWalls } from "./arena.js";
|
||||
import { createBallVisual } from "./ball-visual.js";
|
||||
@@ -353,12 +353,21 @@ async function boot({ scene, camera, renderer }) {
|
||||
}
|
||||
donePolicies("7/7");
|
||||
|
||||
// ── Community policy slot (walk only) ─────────────────────────────────
|
||||
// A validated Hub policy can replace sessions.walk; every other slot
|
||||
// (recovery, sitstand, kicks, roulade, rollers) stays official. The
|
||||
// official walker is pinned here so a swap is always reversible.
|
||||
// ── Community move slots ──────────────────────────────────────────────
|
||||
// A validated move mounts according to its manifest (Academy D7):
|
||||
// perpetual -> sessions.walk (default) or sessions.sitstand (R key)
|
||||
// episodic -> sessions.roll, played as a one-shot "trick" on R
|
||||
// script -> a 13-D command timeline on the walker, toggled by R
|
||||
// Every other slot (recovery, kicks, rollers) stays official. The
|
||||
// official sessions are pinned here so a swap is always reversible.
|
||||
const officialWalk = sessions.walk;
|
||||
let customPolicy = null; // { session, name, ref, actionScale }
|
||||
const officialSitstand = sessions.sitstand;
|
||||
const officialRoll = sessions.roll;
|
||||
let customPolicy = null; // loadCustomPolicy result: { kind, slot, session?, script?, ... }
|
||||
let scriptRun = null; // { t } while a kind "script" move drives the commands
|
||||
// True while the custom session is the one producing this step's actions.
|
||||
const customDriving = () =>
|
||||
!!(customPolicy?.session && activeSession() === customPolicy.session);
|
||||
// Watchdog: abnormal-ending timestamps (recovery entries + solver
|
||||
// explosions) while a custom policy drives the duck. 3 within a rolling
|
||||
// 20 s window auto-reverts; ~10 s without a new event clears the slate
|
||||
@@ -375,18 +384,27 @@ async function boot({ scene, camera, renderer }) {
|
||||
if (!customPolicy) return;
|
||||
const prev = customPolicy;
|
||||
customPolicy = null;
|
||||
scriptRun = null;
|
||||
watchdogEvents = [];
|
||||
sessions.walk = officialWalk;
|
||||
sessions.sitstand = officialSitstand;
|
||||
sessions.roll = officialRoll;
|
||||
if (revertReason) {
|
||||
console.warn(`[policy] reverted "${prev.name}": ${revertReason}`);
|
||||
setStore({
|
||||
customPolicy: { ref: prev.ref, name: prev.name, status: "error", revertReason },
|
||||
customPolicy: { ...storeMove(prev), status: "error", revertReason },
|
||||
});
|
||||
} else {
|
||||
setStore({ customPolicy: null });
|
||||
}
|
||||
}
|
||||
|
||||
// Store projection of a loaded move (no session / script objects in React).
|
||||
const storeMove = (m) => ({
|
||||
ref: m.ref, name: m.name, title: m.title ?? m.name, author: m.author ?? null,
|
||||
kind: m.kind ?? "perpetual", slot: m.slot ?? "walk", academy: m.academy ?? null,
|
||||
});
|
||||
|
||||
function watchdogAbnormalEnd(kind) {
|
||||
if (!customPolicy) return;
|
||||
const now = performance.now();
|
||||
@@ -406,12 +424,15 @@ async function boot({ scene, camera, renderer }) {
|
||||
setStore({ customPolicy: { ref: String(ref), name: String(ref), status: "loading" } });
|
||||
try {
|
||||
const loaded = await loadCustomPolicyModule(ref, { ort });
|
||||
revertCustomPolicy(); // drop any previous custom walker first
|
||||
revertCustomPolicy(); // drop any previous custom move first
|
||||
customPolicy = loaded;
|
||||
watchdogEvents = [];
|
||||
sessions.walk = loaded.session;
|
||||
setStore({ customPolicy: { ref: loaded.ref, name: loaded.name, status: "active" } });
|
||||
console.info(`[policy] custom walk policy active: ${loaded.name} (${loaded.ref})`);
|
||||
if (loaded.slot === "walk") sessions.walk = loaded.session;
|
||||
else if (loaded.slot === "sitstand") sessions.sitstand = loaded.session;
|
||||
else if (loaded.slot === "trick") sessions.roll = loaded.session;
|
||||
// "script": nothing to swap, the R key starts the command player.
|
||||
setStore({ customPolicy: { ...storeMove(loaded), status: "active" } });
|
||||
console.info(`[policy] custom ${loaded.kind} move active in slot ${loaded.slot}: ${loaded.name} (${loaded.ref})`);
|
||||
} catch (e) {
|
||||
const error = e?.message || String(e);
|
||||
console.warn(`[policy] load failed for "${ref}":`, e);
|
||||
@@ -633,6 +654,7 @@ async function boot({ scene, camera, renderer }) {
|
||||
// Single reset path: Space, fall-kill, failed roll, loco switch.
|
||||
clearModeTimers();
|
||||
rollRun = null;
|
||||
scriptRun = null;
|
||||
kickRun = null;
|
||||
crouchRun = null;
|
||||
pickRun = null;
|
||||
@@ -757,6 +779,12 @@ async function boot({ scene, camera, renderer }) {
|
||||
const gpZero = mode === "groundpick" || recovery !== null;
|
||||
cmd[3] = gpZero ? 0 : headSmooth[0]; cmd[4] = gpZero ? 0 : headSmooth[1];
|
||||
cmd[5] = gpZero ? 0 : headSmooth[2]; cmd[6] = gpZero ? 0 : headSmooth[3];
|
||||
// Command script (kind "script" move): the timeline owns the whole
|
||||
// 13-D command vector while it plays on the walker. Movement input is
|
||||
// ignored until R stops it (or the script ends, when it doesn't loop).
|
||||
if (scriptRun && mode === "walk" && !recovery && customPolicy?.script) {
|
||||
scriptCommandAt(customPolicy.script, scriptRun.t, cmd);
|
||||
}
|
||||
for (let c = 0; c < CMD_SIZE; c++) obs[i++] = cmd[c];
|
||||
return obs;
|
||||
}
|
||||
@@ -966,6 +994,17 @@ async function boot({ scene, camera, renderer }) {
|
||||
}
|
||||
stepAudioSim(); // footsteps / rumble / ball thumps off the fresh state
|
||||
|
||||
// Command script clock: 50 Hz like everything here. A non-looping
|
||||
// script ends on its own; a looping one runs until R (or a reset).
|
||||
if (scriptRun) {
|
||||
scriptRun.t += CTRL_DT;
|
||||
const sc = customPolicy?.script;
|
||||
if (!sc || (!sc.loop && scriptRun.t >= sc.durationS)) {
|
||||
scriptRun = null;
|
||||
syncButtons();
|
||||
}
|
||||
}
|
||||
|
||||
// Watchdog housekeeping: a healthy stretch (no abnormal ending for
|
||||
// ~10 s) forgives earlier events, so player-caused falls spread over
|
||||
// a session never accumulate into a revert.
|
||||
@@ -978,8 +1017,9 @@ async function boot({ scene, camera, renderer }) {
|
||||
if (death === "exploded") {
|
||||
haptics.pulse("explode");
|
||||
// Solver explosions only implicate the custom policy while it is the
|
||||
// one driving (legs walk); one-shots and rollers stay official.
|
||||
if (loco === "legs" && mode === "walk") watchdogAbnormalEnd("exploded");
|
||||
// one driving (its slot: walk, sitstand or the trick one-shot);
|
||||
// official one-shots and rollers never count.
|
||||
if (loco === "legs" && customDriving()) watchdogAbnormalEnd("exploded");
|
||||
resetSim();
|
||||
} else if (recovery) {
|
||||
// Recovery state machine owns the duck: settle -> stand policy ->
|
||||
@@ -1028,7 +1068,12 @@ async function boot({ scene, camera, renderer }) {
|
||||
// same haptic thud, once - fallenSince latches until reset/upright.
|
||||
if (fallenSince == null) haptics.pulse("fall");
|
||||
fallenSince ??= now;
|
||||
if (now - fallenSince > graceMs) resetSim();
|
||||
if (now - fallenSince > graceMs) {
|
||||
// A custom sit / trick that floors the duck counts for the
|
||||
// watchdog exactly like a recovery entry does for a walker.
|
||||
if (loco === "legs" && customDriving()) watchdogAbnormalEnd("fallen");
|
||||
resetSim();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fallDebounce = 0;
|
||||
@@ -1089,15 +1134,20 @@ async function boot({ scene, camera, renderer }) {
|
||||
if (obs[5] > -0.3) rollRun.tipped = true;
|
||||
const upright = obs[5] < -0.85;
|
||||
const done = rollRun.tipped && upright && rollRun.steps >= 40;
|
||||
const expired = rollRun.steps >= 150; // 3 s, roll should long be over
|
||||
// 3 s for the official roll (it should long be over); a custom
|
||||
// trick runs for its manifest duration instead.
|
||||
const expired = rollRun.steps >= rollRun.maxSteps;
|
||||
if (done || expired) {
|
||||
const wasCustom = rollRun.custom;
|
||||
rollRun = null;
|
||||
mode = "walk";
|
||||
lastAction.fill(0);
|
||||
// Timed out mid-roll: don't hand a tipped duck to the walking
|
||||
// policy (it has no get-up skill).
|
||||
if (!upright) resetSim();
|
||||
else haptics.pulse("land"); // rolled through and stuck the landing
|
||||
if (!upright) {
|
||||
if (wasCustom) watchdogAbnormalEnd("fallen");
|
||||
resetSim();
|
||||
} else haptics.pulse("land"); // rolled through and stuck the landing
|
||||
syncButtons();
|
||||
}
|
||||
}
|
||||
@@ -1921,6 +1971,10 @@ async function boot({ scene, camera, renderer }) {
|
||||
// the crouch-glide, exactly as the (now unbound) roll action did.
|
||||
controller.on("sitToggle", ({ source } = {}) => {
|
||||
if (loco !== "legs") return triggerCrouch(srcTag(source));
|
||||
// A community trick / script takes over the R key while it is mounted
|
||||
// (a custom sitstand keeps the sit toggle: it IS the sit policy).
|
||||
if (customPolicy?.slot === "trick") return triggerRoll(srcTag(source));
|
||||
if (customPolicy?.slot === "script") return toggleScript();
|
||||
const sitting = mode === "sitstand" && sitFlag === 1;
|
||||
setMode(sitting ? "walk" : "sit");
|
||||
});
|
||||
@@ -2009,11 +2063,30 @@ async function boot({ scene, camera, renderer }) {
|
||||
clearModeTimers();
|
||||
mode = "roll";
|
||||
sitFlag = 0;
|
||||
rollRun = { steps: 0, tipped: false };
|
||||
// A custom episodic trick lives in the roll slot and runs for its own
|
||||
// duration (loadCustomPolicy clamps it); the official roulade keeps
|
||||
// its 3 s hard window.
|
||||
const custom = customPolicy?.slot === "trick" && sessions.roll === customPolicy.session;
|
||||
const maxSteps = custom ? Math.max(10, Math.round((customPolicy.durationS ?? 5) / CTRL_DT)) : 150;
|
||||
rollRun = { steps: 0, tipped: false, custom, maxSteps };
|
||||
syncButtons();
|
||||
stickers?.pop("roll");
|
||||
}
|
||||
|
||||
// Kind "script" move: R toggles the command timeline on the walker.
|
||||
function toggleScript() {
|
||||
if (!customPolicy?.script) return;
|
||||
if (scriptRun) {
|
||||
scriptRun = null;
|
||||
syncButtons();
|
||||
return;
|
||||
}
|
||||
if (inputLocked || mode !== "walk" || standTimer || recovery || loco !== "legs") return;
|
||||
exitHeadMode();
|
||||
scriptRun = { t: 0 };
|
||||
syncButtons();
|
||||
}
|
||||
|
||||
// Roller-only one-shot: crouch, glide low, stand back up (phase-driven).
|
||||
function triggerCrouch(source = "kb") {
|
||||
if (inputLocked || mode !== "walk" || locoSwitching || recovery) return;
|
||||
@@ -2061,7 +2134,8 @@ async function boot({ scene, camera, renderer }) {
|
||||
const sitting = mode === "sitstand" && sitFlag === 1;
|
||||
const label =
|
||||
recovery ? "Recovery"
|
||||
: mode === "roll" ? "Roll"
|
||||
: mode === "roll" ? (rollRun?.custom ? "Trick" : "Roll")
|
||||
: scriptRun ? "Script"
|
||||
: mode === "crouch" ? "Crouch"
|
||||
: mode === "groundpick" ? "Pick"
|
||||
: isKick() ? "Kick"
|
||||
@@ -2109,6 +2183,8 @@ async function boot({ scene, camera, renderer }) {
|
||||
loadCustomPolicy: loadCustomPolicyIntoGame,
|
||||
clearCustomPolicy: revertCustomPolicy,
|
||||
get customPolicy() { return customPolicy; },
|
||||
get scriptRun() { return scriptRun; },
|
||||
toggleScript,
|
||||
get watchdogEvents() { return watchdogEvents.slice(); },
|
||||
get loco() { return loco; },
|
||||
get locoSwitching() { return locoSwitching; },
|
||||
@@ -2164,9 +2240,10 @@ async function boot({ scene, camera, renderer }) {
|
||||
// with READY. + fade on its own.
|
||||
setStore({ bootDone: true });
|
||||
|
||||
// ?policy=<ref> (parsed in App.jsx into the store): load the community
|
||||
// policy now that the sim is up. Fire-and-forget - a bad ref surfaces
|
||||
// its error in the HUD while the official walker keeps the duck alive.
|
||||
// ?move=<ref> / ?policy=<ref> / ?session=<id> (parsed in App.jsx into the
|
||||
// store): load the community move now that the sim is up. Fire-and-forget
|
||||
// - a bad ref surfaces its error in the HUD while the official walker
|
||||
// keeps the duck alive.
|
||||
const requestedPolicy = store().customPolicy;
|
||||
if (requestedPolicy?.status === "loading" && requestedPolicy.ref) {
|
||||
loadCustomPolicyIntoGame(requestedPolicy.ref);
|
||||
|
||||
+5
-3
@@ -29,10 +29,12 @@ export const useGame = create(
|
||||
locoSwitching: false,
|
||||
rollersLoading: false, // OSD line while the roller stack streams in
|
||||
variant: "classic",
|
||||
// Community walk policy: null = official walker. Written by the game
|
||||
// Community move: null = all-official slots. Written by the game
|
||||
// (game.js loadCustomPolicyIntoGame / the watchdog) and by App.jsx for
|
||||
// the boot-time ?policy= request.
|
||||
// { ref, name, status: "loading"|"active"|"error", error?, revertReason? }
|
||||
// the boot-time ?move= request.
|
||||
// { ref, name, status: "loading"|"active"|"error", error?, revertReason?,
|
||||
// kind?: "perpetual"|"episodic"|"script", slot?: "walk"|"sitstand"|"trick"|"script",
|
||||
// title?, author?, academy? (manifest.academy block) }
|
||||
customPolicy: null,
|
||||
padConnected: false,
|
||||
touchMode: false,
|
||||
|
||||
+16
-11
@@ -411,14 +411,19 @@ function Quickbar() {
|
||||
);
|
||||
}
|
||||
|
||||
// Active community policy chip: rides the quickbar row in the same panel
|
||||
// language. Shows the policy's name and an X that swaps the official
|
||||
// walker back in (gameApi.clearCustomPolicy).
|
||||
// Active community move chip: rides the quickbar row in the same panel
|
||||
// language. "PLAYING: <prompt or name> by <owner>" (Academy moves carry
|
||||
// their prompt and author in manifest.academy), a hint on the key that
|
||||
// plays a trick / script, and an X that swaps the official slot back in
|
||||
// (gameApi.clearCustomPolicy).
|
||||
function PolicyChip() {
|
||||
const cp = useGame((s) => s.customPolicy);
|
||||
if (cp?.status !== "active") return null;
|
||||
const title = cp.title || cp.name;
|
||||
const by = cp.author ? ` by ${cp.author}` : "";
|
||||
const hint = cp.slot === "trick" || cp.slot === "script" || cp.slot === "sitstand" ? " \u00b7 R" : "";
|
||||
return (
|
||||
<HudPlate caption="Policy" captionFill="orange">
|
||||
<HudPlate caption="Playing" captionFill="orange">
|
||||
<Box sx={{ display: "inline-flex", alignItems: "stretch", height: "100%" }}>
|
||||
<Box
|
||||
sx={{
|
||||
@@ -426,20 +431,20 @@ function PolicyChip() {
|
||||
px: "0.85rem",
|
||||
cursor: "default",
|
||||
color: ORANGE,
|
||||
maxWidth: "14rem",
|
||||
maxWidth: "22rem",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
display: "inline-block",
|
||||
lineHeight: `${CELL_H}px`,
|
||||
}}
|
||||
title={cp.ref}
|
||||
title={`${cp.ref}${cp.kind ? ` (${cp.kind})` : ""}`}
|
||||
>
|
||||
{cp.name}
|
||||
{`${title}${by}${hint}`}
|
||||
</Box>
|
||||
<Box
|
||||
component="button"
|
||||
type="button"
|
||||
aria-label={`Unload policy ${cp.name}`}
|
||||
aria-label={`Unload move ${cp.name}`}
|
||||
onClick={() => { uiClick(); gameApi.clearCustomPolicy?.(); }}
|
||||
sx={{
|
||||
...hudHitSx,
|
||||
@@ -532,7 +537,7 @@ function OsdLoad() {
|
||||
const policyLoading = useGame((s) => s.customPolicy?.status === "loading");
|
||||
const lines = [];
|
||||
if (rollersLoading) lines.push("LOADING ROLLERS");
|
||||
if (policyLoading) lines.push("LOADING POLICY");
|
||||
if (policyLoading) lines.push("LOADING MOVE");
|
||||
if (!lines.length) return null;
|
||||
return (
|
||||
<Box
|
||||
@@ -582,8 +587,8 @@ function PolicyToast() {
|
||||
}, [cp, isError]);
|
||||
if (!isError) return null;
|
||||
const msg = cp.revertReason
|
||||
? `POLICY REVERTED \u00b7 ${cp.revertReason}`
|
||||
: `POLICY LOAD FAILED \u00b7 ${cp.error ?? "unknown error"}`;
|
||||
? `MOVE REVERTED \u00b7 ${cp.revertReason}`
|
||||
: `MOVE LOAD FAILED \u00b7 ${cp.error ?? "unknown error"}`;
|
||||
return (
|
||||
<Box
|
||||
role="alert"
|
||||
|
||||
Reference in New Issue
Block a user