@hackbuild/humanoid 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -9
- package/dist/files.d.ts +12 -3
- package/dist/files.js +39 -13
- package/dist/humanoid.iife.js +566 -29
- package/dist/runtime.d.ts +10 -0
- package/dist/runtime.js +3 -2
- package/dist/sim.d.ts +13 -2
- package/dist/sim.js +54 -16
- package/dist/single.d.ts +1 -0
- package/dist/single.js +2 -1
- package/dist/sonic.d.ts +178 -0
- package/dist/sonic.js +349 -0
- package/dist/three.d.ts +1 -1
- package/dist/three.js +7 -2
- package/how.ts +1 -0
- package/llms.md +158 -7
- package/package.json +11 -3
package/dist/humanoid.iife.js
CHANGED
|
@@ -30,10 +30,11 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
30
30
|
if (have) return have;
|
|
31
31
|
const p = (async () => {
|
|
32
32
|
let factory = o.factory;
|
|
33
|
-
const url = o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js";
|
|
33
|
+
const url = new URL(o.url ?? "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js", globalThis.location?.href).href;
|
|
34
34
|
if (!factory) try {
|
|
35
35
|
factory = (await import(
|
|
36
36
|
/* @vite-ignore */
|
|
37
|
+
/* webpackIgnore: true */
|
|
37
38
|
url
|
|
38
39
|
)).default;
|
|
39
40
|
} catch (e) {
|
|
@@ -61,10 +62,27 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
61
62
|
* its file, a texture by texturedir and its file. A file that does not
|
|
62
63
|
* arrive is listed in `missing`.
|
|
63
64
|
*/
|
|
64
|
-
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*"([^"]*)"/g)].map((m) => [m[1], m[2]]));
|
|
65
|
-
const
|
|
65
|
+
const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([A-Za-z_]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1], m[2] ?? m[3] ?? ""]));
|
|
66
|
+
const tidy = (path) => {
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const part of path.replace(/\\/g, "/").split("/")) if (part === "..") out.length && out[out.length - 1] !== ".." ? out.pop() : out.push("..");
|
|
69
|
+
else if (part && part !== ".") out.push(part);
|
|
70
|
+
return out.join("/");
|
|
71
|
+
};
|
|
72
|
+
const join = (dir, file) => tidy(dir ? `${dir}/${file}` : file);
|
|
73
|
+
const uncomment = (xml) => xml.replace(/<!--[\s\S]*?-->/g, "");
|
|
74
|
+
const FILE_ATTRS = [
|
|
75
|
+
"file",
|
|
76
|
+
"fileright",
|
|
77
|
+
"fileleft",
|
|
78
|
+
"fileup",
|
|
79
|
+
"filedown",
|
|
80
|
+
"filefront",
|
|
81
|
+
"fileback"
|
|
82
|
+
];
|
|
66
83
|
/** The files one MJCF names, split into includes and the rest, joined onto its compiler's directories. */
|
|
67
|
-
function referencedFiles(
|
|
84
|
+
function referencedFiles(text, dirs = {}) {
|
|
85
|
+
const xml = uncomment(text);
|
|
68
86
|
const d = { ...dirs };
|
|
69
87
|
for (const m of xml.matchAll(/<compiler\b[^>]*>/g)) {
|
|
70
88
|
const a = attrs(m[0]);
|
|
@@ -75,10 +93,9 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
75
93
|
const includes = [...xml.matchAll(/<include\b[^>]*>/g)].map((m) => attrs(m[0]).file).filter((f) => !!f);
|
|
76
94
|
const files = [];
|
|
77
95
|
for (const m of xml.matchAll(/<(mesh|skin|hfield|texture)\b[^>]*>/g)) {
|
|
78
|
-
const
|
|
79
|
-
if (!f) continue;
|
|
96
|
+
const a = attrs(m[0]);
|
|
80
97
|
const dir = m[1] === "texture" ? d.texturedir ?? d.assetdir : d.meshdir ?? d.assetdir;
|
|
81
|
-
files.push(join(dir,
|
|
98
|
+
for (const k of FILE_ATTRS) if (a[k]) files.push(join(dir, a[k]));
|
|
82
99
|
}
|
|
83
100
|
return {
|
|
84
101
|
includes,
|
|
@@ -88,7 +105,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
88
105
|
/** Compiler directories set anywhere in a set of MJCF texts: an included file's compiler applies to the whole model. */
|
|
89
106
|
function dirsOf(xmls) {
|
|
90
107
|
const d = {};
|
|
91
|
-
for (const x of xmls) for (const m of x.matchAll(/<compiler\b[^>]*>/g)) {
|
|
108
|
+
for (const x of xmls) for (const m of uncomment(x).matchAll(/<compiler\b[^>]*>/g)) {
|
|
92
109
|
const a = attrs(m[0]);
|
|
93
110
|
if (a.meshdir !== void 0) d.meshdir = a.meshdir;
|
|
94
111
|
if (a.texturedir !== void 0) d.texturedir = a.texturedir;
|
|
@@ -134,14 +151,19 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
134
151
|
missing
|
|
135
152
|
};
|
|
136
153
|
}
|
|
137
|
-
/**
|
|
154
|
+
/**
|
|
155
|
+
* A robot from the URL of its main MJCF; every file it names is fetched beside it, or for files that
|
|
156
|
+
* are not MJCF beside `assetBase` when given (a repository whose meshes live on another host, such as
|
|
157
|
+
* Git LFS).
|
|
158
|
+
*/
|
|
138
159
|
function fetchModel(url, o = {}) {
|
|
139
160
|
const f = o.fetch ?? globalThis.fetch.bind(globalThis);
|
|
140
161
|
const here = globalThis.location?.href;
|
|
141
162
|
const base = new URL(url, here);
|
|
163
|
+
const assets = o.assetBase ? new URL(o.assetBase.endsWith("/") ? o.assetBase : `${o.assetBase}/`, here) : base;
|
|
142
164
|
const read = async (path) => {
|
|
143
165
|
try {
|
|
144
|
-
const r = await f(path === url ? base.href : new URL(path, base).href);
|
|
166
|
+
const r = await f(path === url ? base.href : new URL(path, /\.xml$/i.test(path) ? base : assets).href);
|
|
145
167
|
return r.ok ? new Uint8Array(await r.arrayBuffer()) : null;
|
|
146
168
|
} catch {
|
|
147
169
|
return null;
|
|
@@ -149,15 +171,19 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
149
171
|
};
|
|
150
172
|
return gather(url, read, o.onFile);
|
|
151
173
|
}
|
|
152
|
-
/**
|
|
174
|
+
/**
|
|
175
|
+
* A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder;
|
|
176
|
+
* loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked. The
|
|
177
|
+
* main MJCF is the one with a worldbody that no other file includes.
|
|
178
|
+
*/
|
|
153
179
|
async function filesFrom(list) {
|
|
154
180
|
const files = /* @__PURE__ */ new Map();
|
|
155
|
-
for (const f of list) files.set((f.webkitRelativePath || f.name)
|
|
181
|
+
for (const f of list) files.set(tidy(f.webkitRelativePath || f.name), f);
|
|
156
182
|
const xmls = [...files.keys()].filter((p) => /\.xml$/i.test(p));
|
|
157
183
|
const texts = /* @__PURE__ */ new Map();
|
|
158
184
|
for (const p of xmls) texts.set(p, await files.get(p).text());
|
|
159
185
|
const included = new Set([...texts].flatMap(([p, t]) => referencedFiles(t).includes.map((i) => join(p.split("/").slice(0, -1).join("/"), i))));
|
|
160
|
-
const main = xmls.filter((p) => !included.has(p) && /<worldbody/.test(texts.get(p))).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length)[0];
|
|
186
|
+
const main = xmls.filter((p) => !included.has(p) && /<worldbody/.test(uncomment(texts.get(p)))).sort((a, b) => a.split("/").length - b.split("/").length || a.length - b.length)[0];
|
|
161
187
|
if (!main) throw new HumanoidError("no mjcf here: drop the robot's folder, with an .xml that has a worldbody.");
|
|
162
188
|
const root = main.split("/").slice(0, -1).join("/");
|
|
163
189
|
const read = async (path) => {
|
|
@@ -168,6 +194,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
168
194
|
}
|
|
169
195
|
// src/sim.ts
|
|
170
196
|
const FREE = 0;
|
|
197
|
+
const JOINT = 0;
|
|
171
198
|
const isArrayLike = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
|
|
172
199
|
/** A robot running in MuJoCo. */
|
|
173
200
|
var Humanoid = class Humanoid {
|
|
@@ -176,7 +203,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
176
203
|
data;
|
|
177
204
|
/** Joint names in model order (a free joint included). */
|
|
178
205
|
joints;
|
|
179
|
-
/** The joint each actuator drives, in actuator order
|
|
206
|
+
/** The joint each actuator drives, in actuator order (`targets[i]` is that joint's target for a position actuator); "" for an actuator on a tendon or a site. */
|
|
180
207
|
actuated;
|
|
181
208
|
bodies;
|
|
182
209
|
keyframes;
|
|
@@ -191,11 +218,18 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
191
218
|
this.mj = mj;
|
|
192
219
|
this.model = model;
|
|
193
220
|
this.data = new mj.MjData(model);
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
221
|
+
const table = new Uint8Array(model.names.buffer, model.names.byteOffset, model.names.length);
|
|
222
|
+
const dec = new TextDecoder();
|
|
223
|
+
const name = (adr, i, kind) => {
|
|
224
|
+
const a = adr[i];
|
|
225
|
+
let e = a;
|
|
226
|
+
while (e < table.length && table[e] !== 0) e++;
|
|
227
|
+
return e > a ? dec.decode(table.subarray(a, e)) : `${kind} ${i}`;
|
|
228
|
+
};
|
|
229
|
+
this.joints = Array.from({ length: model.njnt }, (_, i) => name(model.name_jntadr, i, "joint"));
|
|
230
|
+
this.bodies = Array.from({ length: model.nbody }, (_, i) => name(model.name_bodyadr, i, "body"));
|
|
231
|
+
this.keyframes = Array.from({ length: model.nkey }, (_, i) => name(model.name_keyadr, i, "keyframe"));
|
|
232
|
+
this.actuated = Array.from({ length: model.nu }, (_, i) => model.actuator_trntype[i] === JOINT ? this.joints[model.actuator_trnid[i * 2]] ?? "" : "");
|
|
199
233
|
this.timestep = model.opt.timestep;
|
|
200
234
|
this.missing = missing;
|
|
201
235
|
mj.mj_forward(model, this.data);
|
|
@@ -240,16 +274,18 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
240
274
|
* jump in targets can topple a robot that a ramp of half a second leaves standing (measured on the G1).
|
|
241
275
|
*/
|
|
242
276
|
moveTo(targets, seconds = .5) {
|
|
243
|
-
const
|
|
244
|
-
const to =
|
|
245
|
-
if (isArrayLike(targets)) for (let i = 0; i < Math.min(
|
|
277
|
+
const idx = [];
|
|
278
|
+
const to = [];
|
|
279
|
+
if (isArrayLike(targets)) for (let i = 0; i < Math.min(this.data.ctrl.length, targets.length); i++) idx.push(i), to.push(targets[i]);
|
|
246
280
|
else for (const [name, v] of Object.entries(targets)) {
|
|
247
281
|
const i = this.actuated.indexOf(name);
|
|
248
282
|
if (i < 0) throw new HumanoidError(`no actuator drives ${name}.`);
|
|
249
|
-
|
|
283
|
+
idx.push(i);
|
|
284
|
+
to.push(v);
|
|
250
285
|
}
|
|
251
286
|
this.ramp = {
|
|
252
|
-
|
|
287
|
+
idx,
|
|
288
|
+
from: idx.map((i) => this.data.ctrl[i]),
|
|
253
289
|
to,
|
|
254
290
|
t0: this.data.time,
|
|
255
291
|
dur: Math.max(0, seconds)
|
|
@@ -265,13 +301,15 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
265
301
|
if (!r) return;
|
|
266
302
|
const k = r.dur > 0 ? Math.min(1, (this.data.time - r.t0) / r.dur) : 1;
|
|
267
303
|
const e = k * k * (3 - 2 * k);
|
|
268
|
-
|
|
304
|
+
r.idx.forEach((i, k) => this.data.ctrl[i] = r.from[k] + (r.to[k] - r.from[k]) * e);
|
|
269
305
|
if (k >= 1) this.ramp = null;
|
|
270
306
|
}
|
|
271
|
-
/** Each actuated joint's target set to where the joint is now: the body holds its pose. */
|
|
307
|
+
/** Each actuated joint's target set to where the joint is now: the body holds its pose. Stops a running {@link moveTo}. */
|
|
272
308
|
hold() {
|
|
273
309
|
const { model, data } = this;
|
|
310
|
+
this.ramp = null;
|
|
274
311
|
for (let i = 0; i < model.nu; i++) {
|
|
312
|
+
if (model.actuator_trntype[i] !== JOINT) continue;
|
|
275
313
|
const j = model.actuator_trnid[i * 2];
|
|
276
314
|
data.ctrl[i] = data.qpos[model.jnt_qposadr[j]];
|
|
277
315
|
}
|
|
@@ -279,7 +317,7 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
279
317
|
/** Advances by `seconds` in steps of the model's timestep, carrying the remainder; at most `max` seconds a call (default 0.1). Returns the steps run. */
|
|
280
318
|
step(seconds, max = .1) {
|
|
281
319
|
if (this.gone) return 0;
|
|
282
|
-
this.carry = Math.min(this.carry + Math.max(0, seconds), max);
|
|
320
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), max);
|
|
283
321
|
const n = Math.floor(this.carry / this.timestep + 1e-6);
|
|
284
322
|
for (let i = 0; i < n; i++) {
|
|
285
323
|
this.applyRamp();
|
|
@@ -288,6 +326,31 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
288
326
|
this.carry = Math.max(0, this.carry - n * this.timestep);
|
|
289
327
|
return n;
|
|
290
328
|
}
|
|
329
|
+
/** Runs `n` timesteps, calling `control` before each so a controller can set the actuators every step (a PD loop on motor actuators). */
|
|
330
|
+
run(n, control) {
|
|
331
|
+
if (this.gone) return;
|
|
332
|
+
for (let i = 0; i < n; i++) {
|
|
333
|
+
this.applyRamp();
|
|
334
|
+
control?.(this);
|
|
335
|
+
this.mj.mj_step(this.model, this.data);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/** Recomputes positions and poses from qpos without stepping time: call it after writing qpos by hand. */
|
|
339
|
+
forward() {
|
|
340
|
+
if (!this.gone) this.mj.mj_forward(this.model, this.data);
|
|
341
|
+
}
|
|
342
|
+
/** True once {@link dispose} ran; the data's arrays must not be read after that. */
|
|
343
|
+
get disposed() {
|
|
344
|
+
return this.gone;
|
|
345
|
+
}
|
|
346
|
+
/** Where a hinge or slide joint keeps its position in qpos and its velocity in qvel, or null for a name the model lacks. */
|
|
347
|
+
address(joint) {
|
|
348
|
+
const j = this.joints.indexOf(joint);
|
|
349
|
+
return j < 0 ? null : {
|
|
350
|
+
qpos: this.model.jnt_qposadr[j],
|
|
351
|
+
qvel: this.model.jnt_dofadr[j]
|
|
352
|
+
};
|
|
353
|
+
}
|
|
291
354
|
/** A body's world pose, or null for a name the model lacks. */
|
|
292
355
|
pose(body) {
|
|
293
356
|
const i = typeof body === "number" ? body : this.bodies.indexOf(body);
|
|
@@ -438,7 +501,8 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
438
501
|
const geo = this.geometry(g, type);
|
|
439
502
|
if (!geo) continue;
|
|
440
503
|
const mat = m.geom_matid?.[g] ?? -1;
|
|
441
|
-
const
|
|
504
|
+
const own = m.geom_rgba.subarray(g * 4, g * 4 + 4);
|
|
505
|
+
const rgba = own[0] === .5 && own[1] === .5 && own[2] === .5 && own[3] === 1 && mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : own;
|
|
442
506
|
const material = new three.MeshStandardMaterial({
|
|
443
507
|
roughness: .6,
|
|
444
508
|
metalness: .1,
|
|
@@ -485,8 +549,9 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
485
549
|
default: return null;
|
|
486
550
|
}
|
|
487
551
|
}
|
|
488
|
-
/** Moves every mesh to its geom's pose after the last step. */
|
|
552
|
+
/** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
|
|
489
553
|
update() {
|
|
554
|
+
if (this.sim.disposed) return;
|
|
490
555
|
const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
|
|
491
556
|
for (const { mesh, geom: g } of this.meshes) {
|
|
492
557
|
const a = g * 9, b = g * 3;
|
|
@@ -505,16 +570,488 @@ var HackbuildHumanoid = (function(exports, three) {
|
|
|
505
570
|
this.meshes = [];
|
|
506
571
|
}
|
|
507
572
|
};
|
|
573
|
+
// src/sonic.ts
|
|
574
|
+
/**
|
|
575
|
+
* GEAR-SONIC, NVIDIA's whole body controller for the Unitree G1, run in the
|
|
576
|
+
* page: an encoder turns a reference motion into a 64 number token, a decoder
|
|
577
|
+
* turns the token and ten ticks of the robot's state into 29 joint actions,
|
|
578
|
+
* 50 times a second; a PD loop here turns actions into motor torques at every
|
|
579
|
+
* MuJoCo step. Written for this library from the published deployment
|
|
580
|
+
* description and parameters (observation names, sizes and order, joint
|
|
581
|
+
* orders, gains from motor armature, action scale, default angles). The
|
|
582
|
+
* details the description leaves open were settled by trial on the deploy
|
|
583
|
+
* model: joint positions relative to the default angles, the reference in
|
|
584
|
+
* absolute angles, histories oldest first, a rotation's first two columns
|
|
585
|
+
* row by row, and the anchor as the base's tilt against an upright reference
|
|
586
|
+
* that follows the robot's heading (measured: only that combination stands).
|
|
587
|
+
* The weights are NVIDIA's, under the NVIDIA Open Model License, and load at
|
|
588
|
+
* run time; onnxruntime-web is an optional peer, passed in or loaded from a URL.
|
|
589
|
+
*/
|
|
590
|
+
/** The policy files and their terms. */
|
|
591
|
+
const SONIC = {
|
|
592
|
+
name: "gear-sonic, the default g1 controller",
|
|
593
|
+
/** Hugging Face revision the URLs pin. */
|
|
594
|
+
revision: "6733128a3d8a523b1418b06bca3cdf61c8b0987f",
|
|
595
|
+
encoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_encoder.onnx",
|
|
596
|
+
decoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_decoder.onnx",
|
|
597
|
+
/** Encoder and decoder together, in bytes (vendor: Hugging Face's sizes). */
|
|
598
|
+
bytes: 91001201,
|
|
599
|
+
hz: 50,
|
|
600
|
+
licence: "gear-sonic weights by nvidia. licensed by nvidia corporation under the nvidia open model license (https://huggingface.co/nvidia/GEAR-SONIC/blob/main/LICENSE). they load at run time and are not part of this library."
|
|
601
|
+
};
|
|
602
|
+
/** The G1 model the policy was deployed on: motor actuators, its own joint damping, armature and friction. */
|
|
603
|
+
const G1_SONIC = {
|
|
604
|
+
name: "unitree g1, 29 joints, the gear-sonic deploy model",
|
|
605
|
+
/** The scene, at GR00T-WholeBodyControl commit 2a5e6a1; it includes the robot file beside it. */
|
|
606
|
+
url: "https://raw.githubusercontent.com/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/scene_29dof.xml",
|
|
607
|
+
/** The meshes are in Git LFS; pass this as `assetBase` to `fetchModel`. */
|
|
608
|
+
assetBase: "https://media.githubusercontent.com/media/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/",
|
|
609
|
+
licence: "g1 deploy model from nvidia's gr00t-wholebodycontrol (apache-2.0), meshes copyright unitree robotics (bsd-3-clause). they load at run time and are not part of this library."
|
|
610
|
+
};
|
|
611
|
+
const MOTORS = {
|
|
612
|
+
m22: [.025101925, 139],
|
|
613
|
+
m14: [.01017752, 88],
|
|
614
|
+
m5020: [.003609725, 25],
|
|
615
|
+
m4010: [.00425, 5]
|
|
616
|
+
};
|
|
617
|
+
const MOTOR_OF = [
|
|
618
|
+
"m22",
|
|
619
|
+
"m22",
|
|
620
|
+
"m14",
|
|
621
|
+
"m22",
|
|
622
|
+
"m5020",
|
|
623
|
+
"m5020",
|
|
624
|
+
"m22",
|
|
625
|
+
"m22",
|
|
626
|
+
"m14",
|
|
627
|
+
"m22",
|
|
628
|
+
"m5020",
|
|
629
|
+
"m5020",
|
|
630
|
+
"m14",
|
|
631
|
+
"m5020",
|
|
632
|
+
"m5020",
|
|
633
|
+
"m5020",
|
|
634
|
+
"m5020",
|
|
635
|
+
"m5020",
|
|
636
|
+
"m5020",
|
|
637
|
+
"m5020",
|
|
638
|
+
"m4010",
|
|
639
|
+
"m4010",
|
|
640
|
+
"m5020",
|
|
641
|
+
"m5020",
|
|
642
|
+
"m5020",
|
|
643
|
+
"m5020",
|
|
644
|
+
"m5020",
|
|
645
|
+
"m4010",
|
|
646
|
+
"m4010"
|
|
647
|
+
];
|
|
648
|
+
const DOUBLED = /* @__PURE__ */ new Set([
|
|
649
|
+
4,
|
|
650
|
+
5,
|
|
651
|
+
10,
|
|
652
|
+
11,
|
|
653
|
+
13,
|
|
654
|
+
14
|
|
655
|
+
]);
|
|
656
|
+
const OMEGA = 20 * Math.PI;
|
|
657
|
+
/** The deployment's joint tables, each in the model's joint order (`G1.joints`). */
|
|
658
|
+
const SONIC_JOINTS = {
|
|
659
|
+
/** Standing angles, radians. */
|
|
660
|
+
defaults: [
|
|
661
|
+
-.312,
|
|
662
|
+
0,
|
|
663
|
+
0,
|
|
664
|
+
.669,
|
|
665
|
+
-.363,
|
|
666
|
+
0,
|
|
667
|
+
-.312,
|
|
668
|
+
0,
|
|
669
|
+
0,
|
|
670
|
+
.669,
|
|
671
|
+
-.363,
|
|
672
|
+
0,
|
|
673
|
+
0,
|
|
674
|
+
0,
|
|
675
|
+
0,
|
|
676
|
+
.2,
|
|
677
|
+
.2,
|
|
678
|
+
0,
|
|
679
|
+
.6,
|
|
680
|
+
0,
|
|
681
|
+
0,
|
|
682
|
+
0,
|
|
683
|
+
.2,
|
|
684
|
+
-.2,
|
|
685
|
+
0,
|
|
686
|
+
.6,
|
|
687
|
+
0,
|
|
688
|
+
0,
|
|
689
|
+
0
|
|
690
|
+
],
|
|
691
|
+
/** Position gain, N m per rad: armature times (10 Hz in rad/s) squared (computed). */
|
|
692
|
+
kp: MOTOR_OF.map((m, j) => MOTORS[m][0] * OMEGA * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
|
|
693
|
+
/** Velocity gain, N m s per rad: 2 times damping ratio 2 times armature times omega (computed). */
|
|
694
|
+
kd: MOTOR_OF.map((m, j) => 4 * MOTORS[m][0] * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
|
|
695
|
+
/** Torque limit, N m. */
|
|
696
|
+
effort: MOTOR_OF.map((m) => MOTORS[m][1]),
|
|
697
|
+
/** Radians per unit of action: 0.25 times effort over stiffness (computed). */
|
|
698
|
+
scale: MOTOR_OF.map((m) => .25 * MOTORS[m][1] / (MOTORS[m][0] * OMEGA * OMEGA)),
|
|
699
|
+
/** The policy's (IsaacLab) index of each joint. */
|
|
700
|
+
policyIndex: [
|
|
701
|
+
0,
|
|
702
|
+
3,
|
|
703
|
+
6,
|
|
704
|
+
9,
|
|
705
|
+
13,
|
|
706
|
+
17,
|
|
707
|
+
1,
|
|
708
|
+
4,
|
|
709
|
+
7,
|
|
710
|
+
10,
|
|
711
|
+
14,
|
|
712
|
+
18,
|
|
713
|
+
2,
|
|
714
|
+
5,
|
|
715
|
+
8,
|
|
716
|
+
11,
|
|
717
|
+
15,
|
|
718
|
+
19,
|
|
719
|
+
21,
|
|
720
|
+
23,
|
|
721
|
+
25,
|
|
722
|
+
27,
|
|
723
|
+
12,
|
|
724
|
+
16,
|
|
725
|
+
20,
|
|
726
|
+
22,
|
|
727
|
+
24,
|
|
728
|
+
26,
|
|
729
|
+
28
|
|
730
|
+
]
|
|
731
|
+
};
|
|
732
|
+
/** A model order array (29) in the policy's order. */
|
|
733
|
+
function toPolicyOrder(v) {
|
|
734
|
+
const out = new Array(29).fill(0);
|
|
735
|
+
for (let j = 0; j < 29; j++) out[SONIC_JOINTS.policyIndex[j]] = v[j];
|
|
736
|
+
return out;
|
|
737
|
+
}
|
|
738
|
+
/** Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v. */
|
|
739
|
+
function intoBody(q, v) {
|
|
740
|
+
const [w, x, y, z] = q;
|
|
741
|
+
const r = [
|
|
742
|
+
[
|
|
743
|
+
1 - 2 * (y * y + z * z),
|
|
744
|
+
2 * (x * y - w * z),
|
|
745
|
+
2 * (x * z + w * y)
|
|
746
|
+
],
|
|
747
|
+
[
|
|
748
|
+
2 * (x * y + w * z),
|
|
749
|
+
1 - 2 * (x * x + z * z),
|
|
750
|
+
2 * (y * z - w * x)
|
|
751
|
+
],
|
|
752
|
+
[
|
|
753
|
+
2 * (x * z - w * y),
|
|
754
|
+
2 * (y * z + w * x),
|
|
755
|
+
1 - 2 * (x * x + y * y)
|
|
756
|
+
]
|
|
757
|
+
];
|
|
758
|
+
return [
|
|
759
|
+
0,
|
|
760
|
+
1,
|
|
761
|
+
2
|
|
762
|
+
].map((i) => r[0][i] * v[0] + r[1][i] * v[1] + r[2][i] * v[2]);
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* The anchor observation for an upright reference: the base's tilt with its heading removed (heading is
|
|
766
|
+
* the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to
|
|
767
|
+
* reference, read row by row.
|
|
768
|
+
*/
|
|
769
|
+
function anchorSix(base) {
|
|
770
|
+
const [w, x, y, z] = base;
|
|
771
|
+
const n = Math.max(Math.hypot(w, z), 1e-9);
|
|
772
|
+
const hw = w / n, hz = z / n;
|
|
773
|
+
const rw = hw * w + hz * z, rx = -(hw * x + hz * y), ry = -(hw * y - hz * x), rz = -(hw * z - hz * w);
|
|
774
|
+
return [
|
|
775
|
+
1 - 2 * (ry * ry + rz * rz),
|
|
776
|
+
2 * (rx * ry - rw * rz),
|
|
777
|
+
2 * (rx * ry + rw * rz),
|
|
778
|
+
1 - 2 * (rx * rx + rz * rz),
|
|
779
|
+
2 * (rx * rz - rw * ry),
|
|
780
|
+
2 * (ry * rz + rw * rx)
|
|
781
|
+
];
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint
|
|
785
|
+
* angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts
|
|
786
|
+
* stay zero. `ref` holds 10 frames, or 1 repeated.
|
|
787
|
+
*/
|
|
788
|
+
function encoderInput(ref, anchor) {
|
|
789
|
+
const e = /* @__PURE__ */ new Float32Array(1762);
|
|
790
|
+
const frame = (f) => ref[Math.min(f, ref.length - 1)];
|
|
791
|
+
let o = 4;
|
|
792
|
+
for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).q[k];
|
|
793
|
+
for (let f = 0; f < 10; f++) for (let k = 0; k < 29; k++) e[o++] = frame(f).dq?.[k] ?? 0;
|
|
794
|
+
o += 17;
|
|
795
|
+
for (let f = 0; f < 10; f++) for (let k = 0; k < 6; k++) e[o++] = anchor[k];
|
|
796
|
+
return e;
|
|
797
|
+
}
|
|
798
|
+
/** Ten ticks of state and actions, oldest first, laid out as the decoder reads them. */
|
|
799
|
+
var SonicHistory = class {
|
|
800
|
+
av = [];
|
|
801
|
+
q = [];
|
|
802
|
+
dq = [];
|
|
803
|
+
act = [];
|
|
804
|
+
g = [];
|
|
805
|
+
/** Fills all ten ticks with one state and zero actions. */
|
|
806
|
+
prime(s) {
|
|
807
|
+
for (const k of [
|
|
808
|
+
"av",
|
|
809
|
+
"q",
|
|
810
|
+
"dq",
|
|
811
|
+
"act",
|
|
812
|
+
"g"
|
|
813
|
+
]) this[k] = [];
|
|
814
|
+
for (let i = 0; i < 10; i++) this.add(s, new Array(29).fill(0));
|
|
815
|
+
}
|
|
816
|
+
/** Adds a tick's state, with the actions the last tick produced. */
|
|
817
|
+
add(s, lastAction) {
|
|
818
|
+
const keep = (a, v) => {
|
|
819
|
+
a.push(v);
|
|
820
|
+
if (a.length > 10) a.shift();
|
|
821
|
+
};
|
|
822
|
+
keep(this.av, s.angularVelocity);
|
|
823
|
+
keep(this.q, s.q);
|
|
824
|
+
keep(this.dq, s.dq);
|
|
825
|
+
keep(this.act, Array.from(lastAction));
|
|
826
|
+
keep(this.g, s.gravity);
|
|
827
|
+
}
|
|
828
|
+
/** The decoder's 994 inputs: the token, then each history oldest first. */
|
|
829
|
+
decoderInput(token) {
|
|
830
|
+
const d = /* @__PURE__ */ new Float32Array(994);
|
|
831
|
+
let p = 0;
|
|
832
|
+
for (let k = 0; k < 64; k++) d[p++] = token[k];
|
|
833
|
+
for (const h of [
|
|
834
|
+
this.av,
|
|
835
|
+
this.q,
|
|
836
|
+
this.dq,
|
|
837
|
+
this.act,
|
|
838
|
+
this.g
|
|
839
|
+
]) for (const tick of h) for (const v of tick) d[p++] = v;
|
|
840
|
+
return d;
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
/** Where onnxruntime-web loads from when no module is given. */
|
|
844
|
+
const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
|
|
845
|
+
async function bytesOf(src, f, progress) {
|
|
846
|
+
if (typeof src !== "string") return src instanceof Uint8Array ? src : new Uint8Array(src);
|
|
847
|
+
const r = await f(src);
|
|
848
|
+
if (!r.ok || !r.body) throw new HumanoidError(`the policy file ${src} answered ${r.status}.`);
|
|
849
|
+
const reader = r.body.getReader();
|
|
850
|
+
const parts = [];
|
|
851
|
+
let n = 0;
|
|
852
|
+
for (;;) {
|
|
853
|
+
const { done, value } = await reader.read();
|
|
854
|
+
if (done) break;
|
|
855
|
+
parts.push(value);
|
|
856
|
+
n += value.byteLength;
|
|
857
|
+
progress(value.byteLength);
|
|
858
|
+
}
|
|
859
|
+
const out = new Uint8Array(n);
|
|
860
|
+
let o = 0;
|
|
861
|
+
for (const p of parts) out.set(p, o), o += p.byteLength;
|
|
862
|
+
return out;
|
|
863
|
+
}
|
|
864
|
+
/** The loaded policy: an encoder and a decoder session. Drive a G1 with {@link Sonic.drive}. */
|
|
865
|
+
var Sonic = class Sonic {
|
|
866
|
+
ort;
|
|
867
|
+
encoder;
|
|
868
|
+
decoder;
|
|
869
|
+
constructor(ort, encoder, decoder) {
|
|
870
|
+
this.ort = ort;
|
|
871
|
+
this.encoder = encoder;
|
|
872
|
+
this.decoder = decoder;
|
|
873
|
+
}
|
|
874
|
+
/** Loads onnxruntime-web and both policy files. */
|
|
875
|
+
static async load(o = {}) {
|
|
876
|
+
let ort = o.ort;
|
|
877
|
+
if (!ort) {
|
|
878
|
+
const url = new URL(o.ortUrl ?? "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs", globalThis.location?.href).href;
|
|
879
|
+
try {
|
|
880
|
+
ort = await import(
|
|
881
|
+
/* @vite-ignore */
|
|
882
|
+
/* webpackIgnore: true */
|
|
883
|
+
url
|
|
884
|
+
);
|
|
885
|
+
} catch (e) {
|
|
886
|
+
throw new HumanoidError(`onnxruntime-web did not load from ${url}: ${e instanceof Error ? e.message : String(e)}.`);
|
|
887
|
+
}
|
|
888
|
+
ort.env.wasm.wasmPaths = new URL("./", url).href;
|
|
889
|
+
}
|
|
890
|
+
ort.env.wasm.numThreads = 1;
|
|
891
|
+
const f = o.fetch ?? globalThis.fetch.bind(globalThis);
|
|
892
|
+
let loaded = 0;
|
|
893
|
+
const tick = (n) => o.onProgress?.(loaded += n, SONIC.bytes);
|
|
894
|
+
const [eb, db] = await Promise.all([bytesOf(o.encoder ?? SONIC.encoder, f, tick), bytesOf(o.decoder ?? SONIC.decoder, f, tick)]);
|
|
895
|
+
const [encoder, decoder] = await Promise.all([ort.InferenceSession.create(eb), ort.InferenceSession.create(db)]);
|
|
896
|
+
o.onLicence?.(SONIC.licence);
|
|
897
|
+
return new Sonic(ort, encoder, decoder);
|
|
898
|
+
}
|
|
899
|
+
/** The decoder's actions (policy order) for one tick. */
|
|
900
|
+
async act(encoderIn, history) {
|
|
901
|
+
const T = this.ort.Tensor;
|
|
902
|
+
const token = (await this.encoder.run({ obs_dict: new T("float32", encoderIn, [1, 1762]) })).encoded_tokens.data;
|
|
903
|
+
return (await this.decoder.run({ obs_dict: new T("float32", history.decoderInput(token), [1, 994]) })).action.data;
|
|
904
|
+
}
|
|
905
|
+
/** A driver for a G1 whose 29 joints are on motor actuators (the {@link G1_SONIC} model). */
|
|
906
|
+
drive(sim) {
|
|
907
|
+
return new SonicDriver(this, sim);
|
|
908
|
+
}
|
|
909
|
+
async dispose() {
|
|
910
|
+
await Promise.all([this.encoder.release?.(), this.decoder.release?.()]);
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
/** Runs the policy on one robot: 50 ticks a second, the PD loop at every timestep between. */
|
|
914
|
+
var SonicDriver = class {
|
|
915
|
+
sonic;
|
|
916
|
+
sim;
|
|
917
|
+
/** The reference pose the policy tracks, absolute angles in the model's joint order. Default the standing angles. */
|
|
918
|
+
reference = SONIC_JOINTS.defaults.slice();
|
|
919
|
+
/** Milliseconds the last tick's inference took (measured). */
|
|
920
|
+
inferenceMs = 0;
|
|
921
|
+
adr;
|
|
922
|
+
act;
|
|
923
|
+
history = new SonicHistory();
|
|
924
|
+
targets = SONIC_JOINTS.defaults.slice();
|
|
925
|
+
last = /* @__PURE__ */ new Float32Array(29);
|
|
926
|
+
carry = 0;
|
|
927
|
+
busy = false;
|
|
928
|
+
perTick;
|
|
929
|
+
/** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
|
|
930
|
+
generation = 0;
|
|
931
|
+
constructor(sonic, sim) {
|
|
932
|
+
this.sonic = sonic;
|
|
933
|
+
this.sim = sim;
|
|
934
|
+
this.adr = G1.joints.map((j) => {
|
|
935
|
+
const a = sim.address(j);
|
|
936
|
+
if (!a) throw new HumanoidError(`the robot has no joint ${j}; the policy drives the unitree g1.`);
|
|
937
|
+
return a;
|
|
938
|
+
});
|
|
939
|
+
this.act = G1.joints.map((j) => {
|
|
940
|
+
const i = sim.actuated.indexOf(j);
|
|
941
|
+
if (i < 0) throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
942
|
+
if (sim.model.actuator_biastype[i] !== 0) throw new HumanoidError(`${j} is on a servo actuator, not a motor; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
|
|
943
|
+
return i;
|
|
944
|
+
});
|
|
945
|
+
this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
|
|
946
|
+
this.reset();
|
|
947
|
+
}
|
|
948
|
+
/** The robot back at the standing angles, upright at the origin, and the history primed. */
|
|
949
|
+
reset() {
|
|
950
|
+
const { sim } = this;
|
|
951
|
+
if (sim.disposed) return;
|
|
952
|
+
this.generation++;
|
|
953
|
+
sim.reset();
|
|
954
|
+
const d = sim.data;
|
|
955
|
+
d.qpos[2] = .79;
|
|
956
|
+
for (let j = 0; j < 29; j++) d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
|
|
957
|
+
sim.forward();
|
|
958
|
+
this.targets = SONIC_JOINTS.defaults.slice();
|
|
959
|
+
this.last.fill(0);
|
|
960
|
+
this.carry = 0;
|
|
961
|
+
this.history.prime(this.state());
|
|
962
|
+
}
|
|
963
|
+
/** The robot's state this tick, in the policy's order. */
|
|
964
|
+
state() {
|
|
965
|
+
const d = this.sim.data;
|
|
966
|
+
const quat = [
|
|
967
|
+
d.qpos[3],
|
|
968
|
+
d.qpos[4],
|
|
969
|
+
d.qpos[5],
|
|
970
|
+
d.qpos[6]
|
|
971
|
+
];
|
|
972
|
+
return {
|
|
973
|
+
angularVelocity: [
|
|
974
|
+
d.qvel[3],
|
|
975
|
+
d.qvel[4],
|
|
976
|
+
d.qvel[5]
|
|
977
|
+
],
|
|
978
|
+
q: toPolicyOrder(this.adr.map((a, j) => d.qpos[a.qpos] - SONIC_JOINTS.defaults[j])),
|
|
979
|
+
dq: toPolicyOrder(this.adr.map((a) => d.qvel[a.qvel])),
|
|
980
|
+
gravity: intoBody(quat, [
|
|
981
|
+
0,
|
|
982
|
+
0,
|
|
983
|
+
-1
|
|
984
|
+
])
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
/** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. A tick that a reset or dispose overtakes does nothing more. */
|
|
988
|
+
async tick() {
|
|
989
|
+
if (this.sim.disposed) return;
|
|
990
|
+
const d = this.sim.data;
|
|
991
|
+
const gen = this.generation;
|
|
992
|
+
const t0 = performance.now();
|
|
993
|
+
this.history.add(this.state(), this.last);
|
|
994
|
+
const anchor = anchorSix([
|
|
995
|
+
d.qpos[3],
|
|
996
|
+
d.qpos[4],
|
|
997
|
+
d.qpos[5],
|
|
998
|
+
d.qpos[6]
|
|
999
|
+
]);
|
|
1000
|
+
const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
|
|
1001
|
+
if (gen !== this.generation || this.sim.disposed) return;
|
|
1002
|
+
this.inferenceMs = performance.now() - t0;
|
|
1003
|
+
this.last = Float32Array.from(a);
|
|
1004
|
+
const pi = SONIC_JOINTS.policyIndex;
|
|
1005
|
+
for (let j = 0; j < 29; j++) this.targets[j] = SONIC_JOINTS.defaults[j] + a[pi[j]] * SONIC_JOINTS.scale[j];
|
|
1006
|
+
const { kp, kd, effort } = SONIC_JOINTS;
|
|
1007
|
+
this.sim.run(this.perTick, () => {
|
|
1008
|
+
for (let j = 0; j < 29; j++) {
|
|
1009
|
+
const tau = kp[j] * (this.targets[j] - d.qpos[this.adr[j].qpos]) - kd[j] * d.qvel[this.adr[j].qvel];
|
|
1010
|
+
d.ctrl[this.act[j]] = Math.max(-effort[j], Math.min(effort[j], tau));
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
|
|
1016
|
+
* runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
|
|
1017
|
+
*/
|
|
1018
|
+
async advance(seconds) {
|
|
1019
|
+
if (this.sim.disposed) return 0;
|
|
1020
|
+
const per = 1 / SONIC.hz;
|
|
1021
|
+
this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), .1);
|
|
1022
|
+
if (this.busy) return 0;
|
|
1023
|
+
this.busy = true;
|
|
1024
|
+
try {
|
|
1025
|
+
const n = Math.floor(this.carry / per + 1e-6);
|
|
1026
|
+
for (let i = 0; i < n; i++) await this.tick();
|
|
1027
|
+
this.carry = Math.max(0, this.carry - n * per);
|
|
1028
|
+
return n;
|
|
1029
|
+
} finally {
|
|
1030
|
+
this.busy = false;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
508
1034
|
exports.G1 = G1;
|
|
1035
|
+
exports.G1_SONIC = G1_SONIC;
|
|
509
1036
|
exports.Humanoid = Humanoid;
|
|
510
1037
|
exports.HumanoidError = HumanoidError;
|
|
511
1038
|
exports.HumanoidView = HumanoidView;
|
|
512
1039
|
exports.MUJOCO_LICENCE = MUJOCO_LICENCE;
|
|
513
1040
|
exports.MUJOCO_URL = MUJOCO_URL;
|
|
514
1041
|
exports.MUJOCO_VERSION = MUJOCO_VERSION;
|
|
1042
|
+
exports.ORT_URL = ORT_URL;
|
|
1043
|
+
exports.SONIC = SONIC;
|
|
1044
|
+
exports.SONIC_JOINTS = SONIC_JOINTS;
|
|
1045
|
+
exports.Sonic = Sonic;
|
|
1046
|
+
exports.SonicDriver = SonicDriver;
|
|
1047
|
+
exports.SonicHistory = SonicHistory;
|
|
1048
|
+
exports.anchorSix = anchorSix;
|
|
1049
|
+
exports.encoderInput = encoderInput;
|
|
515
1050
|
exports.fetchModel = fetchModel;
|
|
516
1051
|
exports.filesFrom = filesFrom;
|
|
1052
|
+
exports.intoBody = intoBody;
|
|
517
1053
|
exports.loadMujoco = loadMujoco;
|
|
518
1054
|
exports.referencedFiles = referencedFiles;
|
|
1055
|
+
exports.toPolicyOrder = toPolicyOrder;
|
|
519
1056
|
return exports;
|
|
520
1057
|
})({}, THREE);
|