aboutsummaryrefslogtreecommitdiff
path: root/mujoco/src/simulate.c
blob: c88e83a2f98f9bbad6bd8365e3f7df6a148ee0f2 (plain)
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// simulate.c --- run mujoco simulation with serial control
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <GLFW/glfw3.h>
#include <mujoco/mujoco.h>

#define BAUDRATE B115200
#define STEPS_TO_RADIANS (2*M_PI/360)

enum {
  SERVO_LEFT,
  SERVO_RIGHT,
  SERVO_UPPER,
  SERVO_COUNT
};

uint8_t servo_left_handed = 1 << SERVO_LEFT | 1 << SERVO_RIGHT;

int    servo_ids[SERVO_COUNT];
int shoulder_ids[SERVO_COUNT];

const char *progname;
const char *modelfile;
const char *serialdev;

int16_t steps[8] = {0};
uint8_t ends = 0;
uint32_t crc;
char read_buf[sizeof (steps) + sizeof (crc)];
char write_buf[sizeof (ends) + sizeof (crc)];
volatile bool serial_read_ready = false;
struct termios oldtio;

// MuJoCo data structures
mjModel   *m = NULL;            // MuJoCo model
mjData    *d = NULL;            // MuJoCo data
mjvCamera  cam;                 // abstract camera
mjvOption  opt;                 // visualization options
mjvScene   scn;                 // abstract scene
mjrContext con;                 // custom GPU context

// mouse interaction
bool   button_left   = false;
bool   button_middle = false;
bool   button_right  = false;
double lastx         = 0;
double lasty         = 0;

static void
signal_handler_io (int status)
{
  // printf ("received SIGIO\n");
  serial_read_ready = true;
}

static int
open_serial (const char *dev)
{
  int fd;
  for (;;) {
    fd = open (dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd != -1) break;
    printf ("Error %i from open: %s\n", errno, strerror (errno));
    sleep (1);
  }

  struct sigaction saio = {0};
  saio.sa_handler = signal_handler_io;
  // saio.sa_flags = SA_RESTART;
  sigaction (SIGIO, &saio, NULL);

  fcntl (fd, F_SETOWN, getpid ()); // allow the process to receive SIGIO
  fcntl (fd, F_SETFL, FASYNC); // make the file descriptor asynchronous

  struct termios newtio = {0};
  if (tcgetattr (fd, &oldtio) != 0) {
    printf ("Error %i from tcgetattr: %s\n", errno, strerror (errno));
    exit (EXIT_FAILURE);
  }

  newtio.c_iflag = IGNPAR;
  newtio.c_cflag = CS8 | CLOCAL | CREAD;
  newtio.c_cc[VMIN ] = 0;
  newtio.c_cc[VTIME] = 0;
  cfsetspeed (&newtio, BAUDRATE);

  // tcflush (fd, TCIFLUSH);
  // if (tcsetattr (fd, TCSANOW, &newtio) != 0) {
  if (tcsetattr (fd, TCSAFLUSH, &newtio) != 0) {
    printf ("Error %i from tcsetattr: %s\n", errno, strerror (errno));
  }

  return fd;
}

static uint32_t
crc32 (uint32_t *data, size_t len)
{
  uint32_t crc  = 0xffffffff;

  for (size_t i = 0; i < len; ++i) {
    crc ^= data[i];

    for (int j = 0; j < 32; ++j) {
      crc = crc & 1 << 31 ? crc << 1 ^ 0x04c11db7
                          : crc << 1;
    }
  }

  return crc;
}

void
model_load (void)
{
  char error[1000] = "Could not load binary model";
  if (strlen (modelfile) > 4 &&
      !strcmp (modelfile + strlen (modelfile) - 4, ".mjb")) {
    m = mj_loadModel (modelfile, 0);
  } else {
    m = mj_loadXML (modelfile, 0, error, 1000);
  }

  if (!m) mju_error ("Load model error: %s", error);
}

void
keyboard (GLFWwindow *window, int key, int scancode, int act, int mods)
{
  // Backspace: reset simulation
  if (act == GLFW_PRESS && key == GLFW_KEY_BACKSPACE) {
    mj_resetData (m, d);
    mj_forward (m, d);
  }

  // F5: reload
  if (act == GLFW_PRESS && key == GLFW_KEY_F5) {
    model_load ();
  }
}

void
mouse_button (GLFWwindow *window, int button, int act, int mods)
{
  button_left   = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_LEFT  ) == GLFW_PRESS;
  button_middle = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS;
  button_right  = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS;

  // update mouse position
  glfwGetCursorPos (window, &lastx, &lasty);
}


