xlerobot-sim / src /robots /generic.js
VectorW's picture
Household tasks in the style of the BEHAVIOR Challenge; walls cut away in the view; fixes
d72771b verified
Raw History Blame Contribute Delete
1.86 kB
// Driver for robots without a dedicated controller (uploaded folders): one target per actuator,
// set from sliders or the JS API, written to data.ctrl every control period.
export class GenericRobot {
constructor(sim, meta) {
this.sim = sim;
this.meta = meta;
const { model } = sim;
// The robot's top-level bodies; the one with the most bodies under it gives the robot's pose.
this.roots = (meta.roots ?? []).map((n) => sim.id("body", n)).filter((id) => id > 0);
const size = (r) => Array.from(model.body_rootid).filter((x) => x === r).length;
this.root = this.roots.slice().sort((a, b) => size(b) - size(a))[0] ?? -1;
this.actuators = Array.from({ length: model.nu }, (_, i) => {
const limited = model.actuator_ctrllimited[i];
const lo = limited ? model.actuator_ctrlrange[2 * i] : -1;
const hi = limited ? model.actuator_ctrlrange[2 * i + 1] : 1;
return { id: i, name: model.actuator(i).name || `actuator ${i}`, range: [lo, hi] };
});
this.targets = new Float64Array(model.nu);
this.home();
}
/** Targets from the model's initial controls (zero, or the middle of a range that excludes zero). */
home() {
for (const a of this.actuators) {
const [lo, hi] = a.range;
this.targets[a.id] = lo <= 0 && hi >= 0 ? 0 : (lo + hi) / 2;
}
this.apply();
}
set(name, value) {
const a = this.actuators.find((x) => x.name === name);
if (!a) throw new Error(`no actuator named ${name}`);
this.targets[a.id] = Math.max(a.range[0], Math.min(a.range[1], value));
}
apply() {
this.sim.data.ctrl.set(this.targets);
}
update() {
this.apply();
}
pose() {
if (this.root < 0) return [0, 0, 0];
const p = this.sim.bodyPos(this.root);
const m = this.sim.bodyMat(this.root);
return [p[0], p[1], Math.atan2(m[3], m[0])];
}
}