Spaces:
Running
Running
File size: 6,524 Bytes
9d9352a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | // LimX Luna (HU_L04) in the browser: the MuJoCo model from luna-description, posed kinematically,
// either by a recorded reference motion or by hand with one slider per joint. Nothing here runs a
// controller or physics.
import loadMujoco from "./vendor/mujoco.js";
const SIGN = new URLSearchParams(location.search).get("__sign");
// The MuJoCo WebAssembly binary is the same file the TRON 2 Space ships, so it is loaded from there
// (Hugging Face serves it with CORS); local test runs use ./vendor.
const WASM_HOME = "https://huggingface.co/spaces/limxdynamics/tron2-teleop/resolve/main/vendor/";
const LOCAL = /^(127\.0\.0\.1|localhost)$/.test(location.hostname);
const vendor = (f) => {
if (f.endsWith(".wasm") && !LOCAL) return WASM_HOME + f;
const u = new URL(`./vendor/${f}`, location.href.split("?")[0]); if (SIGN) u.searchParams.set("__sign", SIGN); return u.href;
};
const local = (f) => { const u = new URL(`./${f}`, location.href.split("?")[0]); if (SIGN) u.searchParams.set("__sign", SIGN); return u.href; };
const HF = "https://huggingface.co/limxdynamics";
const ROBOT = "HU_L04_01";
async function fetchBytes(url, onBytes) {
const r = await fetch(url);
if (!r.ok) throw new Error(`${r.status} ${url}`);
const reader = r.body.getReader(); const parts = []; let got = 0;
for (;;) { const { done, value } = await reader.read(); if (done) break; parts.push(value); got += value.length; onBytes?.(value.length); }
const out = new Uint8Array(got); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; }
return out;
}
// motion.json keeps the motion small and plain text (no Git LFS): see its "encoding" field.
async function decodeMotion({ data, frames, stride }) {
const gz = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
const raw = await new Response(new Blob([gz]).stream().pipeThrough(new DecompressionStream("gzip"))).arrayBuffer();
const d = new Int16Array(raw), out = new Float32Array(frames * stride);
for (let c = 0; c < stride; c++) { let v = 0; for (let f = 0; f < frames; f++) { v += d[c * frames + f]; out[f * stride + c] = v * 1e-4; } }
return out;
}
export class Viewer {
static async create({ base = HF, onProgress } = {}) {
const desc = `${base}/luna-description/resolve/main/HU_L04_description`;
const APPROX_TOTAL = 11e6 + 72e6; let got = 0;
const tick = (n) => { got += n; onProgress?.(Math.min(0.97, got / APPROX_TOTAL)); };
const mjP = loadMujoco({ locateFile: vendor });
// HU_L04_01_vis.xml is the kinematics-only variant of the model (no linkage constraints), meant
// for retargeting and visualization: the joints can be set directly.
const xml = await fetchBytes(`${desc}/xml/${ROBOT}_vis.xml`, tick);
const meshes = [...new Set([...new TextDecoder().decode(xml).matchAll(/file=["']([^"']+)["']/g)].map((m) => m[1]))];
const [mj, motionMeta, ...blobs] = await Promise.all([
mjP, fetchBytes(local("motion.json"), tick).then((b) => JSON.parse(new TextDecoder().decode(b))),
...meshes.map((f) => fetchBytes(`${desc}/meshes/${ROBOT}/${f}`, tick))]);
for (const dir of ["/luna", "/luna/xml", "/luna/meshes", `/luna/meshes/${ROBOT}`]) try { mj.FS.mkdir(dir); } catch { /* exists */ }
// a fixed arena instead of njmax/nconmax, which would not fit in browser memory
mj.FS.writeFile(`/luna/xml/${ROBOT}.xml`, new TextDecoder().decode(xml).replace(/<size\b[^>]*\/>/, '<size memory="16M"/>'));
meshes.forEach((f, i) => mj.FS.writeFile(`/luna/meshes/${ROBOT}/${f}`, blobs[i]));
let model;
try { model = mj.MjModel.from_xml_path(`/luna/xml/${ROBOT}.xml`); }
finally { meshes.forEach((f) => { try { mj.FS.unlink(`/luna/meshes/${ROBOT}/${f}`); } catch { /* */ } }); try { mj.FS.unlink(`/luna/xml/${ROBOT}.xml`); } catch { /* */ } }
onProgress?.(1);
const motion = { ...motionMeta, data: await decodeMotion(motionMeta) };
return new Viewer(mj, model, motion);
}
constructor(mj, model, motion) {
Object.assign(this, { mj, model, motion });
this.data = new mj.MjData(model);
const id = (t, n) => mj.mj_name2id(model, mj.mjtObj[t].value, n);
this.joints = motion.dof_names.map((name) => {
const j = id("mjOBJ_JOINT", name);
return { name, qadr: model.jnt_qposadr[j], lo: model.jnt_range[2 * j], hi: model.jnt_range[2 * j + 1] };
});
this.feet = [];
for (let g = 0; g < model.ngeom; g++) if (model.geom_type[g] === mj.mjtGeom.mjGEOM_BOX.value && /ankle_roll/.test(mj.mj_id2name(model, mj.mjtObj.mjOBJ_BODY.value, model.geom_bodyid[g]) || "")) this.feet.push(g);
this.duration = (motion.frames - 1) / motion.fps;
}
// Pose from the recorded motion at time t (s), interpolated between frames.
setMotionTime(t) {
const { data: D, motion: M } = this, S = M.stride;
const f = Math.max(0, Math.min(M.frames - 1, t * M.fps)), i = Math.floor(f), k = Math.min(M.frames - 1, i + 1), a = f - i;
const A = M.data.subarray(i * S, i * S + S), B = M.data.subarray(k * S, k * S + S);
for (let c = 0; c < 3; c++) D.qpos[c] = A[c] + (B[c] - A[c]) * a;
// normalized lerp of the base quaternion (wxyz), taking the short way round
const s = A[3] * B[3] + A[4] * B[4] + A[5] * B[5] + A[6] * B[6] < 0 ? -1 : 1; let n = 0;
for (let c = 3; c < 7; c++) { D.qpos[c] = A[c] + (s * B[c] - A[c]) * a; n += D.qpos[c] ** 2; }
n = Math.sqrt(n); for (let c = 3; c < 7; c++) D.qpos[c] /= n;
this.joints.forEach((j, q) => { D.qpos[j.qadr] = A[7 + q] + (B[7 + q] - A[7 + q]) * a; });
this.mj.mj_kinematics(this.model, D);
}
// Pose from joint angles (by index into this.joints), the base upright with the feet on the floor.
setJoints(q) {
const { data: D, mj, model } = this;
D.qpos[0] = 0; D.qpos[1] = 0; D.qpos[2] = 1; D.qpos[3] = 1; D.qpos[4] = D.qpos[5] = D.qpos[6] = 0;
this.joints.forEach((j, i) => { D.qpos[j.qadr] = q[i]; });
mj.mj_kinematics(model, D);
D.qpos[2] -= this.footBottom();
mj.mj_kinematics(model, D);
}
footBottom() {
const { model, data: D } = this; let low = Infinity;
for (const g of this.feet) { const R = D.geom_xmat, o = 9 * g; let z = D.geom_xpos[3 * g + 2]; for (let k = 0; k < 3; k++) z -= Math.abs(R[o + 6 + k]) * model.geom_size[3 * g + k]; low = Math.min(low, z); }
return low;
}
basePos() { const q = this.data.qpos; return [q[0], q[1], q[2]]; }
// joint angles of motion frame 0, a natural standing pose to start the sliders from
firstFrame() { return this.joints.map((_, q) => this.motion.data[7 + q]); }
}
|