@hackbuild/humanoid 0.0.0-stage → 0.2.0

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/dist/sonic.js ADDED
@@ -0,0 +1,329 @@
1
+ /**
2
+ * GEAR-SONIC, NVIDIA's whole body controller for the Unitree G1, run in the
3
+ * page: an encoder turns a reference motion into a 64 number token, a decoder
4
+ * turns the token and ten ticks of the robot's state into 29 joint actions,
5
+ * 50 times a second; a PD loop here turns actions into motor torques at every
6
+ * MuJoCo step. Written for this library from the published deployment
7
+ * description and parameters (observation names, sizes and order, joint
8
+ * orders, gains from motor armature, action scale, default angles). The
9
+ * details the description leaves open were settled by trial on the deploy
10
+ * model: joint positions relative to the default angles, the reference in
11
+ * absolute angles, histories oldest first, a rotation's first two columns
12
+ * row by row, and the anchor as the base's tilt against an upright reference
13
+ * that follows the robot's heading (measured: only that combination stands).
14
+ * The weights are NVIDIA's, under the NVIDIA Open Model License, and load at
15
+ * run time; onnxruntime-web is an optional peer, passed in or loaded from a URL.
16
+ */
17
+ import { G1 } from "./g1.js";
18
+ import { HumanoidError } from "./runtime.js";
19
+ /** The policy files and their terms. */
20
+ export const SONIC = {
21
+ name: "gear-sonic, the default g1 controller",
22
+ /** Hugging Face revision the URLs pin. */
23
+ revision: "6733128a3d8a523b1418b06bca3cdf61c8b0987f",
24
+ encoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_encoder.onnx",
25
+ decoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_decoder.onnx",
26
+ /** Encoder and decoder together, in bytes (vendor: Hugging Face's sizes). */
27
+ bytes: 50_100_513 + 40_900_688,
28
+ hz: 50,
29
+ 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.",
30
+ };
31
+ /** The G1 model the policy was deployed on: motor actuators, its own joint damping, armature and friction. */
32
+ export const G1_SONIC = {
33
+ name: "unitree g1, 29 joints, the gear-sonic deploy model",
34
+ /** The scene, at GR00T-WholeBodyControl commit 2a5e6a1; it includes the robot file beside it. */
35
+ url: "https://raw.githubusercontent.com/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/scene_29dof.xml",
36
+ /** The meshes are in Git LFS; pass this as `assetBase` to `fetchModel`. */
37
+ assetBase: "https://media.githubusercontent.com/media/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/",
38
+ 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.",
39
+ };
40
+ // motor constants of the deployment parameters: armature (kg m2), effort limit (N m)
41
+ const MOTORS = { m22: [0.025101925, 139], m14: [0.01017752, 88], m5020: [0.003609725, 25], m4010: [0.00425, 5] };
42
+ // each joint's motor, in the model's order (G1.joints)
43
+ const MOTOR_OF = [
44
+ "m22", "m22", "m14", "m22", "m5020", "m5020", "m22", "m22", "m14", "m22", "m5020", "m5020",
45
+ "m14", "m5020", "m5020",
46
+ "m5020", "m5020", "m5020", "m5020", "m5020", "m4010", "m4010",
47
+ "m5020", "m5020", "m5020", "m5020", "m5020", "m4010", "m4010",
48
+ ];
49
+ // ankles and waist roll and pitch run at twice their motor's gains
50
+ const DOUBLED = new Set([4, 5, 10, 11, 13, 14]);
51
+ const OMEGA = 10 * 2 * Math.PI;
52
+ const ZETA = 2;
53
+ /** The deployment's joint tables, each in the model's joint order (`G1.joints`). */
54
+ export const SONIC_JOINTS = {
55
+ /** Standing angles, radians. */
56
+ defaults: [-0.312, 0, 0, 0.669, -0.363, 0, -0.312, 0, 0, 0.669, -0.363, 0, 0, 0, 0, 0.2, 0.2, 0, 0.6, 0, 0, 0, 0.2, -0.2, 0, 0.6, 0, 0, 0],
57
+ /** Position gain, N m per rad: armature times (10 Hz in rad/s) squared (computed). */
58
+ kp: MOTOR_OF.map((m, j) => MOTORS[m][0] * OMEGA * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
59
+ /** Velocity gain, N m s per rad: 2 times damping ratio 2 times armature times omega (computed). */
60
+ kd: MOTOR_OF.map((m, j) => 2 * ZETA * MOTORS[m][0] * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
61
+ /** Torque limit, N m. */
62
+ effort: MOTOR_OF.map((m) => MOTORS[m][1]),
63
+ /** Radians per unit of action: 0.25 times effort over stiffness (computed). */
64
+ scale: MOTOR_OF.map((m) => (0.25 * MOTORS[m][1]) / (MOTORS[m][0] * OMEGA * OMEGA)),
65
+ /** The policy's (IsaacLab) index of each joint. */
66
+ policyIndex: [0, 3, 6, 9, 13, 17, 1, 4, 7, 10, 14, 18, 2, 5, 8, 11, 15, 19, 21, 23, 25, 27, 12, 16, 20, 22, 24, 26, 28],
67
+ };
68
+ /** A model order array (29) in the policy's order. */
69
+ export function toPolicyOrder(v) {
70
+ const out = new Array(29).fill(0);
71
+ for (let j = 0; j < 29; j++)
72
+ out[SONIC_JOINTS.policyIndex[j]] = v[j];
73
+ return out;
74
+ }
75
+ /** Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v. */
76
+ export function intoBody(q, v) {
77
+ const [w, x, y, z] = q;
78
+ const r = [
79
+ [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
80
+ [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
81
+ [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
82
+ ];
83
+ return [0, 1, 2].map((i) => r[0][i] * v[0] + r[1][i] * v[1] + r[2][i] * v[2]);
84
+ }
85
+ /**
86
+ * The anchor observation for an upright reference: the base's tilt with its heading removed (heading is
87
+ * the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to
88
+ * reference, read row by row.
89
+ */
90
+ export function anchorSix(base) {
91
+ const [w, x, y, z] = base;
92
+ const n = Math.max(Math.hypot(w, z), 1e-9);
93
+ const hw = w / n, hz = z / n;
94
+ // base without heading: conj(h) * q; the relative rotation is its conjugate
95
+ const rw = hw * w + hz * z, rx = -(hw * x + hz * y), ry = -(hw * y - hz * x), rz = -(hw * z - hz * w);
96
+ const r00 = 1 - 2 * (ry * ry + rz * rz), r01 = 2 * (rx * ry - rw * rz);
97
+ const r10 = 2 * (rx * ry + rw * rz), r11 = 1 - 2 * (rx * rx + rz * rz);
98
+ const r20 = 2 * (rx * rz - rw * ry), r21 = 2 * (ry * rz + rw * rx);
99
+ return [r00, r01, r10, r11, r20, r21];
100
+ }
101
+ /**
102
+ * The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint
103
+ * angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts
104
+ * stay zero. `ref` holds 10 frames, or 1 repeated.
105
+ */
106
+ export function encoderInput(ref, anchor) {
107
+ const e = new Float32Array(1762);
108
+ const frame = (f) => ref[Math.min(f, ref.length - 1)];
109
+ let o = 4; // mode id 0, three zeros
110
+ for (let f = 0; f < 10; f++)
111
+ for (let k = 0; k < 29; k++)
112
+ e[o++] = frame(f).q[k];
113
+ for (let f = 0; f < 10; f++)
114
+ for (let k = 0; k < 29; k++)
115
+ e[o++] = frame(f).dq?.[k] ?? 0;
116
+ o += 10 + 1 + 6; // root height windows and the single anchor belong to other modes
117
+ for (let f = 0; f < 10; f++)
118
+ for (let k = 0; k < 6; k++)
119
+ e[o++] = anchor[k];
120
+ return e;
121
+ }
122
+ /** Ten ticks of state and actions, oldest first, laid out as the decoder reads them. */
123
+ export class SonicHistory {
124
+ av = [];
125
+ q = [];
126
+ dq = [];
127
+ act = [];
128
+ g = [];
129
+ /** Fills all ten ticks with one state and zero actions. */
130
+ prime(s) {
131
+ for (const k of ["av", "q", "dq", "act", "g"])
132
+ this[k] = [];
133
+ for (let i = 0; i < 10; i++)
134
+ this.add(s, new Array(29).fill(0));
135
+ }
136
+ /** Adds a tick's state, with the actions the last tick produced. */
137
+ add(s, lastAction) {
138
+ const keep = (a, v) => {
139
+ a.push(v);
140
+ if (a.length > 10)
141
+ a.shift();
142
+ };
143
+ keep(this.av, s.angularVelocity);
144
+ keep(this.q, s.q);
145
+ keep(this.dq, s.dq);
146
+ keep(this.act, Array.from(lastAction));
147
+ keep(this.g, s.gravity);
148
+ }
149
+ /** The decoder's 994 inputs: the token, then each history oldest first. */
150
+ decoderInput(token) {
151
+ const d = new Float32Array(994);
152
+ let p = 0;
153
+ for (let k = 0; k < 64; k++)
154
+ d[p++] = token[k];
155
+ for (const h of [this.av, this.q, this.dq, this.act, this.g])
156
+ for (const tick of h)
157
+ for (const v of tick)
158
+ d[p++] = v;
159
+ return d;
160
+ }
161
+ }
162
+ /** Where onnxruntime-web loads from when no module is given. */
163
+ export const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
164
+ async function bytesOf(src, f, progress) {
165
+ if (typeof src !== "string")
166
+ return src instanceof Uint8Array ? src : new Uint8Array(src);
167
+ const r = await f(src);
168
+ if (!r.ok || !r.body)
169
+ throw new HumanoidError(`the policy file ${src} answered ${r.status}.`);
170
+ const reader = r.body.getReader();
171
+ const parts = [];
172
+ let n = 0;
173
+ for (;;) {
174
+ const { done, value } = await reader.read();
175
+ if (done)
176
+ break;
177
+ parts.push(value);
178
+ n += value.byteLength;
179
+ progress(value.byteLength);
180
+ }
181
+ const out = new Uint8Array(n);
182
+ let o = 0;
183
+ for (const p of parts)
184
+ (out.set(p, o), (o += p.byteLength));
185
+ return out;
186
+ }
187
+ /** The loaded policy: an encoder and a decoder session. Drive a G1 with {@link Sonic.drive}. */
188
+ export class Sonic {
189
+ ort;
190
+ encoder;
191
+ decoder;
192
+ constructor(ort, encoder, decoder) {
193
+ this.ort = ort;
194
+ this.encoder = encoder;
195
+ this.decoder = decoder;
196
+ }
197
+ /** Loads onnxruntime-web and both policy files. */
198
+ static async load(o = {}) {
199
+ let ort = o.ort;
200
+ if (!ort) {
201
+ const url = o.ortUrl ?? ORT_URL;
202
+ try {
203
+ ort = (await import(/* @vite-ignore */ url));
204
+ }
205
+ catch (e) {
206
+ throw new HumanoidError(`onnxruntime-web did not load from ${url}: ${e instanceof Error ? e.message : String(e)}.`);
207
+ }
208
+ ort.env.wasm.wasmPaths = new URL("./", url).href;
209
+ }
210
+ ort.env.wasm.numThreads = 1;
211
+ const f = o.fetch ?? globalThis.fetch.bind(globalThis);
212
+ let loaded = 0;
213
+ const tick = (n) => o.onProgress?.((loaded += n), SONIC.bytes);
214
+ const [eb, db] = await Promise.all([bytesOf(o.encoder ?? SONIC.encoder, f, tick), bytesOf(o.decoder ?? SONIC.decoder, f, tick)]);
215
+ const [encoder, decoder] = await Promise.all([ort.InferenceSession.create(eb), ort.InferenceSession.create(db)]);
216
+ o.onLicence?.(SONIC.licence);
217
+ return new Sonic(ort, encoder, decoder);
218
+ }
219
+ /** The decoder's actions (policy order) for one tick. */
220
+ async act(encoderIn, history) {
221
+ const T = this.ort.Tensor;
222
+ const token = (await this.encoder.run({ obs_dict: new T("float32", encoderIn, [1, 1762]) })).encoded_tokens.data;
223
+ return (await this.decoder.run({ obs_dict: new T("float32", history.decoderInput(token), [1, 994]) })).action.data;
224
+ }
225
+ /** A driver for a G1 whose 29 joints are on motor actuators (the {@link G1_SONIC} model). */
226
+ drive(sim) {
227
+ return new SonicDriver(this, sim);
228
+ }
229
+ async dispose() {
230
+ await Promise.all([this.encoder.release?.(), this.decoder.release?.()]);
231
+ }
232
+ }
233
+ /** Runs the policy on one robot: 50 ticks a second, the PD loop at every timestep between. */
234
+ export class SonicDriver {
235
+ sonic;
236
+ sim;
237
+ /** The reference pose the policy tracks, absolute angles in the model's joint order. Default the standing angles. */
238
+ reference = SONIC_JOINTS.defaults.slice();
239
+ /** Milliseconds the last tick's inference took (measured). */
240
+ inferenceMs = 0;
241
+ adr;
242
+ act;
243
+ history = new SonicHistory();
244
+ targets = SONIC_JOINTS.defaults.slice();
245
+ last = new Float32Array(29);
246
+ carry = 0;
247
+ busy = false;
248
+ perTick;
249
+ constructor(sonic, sim) {
250
+ this.sonic = sonic;
251
+ this.sim = sim;
252
+ this.adr = G1.joints.map((j) => {
253
+ const a = sim.address(j);
254
+ if (!a)
255
+ throw new HumanoidError(`the robot has no joint ${j}; the policy drives the unitree g1.`);
256
+ return a;
257
+ });
258
+ this.act = G1.joints.map((j) => {
259
+ const i = sim.actuated.indexOf(j);
260
+ if (i < 0)
261
+ throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
262
+ return i;
263
+ });
264
+ this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
265
+ this.reset();
266
+ }
267
+ /** The robot back at the standing angles, upright at the origin, and the history primed. */
268
+ reset() {
269
+ const { sim } = this;
270
+ sim.reset();
271
+ const d = sim.data;
272
+ d.qpos[2] = 0.79;
273
+ for (let j = 0; j < 29; j++)
274
+ d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
275
+ this.targets = SONIC_JOINTS.defaults.slice();
276
+ this.last.fill(0);
277
+ this.carry = 0;
278
+ this.history.prime(this.state());
279
+ }
280
+ /** The robot's state this tick, in the policy's order. */
281
+ state() {
282
+ const d = this.sim.data;
283
+ const quat = [d.qpos[3], d.qpos[4], d.qpos[5], d.qpos[6]];
284
+ return {
285
+ angularVelocity: [d.qvel[3], d.qvel[4], d.qvel[5]],
286
+ q: toPolicyOrder(this.adr.map((a, j) => d.qpos[a.qpos] - SONIC_JOINTS.defaults[j])),
287
+ dq: toPolicyOrder(this.adr.map((a) => d.qvel[a.qvel])),
288
+ gravity: intoBody(quat, [0, 0, -1]),
289
+ };
290
+ }
291
+ /** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. */
292
+ async tick() {
293
+ const d = this.sim.data;
294
+ const t0 = performance.now();
295
+ this.history.add(this.state(), this.last);
296
+ const anchor = anchorSix([d.qpos[3], d.qpos[4], d.qpos[5], d.qpos[6]]);
297
+ const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
298
+ this.inferenceMs = performance.now() - t0;
299
+ this.last = Float32Array.from(a);
300
+ const pi = SONIC_JOINTS.policyIndex;
301
+ for (let j = 0; j < 29; j++)
302
+ this.targets[j] = SONIC_JOINTS.defaults[j] + a[pi[j]] * SONIC_JOINTS.scale[j];
303
+ const { kp, kd, effort } = SONIC_JOINTS;
304
+ this.sim.run(this.perTick, () => {
305
+ for (let j = 0; j < 29; j++) {
306
+ const tau = kp[j] * (this.targets[j] - d.qpos[this.adr[j].qpos]) - kd[j] * d.qvel[this.adr[j].qvel];
307
+ d.ctrl[this.act[j]] = Math.max(-effort[j], Math.min(effort[j], tau));
308
+ }
309
+ });
310
+ }
311
+ /** Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s a call; a call while one runs does nothing. Returns the ticks run. */
312
+ async advance(seconds) {
313
+ if (this.busy)
314
+ return 0;
315
+ this.busy = true;
316
+ try {
317
+ const per = 1 / SONIC.hz;
318
+ this.carry = Math.min(this.carry + Math.max(0, seconds), 0.1);
319
+ const n = Math.floor(this.carry / per + 1e-6);
320
+ for (let i = 0; i < n; i++)
321
+ await this.tick();
322
+ this.carry = Math.max(0, this.carry - n * per);
323
+ return n;
324
+ }
325
+ finally {
326
+ this.busy = false;
327
+ }
328
+ }
329
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The robot in three.js: one mesh per visible geom (spheres, capsules,
3
+ * cylinders, boxes, ellipsoids, planes and MuJoCo's own meshes, each mesh's
4
+ * geometry shared), coloured from the geom's material or rgba, moved each
5
+ * frame from the geoms' world poses. MuJoCo is z up; the view's root turns
6
+ * that to y up and the robot's forward axis to +Z, the family's humanoid
7
+ * space. Collision geoms (group 3 and up) stay hidden unless asked for.
8
+ */
9
+ import { Group } from "three";
10
+ import type { Humanoid } from "./sim.js";
11
+ /** Options for {@link HumanoidView}. */
12
+ export interface HumanoidViewOptions {
13
+ /** Geom groups to draw. Default 0, 1 and 2, MuJoCo's visible groups. */
14
+ groups?: number[];
15
+ /** Draw plane geoms (the scene's floor). Default false: the page has its own. */
16
+ floor?: boolean;
17
+ /** The axis the robot faces in its model, turned to +Z. Default "x", as MuJoCo Menagerie's humanoids face. */
18
+ forward?: "x" | "-x" | "y" | "-y";
19
+ }
20
+ /** A three.js group that follows a {@link Humanoid}; add `root` to a scene and call `update` after each step. */
21
+ export declare class HumanoidView {
22
+ private sim;
23
+ readonly root: Group<import("three").Object3DEventMap>;
24
+ private inner;
25
+ private meshes;
26
+ private shared;
27
+ private owned;
28
+ constructor(sim: Humanoid, o?: HumanoidViewOptions);
29
+ private geometry;
30
+ /** Moves every mesh to its geom's pose after the last step. */
31
+ update(): void;
32
+ /** Meshes drawn. */
33
+ get count(): number;
34
+ /** Removes the group and frees its geometries and materials. */
35
+ dispose(): void;
36
+ }
package/dist/three.js ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The robot in three.js: one mesh per visible geom (spheres, capsules,
3
+ * cylinders, boxes, ellipsoids, planes and MuJoCo's own meshes, each mesh's
4
+ * geometry shared), coloured from the geom's material or rgba, moved each
5
+ * frame from the geoms' world poses. MuJoCo is z up; the view's root turns
6
+ * that to y up and the robot's forward axis to +Z, the family's humanoid
7
+ * space. Collision geoms (group 3 and up) stay hidden unless asked for.
8
+ */
9
+ import { BoxGeometry, BufferAttribute, BufferGeometry, CapsuleGeometry, CylinderGeometry, Group, Mesh, MeshStandardMaterial, PlaneGeometry, SphereGeometry } from "three";
10
+ const PLANE = 0, SPHERE = 2, CAPSULE = 3, ELLIPSOID = 4, CYLINDER = 5, BOX = 6, MESH = 7;
11
+ const TURN = { x: -Math.PI / 2, "-x": Math.PI / 2, y: Math.PI, "-y": 0 };
12
+ /** A three.js group that follows a {@link Humanoid}; add `root` to a scene and call `update` after each step. */
13
+ export class HumanoidView {
14
+ sim;
15
+ root = new Group();
16
+ inner = new Group();
17
+ meshes = [];
18
+ shared = new Map();
19
+ owned = [];
20
+ constructor(sim, o = {}) {
21
+ this.sim = sim;
22
+ const m = sim.model;
23
+ const groups = new Set(o.groups ?? [0, 1, 2]);
24
+ this.root.name = "humanoid";
25
+ this.root.rotation.y = TURN[o.forward ?? "x"];
26
+ this.inner.rotation.x = -Math.PI / 2;
27
+ this.root.add(this.inner);
28
+ for (let g = 0; g < m.ngeom; g++) {
29
+ const type = m.geom_type[g];
30
+ if (!groups.has(m.geom_group[g]) || (type === PLANE && !o.floor))
31
+ continue;
32
+ const geo = this.geometry(g, type);
33
+ if (!geo)
34
+ continue;
35
+ const mat = m.geom_matid?.[g] ?? -1;
36
+ const rgba = mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : m.geom_rgba.subarray(g * 4, g * 4 + 4);
37
+ const material = new MeshStandardMaterial({ roughness: 0.6, metalness: 0.1, transparent: rgba[3] < 1, opacity: rgba[3] });
38
+ material.color.setRGB(rgba[0], rgba[1], rgba[2]);
39
+ this.owned.push(material);
40
+ const mesh = new Mesh(geo, material);
41
+ mesh.matrixAutoUpdate = false;
42
+ mesh.castShadow = mesh.receiveShadow = type !== PLANE;
43
+ this.inner.add(mesh);
44
+ this.meshes.push({ mesh, geom: g });
45
+ }
46
+ this.update();
47
+ }
48
+ geometry(g, type) {
49
+ const m = this.sim.model;
50
+ const s = m.geom_size.subarray(g * 3, g * 3 + 3);
51
+ const own = (geo) => (this.owned.push(geo), geo);
52
+ switch (type) {
53
+ case SPHERE:
54
+ return own(new SphereGeometry(s[0], 20, 14));
55
+ case ELLIPSOID:
56
+ return own(new SphereGeometry(1, 20, 14).scale(s[0], s[1], s[2]));
57
+ case CAPSULE:
58
+ return own(new CapsuleGeometry(s[0], 2 * s[1], 6, 16).rotateX(Math.PI / 2));
59
+ case CYLINDER:
60
+ return own(new CylinderGeometry(s[0], s[0], 2 * s[1], 20).rotateX(Math.PI / 2));
61
+ case BOX:
62
+ return own(new BoxGeometry(2 * s[0], 2 * s[1], 2 * s[2]));
63
+ case PLANE:
64
+ return own(new PlaneGeometry(s[0] ? 2 * s[0] : 40, s[1] ? 2 * s[1] : 40));
65
+ case MESH: {
66
+ const id = m.geom_dataid[g];
67
+ if (id < 0)
68
+ return null;
69
+ const have = this.shared.get(id);
70
+ if (have)
71
+ return have;
72
+ const v = m.mesh_vertadr[id], nv = m.mesh_vertnum[id], f = m.mesh_faceadr[id], nf = m.mesh_facenum[id];
73
+ const geo = new BufferGeometry();
74
+ geo.setAttribute("position", new BufferAttribute(m.mesh_vert.slice(v * 3, (v + nv) * 3), 3));
75
+ geo.setIndex(new BufferAttribute(Uint32Array.from(m.mesh_face.subarray(f * 3, (f + nf) * 3)), 1));
76
+ geo.computeVertexNormals();
77
+ this.shared.set(id, geo);
78
+ return own(geo);
79
+ }
80
+ default:
81
+ return null;
82
+ }
83
+ }
84
+ /** Moves every mesh to its geom's pose after the last step. */
85
+ update() {
86
+ const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
87
+ for (const { mesh, geom: g } of this.meshes) {
88
+ const a = g * 9, b = g * 3;
89
+ mesh.matrix.set(r[a], r[a + 1], r[a + 2], p[b], r[a + 3], r[a + 4], r[a + 5], p[b + 1], r[a + 6], r[a + 7], r[a + 8], p[b + 2], 0, 0, 0, 1);
90
+ mesh.matrixWorldNeedsUpdate = true;
91
+ }
92
+ }
93
+ /** Meshes drawn. */
94
+ get count() {
95
+ return this.meshes.length;
96
+ }
97
+ /** Removes the group and frees its geometries and materials. */
98
+ dispose() {
99
+ this.root.removeFromParent();
100
+ for (const o of this.owned)
101
+ o.dispose();
102
+ this.meshes = [];
103
+ }
104
+ }
package/how.ts ADDED
@@ -0,0 +1,30 @@
1
+ // how this works: the fold of the package page and of the suite tool. Plain data, no imports;
2
+ // shape in tools/how.d.ts, checked by tsconfig.how.json, shipped in the tarball, never imported
3
+ // by the runtime entry. Text from the README.
4
+ const how: HowDoc = {
5
+ what: "a physics humanoid in the page: mujoco simulates a robot from its mjcf files, holds the joint targets you give its position actuators, and gives the body's pose to a three.js view.",
6
+ how: [
7
+ "mujoco, google deepmind's webassembly build, loads at run time from a factory or a url and is never bundled; it is single threaded, so the page needs no cross-origin isolation.",
8
+ "the robot's mjcf and every file it names (includes, meshes, textures) are read from a url or a dropped folder into mujoco's virtual file system, and the model compiles there.",
9
+ "each frame runs whole timesteps of the model and carries the rest; targets go to the position actuators, a keyframe resets the pose, and the view moves one mesh per visible geom.",
10
+ "nvidia's gear-sonic policy can drive the g1 instead: an encoder and a decoder 50 times a second turn a reference pose and the robot's recent state into joint targets, and a pd loop turns those into motor torques at every step, so it balances and catches a shove.",
11
+ ],
12
+ packages: ["@hackbuild/humanoid"],
13
+ install: "npm install @hackbuild/humanoid",
14
+ today: "git clone https://github.com/hackbuild/hackbuild-motion && cd hackbuild-motion && npm ci && npm run build && npm pack -w @hackbuild/humanoid",
15
+ code: `import { G1, Humanoid, fetchModel, loadMujoco } from "@hackbuild/humanoid";
16
+ import { HumanoidView } from "@hackbuild/humanoid/three";
17
+
18
+ const mj = await loadMujoco();
19
+ const robot = Humanoid.open(mj, await fetchModel(G1.url));
20
+ robot.reset(G1.keyframe);
21
+ const view = new HumanoidView(robot);
22
+ scene.add(view.root);
23
+ // each frame
24
+ robot.step(1 / 60);
25
+ view.update();`,
26
+ lang: "ts",
27
+ links: { page: "https://hackbuild.github.io/hackbuild-motion/humanoid/", source: "https://github.com/hackbuild/hackbuild-motion/tree/main/packages/humanoid" },
28
+ };
29
+
30
+ export default how;