feat: release v0.3 with RP1 trained skills and scaled arenas

This commit is contained in:
2026-10-29 14:16:04 +08:00
parent fc5ee4f2c6
commit 09f7b02c3e
86 changed files with 4136 additions and 165 deletions
+3 -2
View File
@@ -19,13 +19,14 @@ export function createArenaFloorPresentation({ sim, rig, world }) {
}
const root = new THREE.Group();
root.name = "arena-floor-presentation";
const grid = makeInfiniteGrid({ subdivisions: 1 });
const scale = world?.scale ?? 1;
const grid = makeInfiniteGrid({ subdivisions: 1, scale });
grid.name = "arena-grid";
grid.material.uniforms.uReveal.value = 1;
grid.material.uniforms.uTopoScale.value = 0;
root.add(grid);
const { wallMeshes, wallMats } = world?.boundary
? makeArenaWalls(world.boundary)
? makeArenaWalls(world.boundary, { scale })
: { wallMeshes: [], wallMats: [] };
wallMeshes.forEach((mesh, i) => {
mesh.name = `arena-boundary-${i}`;
+18 -15
View File
@@ -15,16 +15,16 @@ import {
// Lines derive from world coordinates, so re-centering the mesh under the
// camera target every frame makes the grid effectively infinite without any
// visible swimming.
export function makeInfiniteGrid({ subdivisions = 256 } = {}) {
export function makeInfiniteGrid({ subdivisions = 256, scale = 1 } = {}) {
const material = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCell: { value: 0.1 * scale },
uSection: { value: GRID_SECTION * scale },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
uFadeDist: { value: 3.0 },
uFadeDist: { value: 3.0 * scale },
uFocus: { value: new THREE.Vector3() },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0: the world stays hidden behind the welcome modal and
@@ -143,7 +143,7 @@ export function makeInfiniteGrid({ subdivisions = 256 } = {}) {
// is computed in world space, so the per-frame recentering under the
// camera target doesn't move the bumps.
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30, subdivisions, subdivisions),
new THREE.PlaneGeometry(30 * scale, 30 * scale, subdivisions, subdivisions),
material,
);
mesh.rotation.x = -Math.PI / 2;
@@ -154,19 +154,19 @@ export function makeInfiniteGrid({ subdivisions = 256 } = {}) {
// cell/section lines from world coordinates, same radial fade around the
// duck, plus a vertical fade toward the top edge so the walls read as a
// light enclosure instead of solid slabs.
function makeWallGridMaterial(alongX, wallHeight = ARENA_WALL_H) {
function makeWallGridMaterial(alongX, wallHeight = ARENA_WALL_H, scale = 1) {
return new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCell: { value: 0.1 * scale },
uSection: { value: GRID_SECTION * scale },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
// Gentler radial fade than the floor: the walls sit 1.5+ m from the
// duck by construction and would vanish with the floor's 3 m fade.
uFadeDist: { value: 5.0 },
uFadeDist: { value: 5.0 * scale },
uFocus: { value: new THREE.Vector3() },
uWallH: { value: wallHeight },
uAlongX: { value: alongX ? 1.0 : 0.0 },
@@ -286,11 +286,14 @@ export function entranceLineCues() {
// The four wall planes at their inner faces (three coords: MJCF x -> x,
// MJCF y -> -z). Returns the meshes plus their materials (the ceremony and
// the per-frame focus update both need the material list).
export function makeArenaWalls({
half_extent = ARENA_HALF,
wall_height = ARENA_WALL_H,
wall_thickness = ARENA_WALL_T,
} = {}) {
export function makeArenaWalls(
{
half_extent = ARENA_HALF,
wall_height = ARENA_WALL_H,
wall_thickness = ARENA_WALL_T,
} = {},
{ scale = 1 } = {},
) {
const wallMats = [];
const wallMeshes = [];
const wallLen = 2 * (half_extent + wall_thickness);
@@ -301,7 +304,7 @@ export function makeArenaWalls({
{ x: 0, z: -half_extent, rotY: 0, alongX: true },
];
for (const [index, w] of wallDefs.entries()) {
const mat = makeWallGridMaterial(w.alongX, wall_height);
const mat = makeWallGridMaterial(w.alongX, wall_height, scale);
wallMats.push(mat);
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(wallLen, wall_height),
+3 -1
View File
@@ -28,7 +28,9 @@ export class InputRouter {
constructor({ bindings, getVelocityLimits, isEnabled = () => true }) {
Object.assign(this, { bindings, getVelocityLimits, isEnabled });
this.byCode = new Map(
bindings.flatMap((b) => b.codes.map((code) => [code, b.action])),
bindings
.filter((b) => !b.disabled)
.flatMap((b) => b.codes.map((code) => [code, b.action])),
);
}
init(target = window) {
+3 -3
View File
@@ -1,5 +1,5 @@
import { validatePackage, validateWorld } from "./SchemaValidator.js";
import { DEFAULT_WORLD } from "../worlds/arena.js";
import { DEFAULT_WORLD, fitWorldToRobot } from "../worlds/arena.js";
export function assetUrl(path, base, location = globalThis.location) {
const url = new URL(path, base);
if (location && url.origin !== location.origin)
@@ -43,7 +43,7 @@ export async function loadIndex() {
url: assetUrl(entry.manifest, base),
}));
}
export async function loadWorld(id = DEFAULT_WORLD) {
export async function loadWorld(id = DEFAULT_WORLD, config) {
const base = new URL(
`${import.meta.env.BASE_URL}worlds/${id}/`,
location.origin,
@@ -52,5 +52,5 @@ export async function loadWorld(id = DEFAULT_WORLD) {
validateWorld(world);
if (world.id !== id)
throw new Error(`worlds/${id}: unsupported World schema`);
return world;
return fitWorldToRobot(world, config);
}
+113 -6
View File
@@ -12,6 +12,10 @@ function assertSchema(check, value, label) {
}
export function validateWorld(world) {
assertSchema(checkWorld, world, "world.json");
if (world.scale_to_robot && (world.type !== "flat" || !world.boundary))
throw new Error(
"world.json /scale_to_robot: requires a flat World with boundary",
);
if (world.boundary && world.type !== "flat")
throw new Error("world.json /boundary: requires a flat World");
if (world.type === "flat" && !world.floor)
@@ -37,7 +41,11 @@ export function validatePackage(config) {
ids.add(skill.id);
if (!groups[skill.owns])
throw new Error(`skills.${skill.id}.owns: unknown group ${skill.owns}`);
if (skill.controller.type === "onnx" && !skill.controller.policy)
if (
skill.controller.type === "onnx" &&
skill.available !== false &&
!skill.controller.policy
)
throw new Error(`skills.${skill.id}.controller.policy: required`);
if (skill.kind === "primary") primaries++;
if (skill.kind === "overlay")
@@ -50,17 +58,92 @@ export function validatePackage(config) {
if (
config.adapter === "generic" &&
(primaries !== 1 ||
config.skills.some((s) => !["primary", "overlay"].includes(s.kind)))
config.skills.some(
(s) => !["primary", "overlay", "episodic"].includes(s.kind),
))
)
throw new Error(
"generic runtime requires one primary and disjoint overlays",
"generic runtime requires one primary, disjoint overlays and optional episodic skills",
);
for (const obs of Object.values(config.observations))
const primary = config.skills.find((s) => s.kind === "primary");
if (config.adapter === "generic") {
if (primary.available === false || primary.controller.type !== "onnx")
throw new Error("primary: an available ONNX controller is required");
for (const skill of config.skills) {
if (skill.available === false && skill.kind !== "episodic")
throw new Error(
"available:false is only supported for episodic skills",
);
if (skill.kind === "overlay" && skill.controller.type !== "oscillator")
throw new Error("overlay: oscillator required");
if (
skill.kind === "episodic" &&
(skill.owns !== primary.owns ||
skill.controller.type !== "onnx" ||
!skill.duration ||
!skill.blend)
)
throw new Error(
"episodic: requires primary ownership, ONNX, duration and blend",
);
if (
skill.kind !== "episodic" &&
(skill.observations ||
skill.actions ||
skill.defaults ||
skill.reference)
)
throw new Error(
"per-skill observations/actions/defaults require an episodic skill",
);
const motionTerms = Object.values(
skill.observations ?? config.observations,
)
.flatMap((spec) => spec.terms)
.filter((term) => term.type === "motion_command");
if (motionTerms.length && (!skill.reference || skill.kind !== "episodic"))
throw new Error(
`skills.${skill.id}: motion_command requires an episodic reference`,
);
if (motionTerms.some((term) => term.group !== skill.owns))
throw new Error(
`skills.${skill.id}: motion reference must use owned joint order`,
);
for (const name of Object.keys(skill.defaults ?? {}))
if (!groups[skill.owns].includes(name))
throw new Error(
`skills.${skill.id}.defaults: unknown owned joint ${name}`,
);
}
for (const skill of config.skills.filter((s) =>
["primary", "episodic"].includes(s.kind),
)) {
for (const action of skill.actions ?? config.actions)
if (!groups[action.group])
throw new Error(`actions: unknown group ${action.group}`);
const names = (skill.actions ?? config.actions).flatMap(
(a) => groups[a.group],
);
if (JSON.stringify(names) !== JSON.stringify(groups[skill.owns]))
throw new Error(
`skills.${skill.id}: action order must match owned joints`,
);
}
}
for (const obs of [
config.observations,
...config.skills.map((s) => s.observations).filter(Boolean),
].flatMap(Object.values))
for (const term of obs.terms) {
if (term.group && !groups[term.group])
throw new Error(`observations: unknown group ${term.group}`);
if (
["joint_pos_rel", "joint_vel", "last_action"].includes(term.type) &&
[
"joint_pos_rel",
"joint_vel",
"last_action",
"motion_command",
].includes(term.type) &&
!term.group
)
throw new Error(`${term.type}: group required`);
@@ -76,7 +159,10 @@ export function validatePackage(config) {
"observations.command: size missing or exceeds command buffer",
);
}
for (const action of config.actions)
for (const action of [
config.actions,
...config.skills.map((s) => s.actions).filter(Boolean),
].flat())
if (!groups[action.group])
throw new Error(`actions: unknown group ${action.group}`);
if (
@@ -86,6 +172,17 @@ export function validatePackage(config) {
)
)
throw new Error("actuation: PD gains and torque_limit required");
for (const [name, p] of Object.entries(config.actuation.joints ?? {})) {
if (!Object.values(groups).flat().includes(name))
throw new Error(`actuation.joints: unknown joint ${name}`);
if (
(p.velocity_limit !== undefined || p.keep_velocity !== undefined) &&
!(p.keep_velocity > 0 && p.keep_velocity < p.velocity_limit)
)
throw new Error(
`actuation.${name}: keep_velocity must lie within velocity_limit`,
);
}
const codes = new Set();
for (const binding of config.input.bindings) {
if (
@@ -101,9 +198,19 @@ export function validatePackage(config) {
...config.skills
.filter((s) => s.kind === "overlay")
.map((s) => `toggle:${s.id}`),
...config.skills
.filter((s) => s.kind === "episodic")
.map((s) => `skill:${s.id}`),
].includes(binding.action)
)
throw new Error(`input: unsupported action ${binding.action}`);
if (binding.action.startsWith("skill:")) {
const skill = config.skills.find((s) => s.id === binding.action.slice(6));
if (skill && (skill.available === false) !== (binding.disabled === true))
throw new Error(
`input.${binding.action}: disabled must match skill availability`,
);
}
for (const code of binding.codes) {
if (codes.has(code)) throw new Error(`input: duplicate ${code}`);
codes.add(code);
+34 -1
View File
@@ -60,6 +60,14 @@
}
}
},
"dimensions": {
"type": "object",
"required": ["height"],
"additionalProperties": false,
"properties": {
"height": { "type": "number", "exclusiveMinimum": 0 }
}
},
"base": {
"type": "object",
"required": ["type", "root_body", "freejoint", "spawn"],
@@ -161,6 +169,8 @@
"required": ["terms"],
"additionalProperties": false,
"properties": {
"history": { "type": "integer", "minimum": 1, "maximum": 64 },
"layout": { "enum": ["frame_major", "term_major"] },
"terms": {
"type": "array",
"minItems": 1,
@@ -176,6 +186,7 @@
"joint_pos_rel",
"joint_vel",
"last_action",
"motion_command",
"command"
]
},
@@ -240,6 +251,20 @@
"torque_limit": {
"type": "number",
"exclusiveMinimum": 0
},
"joints": {
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": false,
"properties": {
"kp": { "type": "number", "minimum": 0 },
"kd": { "type": "number", "minimum": 0 },
"torque_limit": { "type": "number", "exclusiveMinimum": 0 },
"velocity_limit": { "type": "number", "exclusiveMinimum": 0 },
"keep_velocity": { "type": "number", "exclusiveMinimum": 0 }
}
}
}
}
},
@@ -279,6 +304,13 @@
"owns": {
"type": "string"
},
"available": { "type": "boolean" },
"duration": { "type": "number", "exclusiveMinimum": 0 },
"blend": { "type": "number", "exclusiveMinimum": 0 },
"observations": { "$ref": "#/properties/observations" },
"actions": { "$ref": "#/properties/actions" },
"defaults": { "$ref": "#/properties/joints/properties/defaults" },
"reference": { "type": "string", "minLength": 1 },
"controller": {
"type": "object",
"required": ["type"],
@@ -332,7 +364,8 @@
},
"label": {
"type": "string"
}
},
"disabled": { "type": "boolean" }
}
}
}
+11 -3
View File
@@ -8,14 +8,22 @@
"type": { "enum": ["flat", "adapter"] },
"adapter": { "type": "string", "minLength": 1 },
"presentation": { "enum": ["arena-grid"] },
"scale_to_robot": {
"type": "object",
"additionalProperties": false,
"required": ["reference_height"],
"properties": {
"reference_height": { "type": "number", "exclusiveMinimum": 0 }
}
},
"boundary": {
"type": "object",
"additionalProperties": false,
"required": ["half_extent", "wall_height", "wall_thickness"],
"properties": {
"half_extent": {"type":"number","exclusiveMinimum":0},
"wall_height": {"type":"number","exclusiveMinimum":0},
"wall_thickness": {"type":"number","exclusiveMinimum":0}
"half_extent": { "type": "number", "exclusiveMinimum": 0 },
"wall_height": { "type": "number", "exclusiveMinimum": 0 },
"wall_thickness": { "type": "number", "exclusiveMinimum": 0 }
}
},
"floor": {
@@ -0,0 +1,68 @@
import { fetchChecked } from "../loader/PackageLoader.js";
// A trained command stream, not a kinematic animation: only observations read
// these samples. Neither qpos nor joint targets are written by this provider.
export class JointMotionReference {
static async load(pkg, path, names, dt) {
const spec = await fetchChecked(pkg.asset(path), "json");
const bytes = await fetchChecked(pkg.asset(spec.data), "bytes");
return new JointMotionReference(spec, bytes, names, dt);
}
constructor(spec, bytes, names, dt) {
if (
spec.schema !== 1 ||
spec.layout !== "positions_then_velocities" ||
spec.dtype !== "float32-le" ||
!Number.isInteger(spec.frames) ||
spec.frames < 2 ||
!Number.isFinite(spec.step_dt) ||
spec.step_dt <= 0 ||
Math.abs(spec.step_dt - dt) > 1e-9 ||
JSON.stringify(spec.joint_names) !== JSON.stringify(names)
)
throw new Error(
"Motion reference: unsupported layout, joint order or control clock",
);
const count = spec.frames * names.length;
if (bytes.byteLength !== count * 2 * 4)
throw new Error(
"Motion reference: truncated/incorrect sample count (check git lfs pull)",
);
const view = new DataView(bytes);
this.values = new Float32Array(count * 2);
for (let i = 0; i < this.values.length; i++) {
const v = view.getFloat32(i * 4, true);
if (!Number.isFinite(v))
throw new Error("Motion reference: non-finite sample");
this.values[i] = v;
}
Object.assign(this, {
frames: spec.frames,
dt: spec.step_dt,
width: names.length,
count,
});
this.reset();
}
reset() {
this.start = null;
this.frame = 0;
}
sample(time) {
if (!Number.isFinite(time))
throw new Error("Motion reference: invalid simulation time");
this.start ??= time;
this.frame = Math.min(
this.frames - 1,
Math.max(0, Math.floor((time - this.start + 1e-9) / this.dt)),
);
}
write(out, offset) {
const a = this.frame * this.width;
out.set(this.values.subarray(a, a + this.width), offset);
out.set(
this.values.subarray(this.count + a, this.count + a + this.width),
offset + this.width,
);
}
}
+54 -4
View File
@@ -6,6 +6,7 @@ export class ObservationPipeline {
this.inputs = {};
this.ops = [];
this.details = {};
this.history = new Map();
for (const [name, spec] of Object.entries(specs)) {
let offset = 0;
const terms = [];
@@ -64,15 +65,64 @@ export class ObservationPipeline {
});
offset += size;
}
if (buffers[name] && buffers[name].length !== offset)
const length = spec.history ?? 1;
const size = offset * length;
if (buffers[name] && buffers[name].length !== size)
throw new Error(`Observation buffer ${name}: incorrect size`);
this.inputs[name] = buffers[name] ?? new Float32Array(offset);
this.inputs[name] = buffers[name] ?? new Float32Array(size);
this.history.set(name, {
length,
layout: spec.layout ?? "frame_major",
terms,
frame: new Float32Array(offset),
frames: new Float32Array(size),
initialized: false,
});
this.details[name] = terms;
}
}
write() {
reset() {
for (const h of this.history.values()) h.initialized = false;
}
write({ advance = true } = {}) {
for (const op of this.ops)
op.implementation.write(this.inputs[op.name], op.offset, this.ctx, op);
op.implementation.write(
this.history.get(op.name).frame,
op.offset,
this.ctx,
op,
);
for (const [name, h] of this.history) {
const size = h.frame.length;
// Diagnostic reads sample live physics without pushing the history clock.
const frames = advance ? h.frames : h.frames.slice();
if (!h.initialized) {
// Isaac Lab CircularBuffer backfills every slot on the first sample.
for (let i = 0; i < h.length; i++) frames.set(h.frame, i * size);
h.initialized = advance;
} else {
if (advance) frames.copyWithin(0, size);
frames.set(h.frame, (h.length - 1) * size);
}
const out = this.inputs[name];
if (h.layout === "frame_major") out.set(frames);
else {
let offset = 0;
for (const term of h.terms)
for (let i = 0; i < h.length; i++) {
out.set(
frames.subarray(
i * size + term.offset,
i * size + term.offset + term.size,
),
offset,
);
offset += term.size;
}
}
if (!out.every(Number.isFinite))
throw new Error(`observations.${name}: non-finite tensor`);
}
return this.inputs;
}
}
+8
View File
@@ -57,6 +57,14 @@ observationTerms.register("command", {
for (let i = 0; i < op.term.size; i++) out[offset + i] = c.command[i];
},
});
observationTerms.register("motion_command", {
size: (_term, _ctx, names) => names.length * 2,
init: (_term, ctx) => {
if (!ctx.reference)
throw new Error("motion_command: missing per-skill reference");
},
write: (out, offset, ctx) => ctx.reference.write(out, offset),
});
for (const type of ["joint_pos_rel", "joint_vel", "last_action"])
observationTerms.register(type, {
size: (_term, _ctx, names) => names.length,
@@ -0,0 +1,54 @@
import { ObservationPipeline } from "../ObservationPipeline.js";
import { ActionPipeline } from "../ActionPipeline.js";
import { OnnxController } from "./OnnxController.js";
// Common lifecycle for independently trained, feed-forward joint-target skills.
export class OnnxPolicy {
static async load(ort, bytes, config, shared, skill, reference = null) {
let session;
try {
const ctx = {
...shared,
reference,
defaults: new Map([
...shared.defaults,
...Object.entries(skill.defaults ?? {}),
]),
lastAction: new Float32Array(shared.policyNames.length),
};
const obs = new ObservationPipeline(
skill.observations ?? config.observations,
ctx,
);
const actions = new ActionPipeline(skill.actions ?? config.actions, ctx);
session = await ort.InferenceSession.create(bytes, {
executionProviders: ["wasm"],
});
const controller = new OnnxController(ort, session, obs, actions.size);
obs.write();
const smoke = await controller.run();
if (smoke.length !== actions.size || !smoke.every(Number.isFinite))
throw new Error(`ONNX ${skill.id}: standing-pose smoke test failed`);
const policy = new OnnxPolicy();
Object.assign(policy, { ctx, obs, actions, controller });
policy.reset();
return policy;
} catch (error) {
await session?.release();
throw error;
}
}
reset() {
this.ctx.lastAction.fill(0);
this.ctx.reference?.reset();
this.obs.reset();
}
async run() {
this.ctx.reference?.sample(this.ctx.sim.data.time);
this.obs.write();
this.actions.apply(await this.controller.run());
}
dispose() {
return this.controller.dispose();
}
}
+94 -22
View File
@@ -9,9 +9,9 @@ import {
JointPdActuation,
NativeActuation,
} from "../sim/actuation/JointPdActuation.js";
import { ObservationPipeline } from "../policy/ObservationPipeline.js";
import { ActionPipeline } from "../policy/ActionPipeline.js";
import { OnnxController } from "../policy/controllers/OnnxController.js";
import { OnnxPolicy } from "../policy/controllers/OnnxPolicy.js";
import { JointMotionReference } from "../policy/JointMotionReference.js";
import { PolicyStateMachine } from "../skills/PolicyStateMachine.js";
import { SkillManager } from "../skills/SkillManager.js";
import { InputRouter } from "../input/InputRouter.js";
import { RigRenderer } from "../render/RigRenderer.js";
@@ -22,7 +22,8 @@ export class RobotRuntime {
const { pkg, world } = options,
config = pkg.config,
{ mujoco, ort } = await loadRuntimes();
let sim, session, rig, worldPresentation;
let sim, rig, worldPresentation;
const policies = new Map();
try {
sim = await SimCore.load(mujoco, pkg, world);
const primary = config.skills.find((s) => s.kind === "primary");
@@ -47,10 +48,7 @@ export class RobotRuntime {
if ([...defaults.values()].some((v) => !Number.isFinite(v)))
throw new Error("joints.defaults: missing/invalid reference pose");
sim.reset(defaults);
session = await ort.InferenceSession.create(bytes, {
executionProviders: ["wasm"],
});
const ctx = {
const shared = {
sim,
config,
defaults,
@@ -61,13 +59,35 @@ export class RobotRuntime {
names.map((n) => [n, sim.data.qpos[sim.joints.get(n).qpos]]),
),
};
const obs = new ObservationPipeline(config.observations, ctx),
actions = new ActionPipeline(config.actions, ctx);
const controller = new OnnxController(ort, session, obs, actions.size);
obs.write();
const smoke = await controller.run();
if (smoke.length !== actions.size || !smoke.every(Number.isFinite))
throw new Error("ONNX: standing-pose smoke test failed");
for (const skill of config.skills.filter(
(s) =>
["primary", "episodic"].includes(s.kind) && s.available !== false,
)) {
const policyBytes =
skill === primary
? bytes
: await fetchChecked(pkg.asset(skill.controller.policy), "bytes");
const reference = skill.reference
? await JointMotionReference.load(
pkg,
skill.reference,
shared.policyNames,
config.sim.timestep * config.sim.decimation,
)
: null;
policies.set(
skill.id,
await OnnxPolicy.load(
ort,
policyBytes,
config,
shared,
skill,
reference,
),
);
}
const { ctx, obs, actions, controller } = policies.get(primary.id);
rig = new RigRenderer(sim.model, sim.data, { ...config.render, world });
worldPresentation = await options.createWorldPresentation?.({
sim,
@@ -82,13 +102,14 @@ export class RobotRuntime {
obs,
actions,
controller,
policies,
rig,
worldPresentation,
});
} catch (error) {
worldPresentation?.dispose();
rig?.dispose();
await session?.release();
await Promise.allSettled([...policies.values()].map((p) => p.dispose()));
sim?.dispose();
throw error;
}
@@ -106,6 +127,8 @@ export class RobotRuntime {
this.active = false;
this.positions = new Map();
this.skills = new SkillManager(this.config);
this.policyState = new PolicyStateMachine(this.config);
this.activePolicy = this.policyState.primary;
this.actuation =
this.config.actuation.type === "joint_pd"
? new JointPdActuation(
@@ -130,6 +153,8 @@ export class RobotRuntime {
);
else if (action === "chaseToggle") this.restoreCamera();
else if (action.startsWith("toggle:")) this.toggle(action.slice(7));
else if (action.startsWith("skill:"))
this.policyState.request(action.slice(6), this.sim.data.time);
};
this.tickCount = 0;
this.hzAt = performance.now();
@@ -187,12 +212,25 @@ export class RobotRuntime {
}
status() {
return {
policyStatus: this.policyStatus(),
actuationLabel:
this.config.actuation.type === "joint_pd"
? "Simplified actuation · joint PD"
: "",
};
}
policyStatus() {
return this.policyState.episodes.size
? `Skill: ${this.policyState.active} · ${this.policyState.state}`
: "";
}
publishPolicyStatus() {
const policyStatus = this.policyStatus();
if (policyStatus !== this.lastPolicyStatus) {
this.lastPolicyStatus = policyStatus;
this.onStatus({ policyStatus });
}
}
async deactivate() {
this.active = false;
await this.pause();
@@ -223,7 +261,9 @@ export class RobotRuntime {
await this.scheduler.pause();
this.input.clear();
this.ctx.command.fill(0);
this.ctx.lastAction.fill(0);
for (const policy of this.policies.values()) policy.reset();
this.policyState.reset();
this.activePolicy = this.policyState.primary;
this.skills.reset();
this.sim.reset(this.ctx.defaults);
this.odo = 0;
@@ -235,6 +275,7 @@ export class RobotRuntime {
this.ctx.targets.set(name, this.sim.data.qpos[joint.qpos]);
this.fallen = false;
this.onStatus({ fallen: false });
this.publishPolicyStatus();
this.rig.sync();
if (running) this.scheduler.start();
}
@@ -248,10 +289,26 @@ export class RobotRuntime {
}
async controlStep() {
if (!this.fallen) {
const v = this.sim.data.qvel,
a = this.sim.rootDof;
const id = this.policyState.step(
this.sim.data.time,
this.input.command,
Math.hypot(v[a], v[a + 1]),
Math.abs(v[a + 5]),
this.ctx.targets,
);
this.publishPolicyStatus();
const policy = this.policies.get(id);
if (id !== this.activePolicy) {
policy.reset();
this.activePolicy = id;
}
this.ctx.command.set(this.input.command);
this.obs.write();
this.actions.apply(await this.controller.run());
if (this.policyState.state !== "walk") this.ctx.command.fill(0);
await policy.run();
this.skills.update(this.sim.data.time, this.ctx.targets);
this.policyState.blend(this.sim.data.time, this.ctx.targets);
}
for (let i = 0; i < this.config.sim.decimation; i++) {
this.actuation.apply();
@@ -338,11 +395,24 @@ export class RobotRuntime {
scene: this.scene,
world: this.world,
command: this.input.command,
lastAction: this.ctx.lastAction,
get lastAction() {
return self.policies.get(self.activePolicy).ctx.lastAction;
},
get referenceFrame() {
return (
self.policies.get(self.activePolicy).ctx.reference?.frame ?? null
);
},
skills: this.skills,
policyState: this.policyState,
get activePolicy() {
return self.activePolicy;
},
buildObs: () => {
this.ctx.command.set(this.input.command);
return Object.values(this.obs.write())[0];
return Object.values(
this.policies.get(this.activePolicy).obs.write({ advance: false }),
)[0];
},
pause: () => this.pause(),
resume: () => this.resume(),
@@ -377,7 +447,9 @@ export class RobotRuntime {
this.controls?.dispose();
this.worldPresentation?.dispose();
this.rig.dispose();
await this.controller.dispose();
await Promise.allSettled(
[...this.policies.values()].map((p) => p.dispose()),
);
this.sim.dispose();
}
}
+2 -1
View File
@@ -65,7 +65,7 @@ export class RuntimeManager {
const entry = this.entries.find((e) => e.id === id);
if (!entry) throw new Error(`Unknown Package ${id}`);
const pkg = await loadPackage(entry.url),
world = await loadWorld(resolveWorldId(pkg.config));
world = await loadWorld(resolveWorldId(pkg.config), pkg.config);
const factory = this.factories[pkg.config.adapter];
if (!factory)
throw new Error(`Unregistered adapter ${pkg.config.adapter}`);
@@ -111,6 +111,7 @@ export class RuntimeManager {
inputBindings: pkg.config.input.bindings,
runtimeCapabilities: {},
actuationLabel: "",
policyStatus: "",
fallen: false,
...candidate.status?.(),
});
@@ -1,6 +1,17 @@
export class JointPdActuation {
constructor(sim, targets, { kp, kd, torque_limit }) {
constructor(sim, targets, { kp, kd, torque_limit, joints = {} }) {
Object.assign(this, { sim, targets, kp, kd, limit: torque_limit });
this.parameters = new Map(
[...sim.joints.keys()].map((name) => [
name,
{
kp,
kd,
torque_limit,
...joints[name],
},
]),
);
this.pending = new Float64Array(sim.joints.size);
this.clipped = new Uint8Array(sim.joints.size);
this.streaks = new Uint32Array(sim.joints.size);
@@ -22,11 +33,25 @@ export class JointPdActuation {
const target = this.targets.get(name);
if (!Number.isFinite(target))
throw new Error(`actuation.${name}: non-finite target`);
const torque = this.kp * (target - q[j.qpos]) - this.kd * v[j.dof];
const p = this.parameters.get(name);
const torque = p.kp * (target - q[j.qpos]) - p.kd * v[j.dof];
if (!Number.isFinite(torque))
throw new Error(`actuation.${name}: non-finite torque`);
this.clipped[i] = Math.abs(torque) > this.limit ? 1 : 0;
this.pending[i++] = Math.max(-this.limit, Math.min(this.limit, torque));
let lower = -p.torque_limit,
upper = p.torque_limit;
if (p.velocity_limit) {
const saturation =
p.torque_limit / (1 - p.keep_velocity / p.velocity_limit);
const corner = p.velocity_limit * (1 + p.torque_limit / saturation);
const velocity = Math.max(-corner, Math.min(corner, v[j.dof]));
lower = Math.max(
saturation * (-1 - velocity / p.velocity_limit),
lower,
);
upper = Math.min(saturation * (1 - velocity / p.velocity_limit), upper);
}
this.clipped[i] = torque < lower || torque > upper ? 1 : 0;
this.pending[i++] = Math.max(lower, Math.min(upper, torque));
}
i = 0;
for (const j of this.sim.joints.values()) {
@@ -0,0 +1,78 @@
// Full-body policies are exclusive, never overlays. All timing is simulation time.
export class PolicyStateMachine {
constructor(config) {
const primary = config.skills.find((s) => s.kind === "primary");
this.primary = primary.id;
this.owned = new Set(config.joints.groups[primary.owns]);
this.episodes = new Map(
config.skills.filter((s) => s.kind === "episodic").map((s) => [s.id, s]),
);
this.reset();
}
reset() {
this.state = "walk";
this.active = this.primary;
this.pending = null;
this.stillSince = null;
this.from = new Map();
this.episode = null;
this.episodeStart = 0;
this.start = 0;
}
request(id, time) {
if (
!this.episodes.has(id) ||
this.episodes.get(id).available === false ||
this.state !== "walk"
)
return false;
this.pending = id;
this.state = "settling";
this.start = time;
this.stillSince = null;
return true;
}
transition(state, active, time, targets) {
this.state = state;
this.active = active;
this.start = time;
this.from = new Map([...targets].filter(([name]) => this.owned.has(name)));
}
step(time, command, speed, angularSpeed, targets) {
const moving = command.some((v) => Math.abs(v) > 0.01);
if (this.state === "settling") {
if (moving || time - this.start > 5) this.reset();
else if (speed < 0.15 && angularSpeed < 0.2) {
this.stillSince ??= time;
if (time - this.stillSince >= 0.4) {
this.episode = this.episodes.get(this.pending);
this.episodeStart = time;
this.transition("entering", this.pending, time, targets);
}
} else this.stillSince = null;
} else if (["entering", "playing"].includes(this.state)) {
if (moving || time - this.episodeStart >= this.episode.duration - 1e-9)
this.transition("returning", this.primary, time, targets);
else if (
this.state === "entering" &&
time - this.start >= this.episode.blend
)
this.state = "playing";
} else if (
this.state === "returning" &&
time - this.start >= this.episode.blend
)
this.reset();
return this.active;
}
blend(time, targets) {
if (!["entering", "returning"].includes(this.state)) return;
const alpha = Math.min(
1,
Math.max(0, (time - this.start) / this.episode.blend),
);
for (const [name, value] of this.from)
if (targets.has(name))
targets.set(name, value + (targets.get(name) - value) * alpha);
}
}
+21
View File
@@ -2,6 +2,27 @@
export const DEFAULT_WORLD = "arena";
export const resolveWorldId = (config) =>
config.presentation?.world ?? DEFAULT_WORLD;
// Authored World dimensions are Microduck-sized. Resolve once before physics
// compilation so collision boxes and presentation share the same world units.
export function fitWorldToRobot(world, config) {
if (!world.scale_to_robot) return world;
const reference = world.scale_to_robot.reference_height;
const height = config?.dimensions?.height ?? reference;
const scale = height / reference;
if (!Number.isFinite(scale) || scale <= 0)
throw new Error("World scale: invalid robot/reference height");
const result = structuredClone(world);
const factor = scale / (world.scale ?? 1);
for (const key of ["half_extent", "wall_height", "wall_thickness"]) {
result.boundary[key] *= factor;
if (!Number.isFinite(result.boundary[key]) || result.boundary[key] <= 0)
throw new Error(`World scale: invalid boundary.${key}`);
}
if (result.floor.grid) result.floor.grid.size *= factor;
// Runtime-only metadata; robot.json/world.json cannot override this value.
result.scale = scale;
return result;
}
export function arenaWalls({ half_extent, wall_height, wall_thickness }) {
const ht = wall_thickness / 2,
hh = wall_height / 2,
+1 -1
View File
@@ -139,7 +139,7 @@ export async function bootGame({
pkg ??= await loadPackage(
`${import.meta.env.BASE_URL}robots/microduck-legs/robot.json`,
);
world ??= await loadWorld(resolveWorldId(pkg.config));
world ??= await loadWorld(resolveWorldId(pkg.config), pkg.config);
return await boot({
scene,
camera,
+1
View File
@@ -24,6 +24,7 @@ export const useGame = create(
presentationTheme: "comic",
runtimeCapabilities: {},
actuationLabel: '',
policyStatus: '',
robotLicense: "",
fallen: false,
// Adapter-compatible boot diagnostics (no alternate boot screen).
+2 -3
View File
@@ -91,9 +91,8 @@ export default function ControlsHelp() {
type={clickable ? "button" : undefined}
disabled={
clickable
? row.action === "chaseToggle"
? blocked
: disabled
? row.disabled ||
(row.action === "chaseToggle" ? blocked : disabled)
: undefined
}
onClick={
+14 -3
View File
@@ -5,8 +5,16 @@ export default function RuntimeStatus() {
paused = useGame((s) => s.paused),
error = useGame((s) => s.runtimeError),
fallen = useGame((s) => s.fallen),
actuationLabel = useGame((s) => s.actuationLabel);
if (phase === "ready" && !paused && !error && !fallen && !actuationLabel)
actuationLabel = useGame((s) => s.actuationLabel),
policyStatus = useGame((s) => s.policyStatus);
if (
phase === "ready" &&
!paused &&
!error &&
!fallen &&
!actuationLabel &&
!policyStatus
)
return null;
return (
<Box
@@ -47,7 +55,10 @@ export default function RuntimeStatus() {
paused ? (
"Paused · Esc to continue"
) : (
actuationLabel
<>
{actuationLabel}
{policyStatus && <div>{policyStatus}</div>}
</>
)
) : (
"Loading simulation…"