File size: 4,809 Bytes
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// The simulation core: a compiled MuJoCo model and its data, stepped in fixed control periods.
// It knows nothing about a particular robot; a robot driver (src/robots/) sets data.ctrl each period.
// The same class runs in the browser and in Node (tools/), so both step identical physics.

/** A small seeded random generator (mulberry32), for repeatable scenes. */
export function makeRng(seed) {
  let a = seed >>> 0;
  const next = () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  return {
    next,
    uniform: (lo, hi) => lo + (hi - lo) * next(),
    choice: (items) => items[Math.floor(next() * items.length)],
  };
}

const FREE = 0; // mjJNT_FREE

export class Sim {
  /** `controlHz` sets the control period: the robot driver runs every round(1 / (controlHz * timestep)) steps. */
  constructor(mujoco, model, { controlHz = 50 } = {}) {
    this.mujoco = mujoco;
    this.model = model;
    this.data = new mujoco.MjData(model);
    this.timestep = model.opt.timestep;
    this.substeps = Math.max(1, Math.round(1 / (controlHz * this.timestep)));
    this.controlDt = this.substeps * this.timestep;
    this.steps = 0;
    this.controlled = false;
    this.bodyNames = Array.from({ length: model.nbody }, (_, i) => model.body(i).name);
  }

  dispose() {
    this.data.delete();
    this.model.delete();
  }

  get time() {
    return this.data.time;
  }

  /** The id of a named object, or -1. `type` is "body", "joint", "geom", "site", "actuator"... */
  id(type, name) {
    const key = { body: "mjOBJ_BODY", joint: "mjOBJ_JOINT", geom: "mjOBJ_GEOM", site: "mjOBJ_SITE", actuator: "mjOBJ_ACTUATOR", camera: "mjOBJ_CAMERA", tendon: "mjOBJ_TENDON" }[type];
    return this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj[key].value, name);
  }

  bodyPos(id) {
    const p = this.data.xpos;
    return [p[3 * id], p[3 * id + 1], p[3 * id + 2]];
  }

  /** The body's rotation matrix, row major. */
  bodyMat(id) {
    return Array.from(this.data.xmat.subarray(9 * id, 9 * id + 9));
  }

  /** Bodies on a free joint whose root is not in `excludeRoots`: the objects of the scene. */
  freeBodies(excludeRoots = []) {
    const { model } = this;
    const out = [];
    for (let b = 1; b < model.nbody; b++) {
      const j = model.body_jntadr[b];
      if (j < 0 || model.jnt_type[j] !== FREE || model.body_parentid[b] !== 0) continue;
      if (excludeRoots.includes(b)) continue;
      out.push({ id: b, name: this.bodyNames[b], qpos: model.jnt_qposadr[j], dof: model.jnt_dofadr[j] });
    }
    return out;
  }

  /** One physics step. */
  step() {
    this.mujoco.mj_step(this.model, this.data);
    this.steps++;
    if (this.steps % this.substeps === 0) this.controlled = false;
  }

  /**
   * Up to `n` physics steps; `onControl(dt)` runs at the start of every control period. If it returns
   * false the physics stops there (a policy is still thinking) and the next call asks again.
   * Returns the number of steps taken.
   */
  runSteps(n, onControl) {
    for (let i = 0; i < n; i++) {
      if (onControl && this.steps % this.substeps === 0 && !this.controlled) {
        if (onControl(this.controlDt) === false) return i;
        this.controlled = true;
      }
      this.step();
    }
    return n;
  }

  /** One control period: `onControl(dt)`, then its physics steps. */
  tick(onControl) {
    const toBoundary = (this.substeps - (this.steps % this.substeps)) % this.substeps;
    for (let i = 0; i < toBoundary; i++) this.step();
    if (onControl) onControl(this.controlDt);
    for (let i = 0; i < this.substeps; i++) this.step();
  }

  /** Steps for about `seconds`, running `onControl` every period. */
  run(seconds, onControl) {
    this.runSteps(Math.round(seconds / this.timestep), onControl);
  }

  forward() {
    this.mujoco.mj_forward(this.model, this.data);
  }

  /** The model's initial state; `setup` may change qpos and ctrl before the first forward pass. */
  reset(setup) {
    this.mujoco.mj_resetData(this.model, this.data);
    if (setup) setup(this);
    this.steps = 0;
    this.controlled = false;
    this.forward();
  }

  /** Copy of the state that `restore` puts back. */
  snapshot() {
    const d = this.data;
    return { time: d.time, qpos: Float64Array.from(d.qpos), qvel: Float64Array.from(d.qvel), act: Float64Array.from(d.act), ctrl: Float64Array.from(d.ctrl), steps: this.steps };
  }

  restore(s) {
    const d = this.data;
    d.time = s.time;
    d.qpos.set(s.qpos);
    d.qvel.set(s.qvel);
    d.act.set(s.act);
    d.ctrl.set(s.ctrl);
    d.qacc_warmstart.fill(0);
    d.xfrc_applied.fill(0);
    this.steps = s.steps;
    this.controlled = false;
    this.forward();
  }
}