// mouse move callback
void
mouse_move (GLFWwindow *window, double xpos, double ypos)
{
  // no buttons down: nothing to do
  if (!button_left && !button_middle && !button_right) return;

  // compute mouse displacement, save
  double dx = xpos - lastx;
  double dy = ypos - lasty;
  lastx = xpos;
  lasty = ypos;

  // get current window size
  int width, height;
  glfwGetWindowSize (window, &width, &height);

  // get shift key state
  bool mod_shift = (glfwGetKey (window, GLFW_KEY_LEFT_SHIFT ) == GLFW_PRESS ||
                    glfwGetKey (window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS);

  // determine action based on mouse button
  mjtMouse action;
  if      (button_right) action = mod_shift ? mjMOUSE_MOVE_H   : mjMOUSE_MOVE_V;
  else if (button_left ) action = mod_shift ? mjMOUSE_ROTATE_H : mjMOUSE_ROTATE_V;
  else                   action =                                mjMOUSE_ZOOM;

  // move camera
  mjv_moveCamera (m, action, dx/height, dy/height, &scn, &cam);
}


// scroll callback
void
scroll (GLFWwindow *window, double xoffset, double yoffset)
{
  // emulate vertical mouse motion = 5% of window height
  mjv_moveCamera (m, mjMOUSE_ZOOM, 0, -.05*yoffset, &scn, &cam);
}

int
get_obj_id (const char *name, mjtObj obj)
{
  // return 0;
  int id = mj_name2id (m, obj, name);
  if (id == -1) mju_error ("Object '%s' not found", name);
  return id;
}

void
control (const mjModel* m, mjData* d)
{
  d->ctrl[servo_ids[SERVO_LEFT ]] = steps[SERVO_LEFT ]*STEPS_TO_RADIANS;
  d->ctrl[servo_ids[SERVO_RIGHT]] = steps[SERVO_RIGHT]*STEPS_TO_RADIANS;
  d->ctrl[servo_ids[SERVO_UPPER]] = steps[SERVO_UPPER]*STEPS_TO_RADIANS;
}

int
main (int argc, const char** argv)
{
  progname  = *argv++;
  modelfile = *argv++;
  if (!modelfile) {
    printf ("Usage: %s modelfile [serialdev]\n", progname);
    return EXIT_FAILURE;
  }
  serialdev = *argv++;
  if (serialdev && *argv) {
    printf ("Usage: %s modelfile [serialdev]\n", progname);
    return EXIT_FAILURE;
  }

  model_load ();
  d = mj_makeData (m);

  mjcb_control = control;

  servo_ids[SERVO_LEFT ] = get_obj_id ("servo-left",  mjOBJ_ACTUATOR);
  servo_ids[SERVO_RIGHT] = get_obj_id ("servo-right", mjOBJ_ACTUATOR);
  servo_ids[SERVO_UPPER] = get_obj_id ("servo-upper", mjOBJ_ACTUATOR);

  shoulder_ids[SERVO_LEFT ] = get_obj_id ("shoulder-left",  mjOBJ_JOINT);
  shoulder_ids[SERVO_RIGHT] = get_obj_id ("shoulder-right", mjOBJ_JOINT) + 1;
  shoulder_ids[SERVO_UPPER] = get_obj_id ("shoulder-upper", mjOBJ_JOINT) + 1;

  if (!glfwInit ())
    mju_error ("Could not initialize GLFW");

  // create window, make OpenGL context current, request v-sync
  GLFWwindow *window = glfwCreateWindow (1200, 900, "", NULL, NULL);
  glfwMakeContextCurrent (window);
  glfwSwapInterval (1);

  // initialize visualization data structures
  mjv_defaultCamera  (&cam);
  mjv_defaultOption  (&opt);
  mjv_defaultScene   (&scn);
  mjr_defaultContext (&con);

  // create scene and context
  mjv_makeScene   (m, &scn, 2000);
  mjr_makeContext (m, &con, mjFONTSCALE_150);

  // install GLFW mouse and keyboard callbacks
  glfwSetKeyCallback         (window, keyboard);
  glfwSetCursorPosCallback   (window, mouse_move);
  glfwSetMouseButtonCallback (window, mouse_button);
  glfwSetScrollCallback      (window, scroll);

  int serial = serialdev ? open_serial (serialdev) : open ("/dev/null", O_RDWR);

  // run main loop, target real-time simulation and 60 fps rendering
  while (!glfwWindowShouldClose (window)) {
    // int id = mj_name2id (m, mjOBJ_BODY, "carriage");
    // printf ("%.3f %.3f %.3f\n", d->xpos[id*3 + 0], d->xpos[id*3 + 1], d->xpos[id*3 + 2]);

    mjtNum simstart = d->time;
    while (d->time - simstart < 1./60) {
      if (serial_read_ready) {
        int bytes_available;
        if (ioctl (serial, FIONREAD, &bytes_available) == -1 ||
            bytes_available < sizeof (read_buf)) {
          goto after_read;
        }

        serial_read_ready = false;
        ssize_t res = read (serial, read_buf, sizeof (read_buf));
        tcflush (serial, TCIFLUSH);
        if (res != sizeof (read_buf)) {
          fprintf (stderr, "not enough bytes!\n");
          goto after_read;
        }

        crc = *(uint32_t *) (read_buf + sizeof (steps));
        if (crc != crc32 ((uint32_t *) read_buf, sizeof (steps)/4)) {
          fprintf (stderr, "CRC mismatch!\n");
          goto after_read;
        }
        // memcpy (steps, read_buf, sizeof (steps));
        // printf ("%hd %hd %hd %hd %hd %hd %hd %hd %u\n",
        //         steps[0], steps[1], steps[2], steps[3],
        //         steps[4], steps[5], steps[6], steps[7], crc);

        memset (write_buf, 0, sizeof (write_buf));
        write_buf[0] = ends;
        *((uint32_t *) (write_buf + 1)) = crc32 ((uint32_t *) write_buf, 1);
        write (serial, write_buf, sizeof (write_buf));
        tcflush (serial, TCOFLUSH);
      } else if (!serialdev) {
        steps[SERVO_LEFT ] = (M_PI/8 - 0.2 + sinf (8/8.*glfwGetTime () + 0)*M_PI/8)/STEPS_TO_RADIANS*(1 - 2*(servo_left_handed >> SERVO_LEFT  & 1));
        steps[SERVO_RIGHT] = (M_PI/8 - 0.2 + sinf (7/8.*glfwGetTime () + 4)*M_PI/8)/STEPS_TO_RADIANS*(1 - 2*(servo_left_handed >> SERVO_RIGHT & 1));
        steps[SERVO_UPPER] = (M_PI/8 - 0.2 + sinf (6/8.*glfwGetTime () + 8)*M_PI/8)/STEPS_TO_RADIANS*(1 - 2*(servo_left_handed >> SERVO_UPPER & 1));
    } after_read:

      mj_step (m, d);

      ends = 0;
      ends |= (d->qpos[shoulder_ids[SERVO_LEFT ]]*(1 - 2*(servo_left_handed >> SERVO_LEFT  & 1)) < 0 ) << SERVO_LEFT;
      ends |= (d->qpos[shoulder_ids[SERVO_RIGHT]]*(1 - 2*(servo_left_handed >> SERVO_RIGHT & 1)) < 0 ) << SERVO_RIGHT;
      ends |= (d->qpos[shoulder_ids[SERVO_UPPER]]*(1 - 2*(servo_left_handed >> SERVO_UPPER & 1)) < 0 ) << SERVO_UPPER;

      // print actual angles and end cap states
      printf ("%+.3lf %+.3lf %+.3lf %b%b%b\n",
              d->qpos[shoulder_ids[SERVO_LEFT ]],
              d->qpos[shoulder_ids[SERVO_RIGHT]],
              d->qpos[shoulder_ids[SERVO_UPPER]],
              ends >> SERVO_LEFT  & 1,
              ends >> SERVO_RIGHT & 1,
              ends >> SERVO_UPPER & 1);

      // print actual angle, desired angle, error and end cap state for one servo
      // int servo = SERVO_UPPER;
      // printf ("%+lf %+lf %+lf %0b\n",
      //         d->qpos[shoulder_ids[servo]],  d->ctrl[servo_ids[servo]],
      //         d->qpos[shoulder_ids[servo]] - d->ctrl[servo_ids[servo]],
      //         ends >> servo);

      // print error (actual - desired)
      // printf ("%+lf %+lf %+lf\n",
      //         d->qpos[shoulder_ids[SERVO_LEFT ]] - d->ctrl[servo_ids[SERVO_LEFT ]],
      //         d->qpos[shoulder_ids[SERVO_RIGHT]] - d->ctrl[servo_ids[SERVO_RIGHT]],
      //         d->qpos[shoulder_ids[SERVO_UPPER]] - d->ctrl[servo_ids[SERVO_UPPER]]);
    }

    // get framebuffer viewport
    mjrRect viewport = { 0, 0, 0, 0 };
    glfwGetFramebufferSize (window, &viewport.width, &viewport.height);

    // update scene and render
    mjv_updateScene (m, d, &opt, NULL, &cam, mjCAT_ALL, &scn);
    mjr_render (viewport, &scn, &con);

    glfwSwapBuffers (window);
    glfwPollEvents ();

    if (glfwGetKey (window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
      glfwSetWindowShouldClose (window, GLFW_TRUE);
  }


  if (serialdev)
    tcsetattr (serial, TCSANOW, &oldtio);
  close (serial);

  mjv_freeScene   (&scn);
  mjr_freeContext (&con);

  glfwTerminate ();

  mj_deleteData  (d);
  mj_deleteModel (m);

  return EXIT_SUCCESS;
}
// end of simulate.c