diff options
| author | 2026-11-09 17:48:23 +0000 | |
|---|---|---|
| committer | 2026-11-09 18:03:25 +0000 | |
| commit | bd1b82e7eba0695ad7bb62ca0482e756dc374ba4 (patch) | |
| tree | 8cc51952853cd21cd55b48974c94d57f955ea555 /mujoco/src/simulate.c | |
| download | summer-practice-bd1b82e7eba0695ad7bb62ca0482e756dc374ba4.tar.gz | |
Diffstat (limited to 'mujoco/src/simulate.c')
| -rw-r--r-- | mujoco/src/simulate.c | 379 |
1 files changed, 379 insertions, 0 deletions
diff --git a/mujoco/src/simulate.c b/mujoco/src/simulate.c new file mode 100644 index 0000000..c88e83a --- /dev/null +++ b/mujoco/src/simulate.c | |||
| @@ -0,0 +1,379 @@ | |||
| 1 | // simulate.c --- run mujoco simulation with serial control | ||
| 2 | #include <stdlib.h> | ||
| 3 | #include <stdio.h> | ||
| 4 | #include <math.h> | ||
| 5 | #include <stdint.h> | ||
| 6 | #include <stdbool.h> | ||
| 7 | #include <string.h> | ||
| 8 | #include <time.h> | ||
| 9 | #include <errno.h> | ||
| 10 | #include <fcntl.h> | ||
| 11 | #include <termios.h> | ||
| 12 | #include <signal.h> | ||
| 13 | #include <sys/ioctl.h> | ||
| 14 | #include <unistd.h> | ||
| 15 | #include <GLFW/glfw3.h> | ||
| 16 | #include <mujoco/mujoco.h> | ||
| 17 | |||
| 18 | #define BAUDRATE B115200 | ||
| 19 | #define STEPS_TO_RADIANS (2*M_PI/360) | ||
| 20 | |||
| 21 | enum { | ||
| 22 | SERVO_LEFT, | ||
| 23 | SERVO_RIGHT, | ||
| 24 | SERVO_UPPER, | ||
| 25 | SERVO_COUNT | ||
| 26 | }; | ||
| 27 | |||
| 28 | uint8_t servo_left_handed = 1 << SERVO_LEFT | 1 << SERVO_RIGHT; | ||
| 29 | |||
| 30 | int servo_ids[SERVO_COUNT]; | ||
| 31 | int shoulder_ids[SERVO_COUNT]; | ||
| 32 | |||
| 33 | const char *progname; | ||
| 34 | const char *modelfile; | ||
| 35 | const char *serialdev; | ||
| 36 | |||
| 37 | int16_t steps[8] = {0}; | ||
| 38 | uint8_t ends = 0; | ||
| 39 | uint32_t crc; | ||
| 40 | char read_buf[sizeof (steps) + sizeof (crc)]; | ||
| 41 | char write_buf[sizeof (ends) + sizeof (crc)]; | ||
| 42 | volatile bool serial_read_ready = false; | ||
| 43 | struct termios oldtio; | ||
| 44 | |||
| 45 | // MuJoCo data structures | ||
| 46 | mjModel *m = NULL; // MuJoCo model | ||
| 47 | mjData *d = NULL; // MuJoCo data | ||
| 48 | mjvCamera cam; // abstract camera | ||
| 49 | mjvOption opt; // visualization options | ||
| 50 | mjvScene scn; // abstract scene | ||
| 51 | mjrContext con; // custom GPU context | ||
| 52 | |||
| 53 | // mouse interaction | ||
| 54 | bool button_left = false; | ||
| 55 | bool button_middle = false; | ||
| 56 | bool button_right = false; | ||
| 57 | double lastx = 0; | ||
| 58 | double lasty = 0; | ||
| 59 | |||
| 60 | static void | ||
| 61 | signal_handler_io (int status) | ||
| 62 | { | ||
| 63 | // printf ("received SIGIO\n"); | ||
| 64 | serial_read_ready = true; | ||
| 65 | } | ||
| 66 | |||
| 67 | static int | ||
| 68 | open_serial (const char *dev) | ||
| 69 | { | ||
| 70 | int fd; | ||
| 71 | for (;;) { | ||
| 72 | fd = open (dev, O_RDWR | O_NOCTTY | O_NONBLOCK); | ||
| 73 | if (fd != -1) break; | ||
| 74 | printf ("Error %i from open: %s\n", errno, strerror (errno)); | ||
| 75 | sleep (1); | ||
| 76 | } | ||
| 77 | |||
| 78 | struct sigaction saio = {0}; | ||
| 79 | saio.sa_handler = signal_handler_io; | ||
| 80 | // saio.sa_flags = SA_RESTART; | ||
| 81 | sigaction (SIGIO, &saio, NULL); | ||
| 82 | |||
| 83 | fcntl (fd, F_SETOWN, getpid ()); // allow the process to receive SIGIO | ||
| 84 | fcntl (fd, F_SETFL, FASYNC); // make the file descriptor asynchronous | ||
| 85 | |||
| 86 | struct termios newtio = {0}; | ||
| 87 | if (tcgetattr (fd, &oldtio) != 0) { | ||
| 88 | printf ("Error %i from tcgetattr: %s\n", errno, strerror (errno)); | ||
| 89 | exit (EXIT_FAILURE); | ||
| 90 | } | ||
| 91 | |||
| 92 | newtio.c_iflag = IGNPAR; | ||
| 93 | newtio.c_cflag = CS8 | CLOCAL | CREAD; | ||
| 94 | newtio.c_cc[VMIN ] = 0; | ||
| 95 | newtio.c_cc[VTIME] = 0; | ||
| 96 | cfsetspeed (&newtio, BAUDRATE); | ||
| 97 | |||
| 98 | // tcflush (fd, TCIFLUSH); | ||
| 99 | // if (tcsetattr (fd, TCSANOW, &newtio) != 0) { | ||
| 100 | if (tcsetattr (fd, TCSAFLUSH, &newtio) != 0) { | ||
| 101 | printf ("Error %i from tcsetattr: %s\n", errno, strerror (errno)); | ||
| 102 | } | ||
| 103 | |||
| 104 | return fd; | ||
| 105 | } | ||
| 106 | |||
| 107 | static uint32_t | ||
| 108 | crc32 (uint32_t *data, size_t len) | ||
| 109 | { | ||
| 110 | uint32_t crc = 0xffffffff; | ||
| 111 | |||
| 112 | for (size_t i = 0; i < len; ++i) { | ||
| 113 | crc ^= data[i]; | ||
| 114 | |||
| 115 | for (int j = 0; j < 32; ++j) { | ||
| 116 | crc = crc & 1 << 31 ? crc << 1 ^ 0x04c11db7 | ||
| 117 | : crc << 1; | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | return crc; | ||
| 122 | } | ||
| 123 | |||
| 124 | void | ||
| 125 | model_load (void) | ||
| 126 | { | ||
| 127 | char error[1000] = "Could not load binary model"; | ||
| 128 | if (strlen (modelfile) > 4 && | ||
| 129 | !strcmp (modelfile + strlen (modelfile) - 4, ".mjb")) { | ||
| 130 | m = mj_loadModel (modelfile, 0); | ||
| 131 | } else { | ||
| 132 | m = mj_loadXML (modelfile, 0, error, 1000); | ||
| 133 | } | ||
| 134 | |||
| 135 | if (!m) mju_error ("Load model error: %s", error); | ||
| 136 | } | ||
| 137 | |||
| 138 | void | ||
| 139 | keyboard (GLFWwindow *window, int key, int scancode, int act, int mods) | ||
| 140 | { | ||
| 141 | // Backspace: reset simulation | ||
| 142 | if (act == GLFW_PRESS && key == GLFW_KEY_BACKSPACE) { | ||
| 143 | mj_resetData (m, d); | ||
| 144 | mj_forward (m, d); | ||
| 145 | } | ||
| 146 | |||
| 147 | // F5: reload | ||
| 148 | if (act == GLFW_PRESS && key == GLFW_KEY_F5) { | ||
| 149 | model_load (); | ||
| 150 | } | ||
| 151 | } | ||
| 152 | |||
| 153 | void | ||
| 154 | mouse_button (GLFWwindow *window, int button, int act, int mods) | ||
| 155 | { | ||
| 156 | button_left = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS; | ||
| 157 | button_middle = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS; | ||
| 158 | button_right = glfwGetMouseButton (window, GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS; | ||
| 159 | |||
| 160 | // update mouse position | ||
| 161 | glfwGetCursorPos (window, &lastx, &lasty); | ||
| 162 | } | ||
| 163 | |||
| 164 | |||
| 165 | // mouse move callback | ||
| 166 | void | ||
| 167 | mouse_move (GLFWwindow *window, double xpos, double ypos) | ||
| 168 | { | ||
| 169 | // no buttons down: nothing to do | ||
| 170 | if (!button_left && !button_middle && !button_right) return; | ||
| 171 | |||
| 172 | // compute mouse displacement, save | ||
| 173 | double dx = xpos - lastx; | ||
| 174 | double dy = ypos - lasty; | ||
| 175 | lastx = xpos; | ||
| 176 | lasty = ypos; | ||
| 177 | |||
| 178 | // get current window size | ||
| 179 | int width, height; | ||
| 180 | glfwGetWindowSize (window, &width, &height); | ||
| 181 | |||
| 182 | // get shift key state | ||
| 183 | bool mod_shift = (glfwGetKey (window, GLFW_KEY_LEFT_SHIFT ) == GLFW_PRESS || | ||
| 184 | glfwGetKey (window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); | ||
| 185 | |||
| 186 | // determine action based on mouse button | ||
| 187 | mjtMouse action; | ||
| 188 | if (button_right) action = mod_shift ? mjMOUSE_MOVE_H : mjMOUSE_MOVE_V; | ||
| 189 | else if (button_left ) action = mod_shift ? mjMOUSE_ROTATE_H : mjMOUSE_ROTATE_V; | ||
| 190 | else action = mjMOUSE_ZOOM; | ||
| 191 | |||
| 192 | // move camera | ||
| 193 | mjv_moveCamera (m, action, dx/height, dy/height, &scn, &cam); | ||
| 194 | } | ||
| 195 | |||
| 196 | |||
| 197 | // scroll callback | ||
| 198 | void | ||
| 199 | scroll (GLFWwindow *window, double xoffset, double yoffset) | ||
| 200 | { | ||
| 201 | // emulate vertical mouse motion = 5% of window height | ||
| 202 | mjv_moveCamera (m, mjMOUSE_ZOOM, 0, -.05*yoffset, &scn, &cam); | ||
| 203 | } | ||
| 204 | |||
| 205 | int | ||
| 206 | get_obj_id (const char *name, mjtObj obj) | ||
| 207 | { | ||
| 208 | // return 0; | ||
| 209 | int id = mj_name2id (m, obj, name); | ||
| 210 | if (id == -1) mju_error ("Object '%s' not found", name); | ||
| 211 | return id; | ||
| 212 | } | ||
| 213 | |||
| 214 | void | ||
| 215 | control (const mjModel* m, mjData* d) | ||
| 216 | { | ||
| 217 | d->ctrl[servo_ids[SERVO_LEFT ]] = steps[SERVO_LEFT ]*STEPS_TO_RADIANS; | ||
| 218 | d->ctrl[servo_ids[SERVO_RIGHT]] = steps[SERVO_RIGHT]*STEPS_TO_RADIANS; | ||
| 219 | d->ctrl[servo_ids[SERVO_UPPER]] = steps[SERVO_UPPER]*STEPS_TO_RADIANS; | ||
| 220 | } | ||
| 221 | |||
| 222 | int | ||
| 223 | main (int argc, const char** argv) | ||
| 224 | { | ||
| 225 | progname = *argv++; | ||
| 226 | modelfile = *argv++; | ||
| 227 | if (!modelfile) { | ||
| 228 | printf ("Usage: %s modelfile [serialdev]\n", progname); | ||
| 229 | return EXIT_FAILURE; | ||
| 230 | } | ||
| 231 | serialdev = *argv++; | ||
| 232 | if (serialdev && *argv) { | ||
| 233 | printf ("Usage: %s modelfile [serialdev]\n", progname); | ||
| 234 | return EXIT_FAILURE; | ||
| 235 | } | ||
| 236 | |||
| 237 | model_load (); | ||
| 238 | d = mj_makeData (m); | ||
| 239 | |||
| 240 | mjcb_control = control; | ||
| 241 | |||
| 242 | servo_ids[SERVO_LEFT ] = get_obj_id ("servo-left", mjOBJ_ACTUATOR); | ||
| 243 | servo_ids[SERVO_RIGHT] = get_obj_id ("servo-right", mjOBJ_ACTUATOR); | ||
| 244 | servo_ids[SERVO_UPPER] = get_obj_id ("servo-upper", mjOBJ_ACTUATOR); | ||
| 245 | |||
| 246 | shoulder_ids[SERVO_LEFT ] = get_obj_id ("shoulder-left", mjOBJ_JOINT); | ||
| 247 | shoulder_ids[SERVO_RIGHT] = get_obj_id ("shoulder-right", mjOBJ_JOINT) + 1; | ||
| 248 | shoulder_ids[SERVO_UPPER] = get_obj_id ("shoulder-upper", mjOBJ_JOINT) + 1; | ||
| 249 | |||
| 250 | if (!glfwInit ()) | ||
| 251 | mju_error ("Could not initialize GLFW"); | ||
| 252 | |||
| 253 | // create window, make OpenGL context current, request v-sync | ||
| 254 | GLFWwindow *window = glfwCreateWindow (1200, 900, "", NULL, NULL); | ||
| 255 | glfwMakeContextCurrent (window); | ||
| 256 | glfwSwapInterval (1); | ||
| 257 | |||
| 258 | // initialize visualization data structures | ||
| 259 | mjv_defaultCamera (&cam); | ||
| 260 | mjv_defaultOption (&opt); | ||
| 261 | mjv_defaultScene (&scn); | ||
| 262 | mjr_defaultContext (&con); | ||
| 263 | |||
| 264 | // create scene and context | ||
| 265 | mjv_makeScene (m, &scn, 2000); | ||
| 266 | mjr_makeContext (m, &con, mjFONTSCALE_150); | ||
| 267 | |||
| 268 | // install GLFW mouse and keyboard callbacks | ||
| 269 | glfwSetKeyCallback (window, keyboard); | ||
| 270 | glfwSetCursorPosCallback (window, mouse_move); | ||
| 271 | glfwSetMouseButtonCallback (window, mouse_button); | ||
| 272 | glfwSetScrollCallback (window, scroll); | ||
| 273 | |||
| 274 | int serial = serialdev ? open_serial (serialdev) : open ("/dev/null", O_RDWR); | ||
| 275 | |||
| 276 | // run main loop, target real-time simulation and 60 fps rendering | ||
| 277 | while (!glfwWindowShouldClose (window)) { | ||
| 278 | // int id = mj_name2id (m, mjOBJ_BODY, "carriage"); | ||
| 279 | // printf ("%.3f %.3f %.3f\n", d->xpos[id*3 + 0], d->xpos[id*3 + 1], d->xpos[id*3 + 2]); | ||
| 280 | |||
| 281 | mjtNum simstart = d->time; | ||
| 282 | while (d->time - simstart < 1./60) { | ||
| 283 | if (serial_read_ready) { | ||
| 284 | int bytes_available; | ||
| 285 | if (ioctl (serial, FIONREAD, &bytes_available) == -1 || | ||
| 286 | bytes_available < sizeof (read_buf)) { | ||
| 287 | goto after_read; | ||
| 288 | } | ||
| 289 | |||
| 290 | serial_read_ready = false; | ||
| 291 | ssize_t res = read (serial, read_buf, sizeof (read_buf)); | ||
| 292 | tcflush (serial, TCIFLUSH); | ||
| 293 | if (res != sizeof (read_buf)) { | ||
| 294 | fprintf (stderr, "not enough bytes!\n"); | ||
| 295 | goto after_read; | ||
| 296 | } | ||
| 297 | |||
| 298 | crc = *(uint32_t *) (read_buf + sizeof (steps)); | ||
| 299 | if (crc != crc32 ((uint32_t *) read_buf, sizeof (steps)/4)) { | ||
| 300 | fprintf (stderr, "CRC mismatch!\n"); | ||
| 301 | goto after_read; | ||
| 302 | } | ||
| 303 | // memcpy (steps, read_buf, sizeof (steps)); | ||
| 304 | // printf ("%hd %hd %hd %hd %hd %hd %hd %hd %u\n", | ||
| 305 | // steps[0], steps[1], steps[2], steps[3], | ||
| 306 | // steps[4], steps[5], steps[6], steps[7], crc); | ||
| 307 | |||
| 308 | memset (write_buf, 0, sizeof (write_buf)); | ||
| 309 | write_buf[0] = ends; | ||
| 310 | *((uint32_t *) (write_buf + 1)) = crc32 ((uint32_t *) write_buf, 1); | ||
| 311 | write (serial, write_buf, sizeof (write_buf)); | ||
| 312 | tcflush (serial, TCOFLUSH); | ||
| 313 | } else if (!serialdev) { | ||
| 314 | 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)); | ||
| 315 | 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)); | ||
| 316 | 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)); | ||
| 317 | } after_read: | ||
| 318 | |||
| 319 | mj_step (m, d); | ||
| 320 | |||
| 321 | ends = 0; | ||
| 322 | ends |= (d->qpos[shoulder_ids[SERVO_LEFT ]]*(1 - 2*(servo_left_handed >> SERVO_LEFT & 1)) < 0 ) << SERVO_LEFT; | ||
| 323 | ends |= (d->qpos[shoulder_ids[SERVO_RIGHT]]*(1 - 2*(servo_left_handed >> SERVO_RIGHT & 1)) < 0 ) << SERVO_RIGHT; | ||
| 324 | ends |= (d->qpos[shoulder_ids[SERVO_UPPER]]*(1 - 2*(servo_left_handed >> SERVO_UPPER & 1)) < 0 ) << SERVO_UPPER; | ||
| 325 | |||
| 326 | // print actual angles and end cap states | ||
| 327 | printf ("%+.3lf %+.3lf %+.3lf %b%b%b\n", | ||
| 328 | d->qpos[shoulder_ids[SERVO_LEFT ]], | ||
| 329 | d->qpos[shoulder_ids[SERVO_RIGHT]], | ||
| 330 | d->qpos[shoulder_ids[SERVO_UPPER]], | ||
| 331 | ends >> SERVO_LEFT & 1, | ||
| 332 | ends >> SERVO_RIGHT & 1, | ||
| 333 | ends >> SERVO_UPPER & 1); | ||
| 334 | |||
| 335 | // print actual angle, desired angle, error and end cap state for one servo | ||
| 336 | // int servo = SERVO_UPPER; | ||
| 337 | // printf ("%+lf %+lf %+lf %0b\n", | ||
| 338 | // d->qpos[shoulder_ids[servo]], d->ctrl[servo_ids[servo]], | ||
| 339 | // d->qpos[shoulder_ids[servo]] - d->ctrl[servo_ids[servo]], | ||
| 340 | // ends >> servo); | ||
| 341 | |||
| 342 | // print error (actual - desired) | ||
| 343 | // printf ("%+lf %+lf %+lf\n", | ||
| 344 | // d->qpos[shoulder_ids[SERVO_LEFT ]] - d->ctrl[servo_ids[SERVO_LEFT ]], | ||
| 345 | // d->qpos[shoulder_ids[SERVO_RIGHT]] - d->ctrl[servo_ids[SERVO_RIGHT]], | ||
| 346 | // d->qpos[shoulder_ids[SERVO_UPPER]] - d->ctrl[servo_ids[SERVO_UPPER]]); | ||
| 347 | } | ||
| 348 | |||
| 349 | // get framebuffer viewport | ||
| 350 | mjrRect viewport = { 0, 0, 0, 0 }; | ||
| 351 | glfwGetFramebufferSize (window, &viewport.width, &viewport.height); | ||
| 352 | |||
| 353 | // update scene and render | ||
| 354 | mjv_updateScene (m, d, &opt, NULL, &cam, mjCAT_ALL, &scn); | ||
| 355 | mjr_render (viewport, &scn, &con); | ||
| 356 | |||
| 357 | glfwSwapBuffers (window); | ||
| 358 | glfwPollEvents (); | ||
| 359 | |||
| 360 | if (glfwGetKey (window, GLFW_KEY_ESCAPE) == GLFW_PRESS) | ||
| 361 | glfwSetWindowShouldClose (window, GLFW_TRUE); | ||
| 362 | } | ||
| 363 | |||
| 364 | |||
| 365 | if (serialdev) | ||
| 366 | tcsetattr (serial, TCSANOW, &oldtio); | ||
| 367 | close (serial); | ||
| 368 | |||
| 369 | mjv_freeScene (&scn); | ||
| 370 | mjr_freeContext (&con); | ||
| 371 | |||
| 372 | glfwTerminate (); | ||
| 373 | |||
| 374 | mj_deleteData (d); | ||
| 375 | mj_deleteModel (m); | ||
| 376 | |||
| 377 | return EXIT_SUCCESS; | ||
| 378 | } | ||
| 379 | // end of simulate.c | ||
