From cb070b2d3f2b6e241e3be1b7e0eeb90fc755255f Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Thu, 12 Nov 2026 01:28:13 +0300 Subject: publish --- src/simulate.c | 646 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 646 insertions(+) create mode 100644 src/simulate.c (limited to 'src/simulate.c') diff --git a/src/simulate.c b/src/simulate.c new file mode 100644 index 0000000..e053599 --- /dev/null +++ b/src/simulate.c @@ -0,0 +1,646 @@ +/// src/simulate.h +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#include +#include +#include +#include + +#include +#include +#include + +#include "utils.h" +#include "da.h" +#include "rs274ngc_lexer.h" +#include "rs274ngc_cst.h" +#include "path.h" +#include "motion_planner.h" +#include "critical_points.h" +#include "compensations.h" +#include "rate.h" + +#define LINE_THICKNESS 4 +#define TITLE "RS274NGC Simulator" + +#define DPU 8 // dots per unit + +struct point { + Vector2 c; + Vector2 n; +}; + +struct points { + struct point *items; + uint32_t count; + uint32_t capacity; +} points = {0}; + +struct rgb32 { + uint8_t r, g, b, a; +}; + +struct overlay { + const char *name; + struct rgb32 *items; + uint32_t count; + uint32_t capacity; +}; + +struct overlays { + struct overlay *items; + uint32_t count; + uint32_t capacity; +} overlays = {0}; + +struct path path = {0}; +struct critical_points cps = {0}; +struct compensations comps = {0}; + +struct rgb32 +lerp_rgb32 (struct rgb32 a, struct rgb32 b, float t) +{ + struct rgb32 c; + c.r = (uint8_t) (a.r + (b.r - a.r)*t); + c.g = (uint8_t) (a.g + (b.g - a.g)*t); + c.b = (uint8_t) (a.b + (b.b - a.b)*t); + c.a = (uint8_t) (a.a + (b.a - a.a)*t); + return c; +} + +void +print_arena (const struct arena *a) +{ + for (struct arena_chunk *ch = a->head; ch; ch = ch->next) + printf ("%p %lu\n", ch, (void *) ch - ch->begin); +} + +void +print_path (struct path path) +{ + DA_FOR_EACH (pe, path) { + printf ("%04b | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %.*s\n", + pe->flags, pe->x, pe->y, pe->f, pe->i, pe->j, SV_FMTA (pe->line)); + } +} + +void +draw_path (struct path path) +{ + SetConfigFlags (FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT); + InitWindow (700, 700, TITLE); + Camera2D camera = { + .zoom = 8, + }; + + int first = 1; + while (!WindowShouldClose ()) { + float line_thickness = LINE_THICKNESS/camera.zoom; + + Vector2 cursor = Vector2Zero (); + if (IsMouseButtonDown (MOUSE_BUTTON_LEFT) || + IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) { + camera.target = Vector2Add (camera.target, Vector2Scale (GetMouseDelta (), -1/camera.zoom)); + } + + float wheel_move = -GetMouseWheelMove (); + if (wheel_move) { + Vector2 offset = GetMousePosition (); + camera.target = GetScreenToWorld2D (offset, camera); + camera.offset = offset; + camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel_move), 4, 128); + } + + BeginDrawing (); + ClearBackground (WHITE); + BeginMode2D (camera); + + // DrawLine (-1000, 0, +1000, 0, GRAY); + // DrawLine (0, -1000, 0, +1000, GRAY); + rlPushMatrix (); + rlTranslatef (100, 0, 0); + rlRotatef (90, 1, 0, 0); + DrawGrid (200, 1); + rlPopMatrix(); + + DA_FOR_EACH (pe, path) { + Vector2 from = cursor; + cursor = (Vector2) { pe->x, -pe->y }; + if (pe->flags & PEF_ARC) { + Vector2 center = { pe->i, -pe->j }; + float r = Vector2Distance (from, center); + + Vector2 v0 = Vector2Subtract (from, center); + Vector2 v1 = Vector2Subtract (cursor, center); + float angle_beg = Vector2Angle ((Vector2) { 1, 0 }, v0)/PI*180; + float angle_end = Vector2Angle ((Vector2) { 1, 0 }, v1)/PI*180; + if (first) printf ("< %f %f | " SV_FMT "\n", angle_beg, angle_end, SV_FMTA (pe->line)); + if (pe->flags & PEF_CCW) { + float tmp = angle_beg; + angle_beg = angle_end; + angle_end = tmp; + } + if (angle_beg > angle_end) + angle_end += 360; + if (Vector2Equals (from, cursor)) { + angle_beg = 0; + angle_end = 360; + } + if (first) printf ("< %f %f\n\n", angle_beg, angle_end); + + DrawCircleV (center, line_thickness/2, GREEN); + DrawRing (center, r - line_thickness/2, r + line_thickness/2, + angle_beg, angle_end, 32, BLUE); + } else { + if (pe->flags & PEF_TRAVERSING) { + // DrawLineV (from, cursor, ORANGE); + DrawCircleV (from, line_thickness/4, ORANGE); + DrawLineEx (from, cursor, line_thickness/2, ORANGE); + DrawCircleV (cursor, line_thickness/4, ORANGE); + } else { + // DrawLineV (from, cursor, BLUE); + DrawCircleV (from, line_thickness/2, BLUE); + DrawLineEx (from, cursor, line_thickness, BLUE); + DrawCircleV (cursor, line_thickness/2, BLUE); + } + } + } + EndMode2D (); + EndDrawing (); + first = 0; + } + + CloseWindow (); +} + +void +draw_grid (Rectangle bb, float step) +{ + rlBegin (RL_LINES); + int i = 0; + for (float y = bb.y; y <= bb.y + bb.height; y += step) { + if (i % 10 == 0) { + rlColor3f (.25, .25, .25); + rlColor3f (.25, .25, .25); + } else { + rlColor3f (.5, .5, .5); + rlColor3f (.5, .5, .5); + } i += 1; + + rlVertex3f (bb.x, -y, 0); + rlVertex3f (bb.x + bb.width, -y, 0); + } + i = 0; + for (float x = bb.x; x <= bb.x + bb.width; x += step) { + if (i % 10 == 0) { + rlColor3f (.25, .25, .25); + rlColor3f (.25, .25, .25); + } else { + rlColor3f (.5, .5, .5); + rlColor3f (.5, .5, .5); + } i += 1; + + rlVertex3f (x, -bb.y, 0); + rlVertex3f (x, -bb.y - bb.height, 0); + } + rlEnd (); +} + +#define ARROW_LENGTH .5 +#define ARROW_ANGLE 10 + +void +draw_arrow (Vector2 beg, Vector2 end, float thick, Color c) +{ + Vector2 off = Vector2Scale (Vector2Normalize (Vector2Subtract (end, beg)), + ARROW_LENGTH); + Vector2 ahl = Vector2Add (end, Vector2Rotate (off, +ARROW_ANGLE)); + Vector2 ahr = Vector2Add (end, Vector2Rotate (off, -ARROW_ANGLE)); + + DrawLineEx (beg, end, thick, c); + DrawLineEx (end, ahl, thick, c); + DrawLineEx (end, ahr, thick, c); + + DrawCircleV (beg, thick/2., c); + DrawCircleV (end, thick/2., c); + DrawCircleV (ahl, thick/2., c); + DrawCircleV (ahr, thick/2., c); +} + +void +visualize (void) +{ + uint32_t active_overlay = 0; + + SetConfigFlags (FLAG_MSAA_4X_HINT | + FLAG_VSYNC_HINT | + FLAG_WINDOW_UNDECORATED | + FLAG_BORDERLESS_WINDOWED_MODE | + FLAG_WINDOW_RESIZABLE | + 0); + float s = 1.25; + // InitWindow (700*s, 700, TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); + InitWindow (750, 650, TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); + SetTargetFPS (60); + rlDisableBackfaceCulling (); + + Camera2D camera = { + // .zoom = 16, + .zoom = 7*s, + .offset = { + .x = 0, + .y = GetScreenHeight (), + }, + .target = { + .x = 25.85, + .y = -33.6, + }, + }; + + int draw_grid_flag = 1; + int draw_fps_flag = 0; + int draw_cps_flag = 0; + int draw_comps_flag = 0; + // uint32_t from = 37120; + // uint32_t upto = 48080; + // uint32_t from = 17800; + // uint32_t upto = 24000; + uint32_t from = 0; + uint32_t upto = points.count; + while (!WindowShouldClose ()) { + if (IsKeyPressed (KEY_UP)) { + active_overlay = (active_overlay + 1) % overlays.count; + SetWindowTitle (TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); + } + if (IsKeyPressed (KEY_DOWN)) { + active_overlay = overlays.count - 1 - (overlays.count - active_overlay) % overlays.count; + SetWindowTitle (TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); + } + + uint32_t speed = (300 + 700*IsKeyDown (KEY_LEFT_SHIFT))*GetFrameTime (); + // speed = 1; + if (IsKeyUp (KEY_LEFT_CONTROL)) { + if (IsKeyDown (KEY_RIGHT)) + upto = (upto + speed) % (points.count + 1); + if (IsKeyDown (KEY_LEFT)) + upto = upto <= speed ? from : upto - speed; + } else { + if (IsKeyDown (KEY_RIGHT)) + from = (from + speed) % (upto + 1); + if (IsKeyDown (KEY_LEFT)) + from = from <= speed ? points.count : from - speed; + } + + if (IsKeyPressed (KEY_G)) + draw_grid_flag = !draw_grid_flag; + if (IsKeyPressed (KEY_F)) + draw_fps_flag = !draw_fps_flag; + if (IsKeyPressed (KEY_P)) + draw_cps_flag = !draw_cps_flag; + if (IsKeyPressed (KEY_C)) + draw_comps_flag = !draw_comps_flag; + + float line_thickness = LINE_THICKNESS/camera.zoom; + + Vector2 cursor = Vector2Zero (); + if (IsMouseButtonDown (MOUSE_BUTTON_LEFT) || + IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) { + camera.target = + Vector2Add (camera.target, + Vector2Scale (GetMouseDelta (), -1/camera.zoom)); + } + + float wheel_move = -GetMouseWheelMove (); + if (wheel_move) { + Vector2 offset = GetMousePosition (); + camera.target = GetScreenToWorld2D (offset, camera); + camera.offset = offset; + camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel_move), 4, 128); + } + + Rectangle screen = { + .width = GetScreenWidth (), + .height = GetScreenHeight (), + }; + + BeginDrawing (); + ClearBackground (WHITE); + BeginMode2D (camera); + + float grid_size = 200; + if (draw_grid_flag) { + // rlPushMatrix (); + // rlTranslatef (grid_size/2, 0, 0); + // rlRotatef (90, 1, 0, 0); + // DrawGrid (grid_size, 1); + // rlPopMatrix(); + draw_grid ((Rectangle) { 0, 0, 100, 80 }, 10); + } + + struct overlay *overlay = &overlays.items[active_overlay]; + + uint32_t i = from; + struct rgb32 pc = overlay->items[i]; + + Vector2 c = points.items[i].c; + Vector2 n = Vector2Scale (points.items[i].n, LINE_THICKNESS/2/camera.zoom); + Vector2 pl = Vector2Add (c, n); + Vector2 pr = Vector2Subtract (c, n); + + rlBegin (RL_TRIANGLES); + for (i = from + 1; i < upto; i += logf (128)/logf (camera.zoom)) { + Vector2 c = points.items[i].c; + Vector2 n = Vector2Scale (points.items[i].n, LINE_THICKNESS/2/camera.zoom); + Vector2 cl = Vector2Add (c, n); + Vector2 cr = Vector2Subtract (c, n); + + struct rgb32 cc = overlay->items[i]; + + rlColor4ub (pc.r, pc.g, pc.b, pc.a); rlVertex2f (pl.x, pl.y); + rlColor4ub (cc.r, cc.g, cc.b, cc.a); rlVertex2f (cl.x, cl.y); + rlColor4ub (pc.r, pc.g, pc.b, pc.a); rlVertex2f (pr.x, pr.y); + + rlColor4ub (pc.r, pc.g, pc.b, pc.a); rlVertex2f (pr.x, pr.y); + rlColor4ub (cc.r, cc.g, cc.b, cc.a); rlVertex2f (cl.x, cl.y); + rlColor4ub (cc.r, cc.g, cc.b, cc.a); rlVertex2f (cr.x, cr.y); + + pl = cl; + pr = cr; + pc = cc; + } + rlEnd (); + + if (draw_comps_flag) { + for (uint32_t i = 0; i < comps.count; ++i) { + const struct compensation *c = &comps.items[i]; + const struct polyline *pl = &c->polyline; + Vector2 from = { c->initial_position.x, -c->initial_position.y }; + for (uint32_t j = 0; j < pl->count; ++j) { + struct vec2 tov = pl->items[j]; + Vector2 to = { tov.x, -tov.y }; + DrawLineEx (from, to, line_thickness/2, GREEN); + from = to; + } + } + } + + if (draw_cps_flag) { + for (uint32_t i = 0; i < cps.count; ++i) { + const struct critical_point *cp = &cps.items[i]; + Vector2 c = { cp->r.x, -cp->r.y }; + Vector2 in = { 1.5*cp->t_left .x, -1.5*cp->t_left .y }; + Vector2 out = { 1.5*cp->t_right.x, -1.5*cp->t_right.y }; + + struct Color colors[] = { + [CPT_IN ] = RED, + [CPT_OUT ] = GREEN, + [CPT_LOOP] = BLACK, + [CPT_BEG ] = RED, + [CPT_END ] = GREEN, + }; + DrawCircleV (c, line_thickness, colors[cp->type]); + // DrawCircleV (c, 2*line_thickness, BLACK); + + draw_arrow (c, Vector2Add (c, in ), line_thickness, GREEN); + draw_arrow (c, Vector2Add (c, out), line_thickness, RED); + } + } + + EndMode2D (); + if (draw_fps_flag) + DrawFPS (2, 0); + // DrawText (TextFormat ("FROM: %u", from), 2, 0, 20, BLACK); + // DrawText (TextFormat ("UPTO: %u", upto), 2, 20, 20, BLACK); + // DrawText (TextFormat ("WIDTH: %d", GetScreenWidth ()), 2, 0*20, 20, BLACK); + // DrawText (TextFormat ("HEIGHT: %d", GetScreenHeight ()), 2, 1*20, 20, BLACK); + // DrawText (TextFormat ("ZOOM: %f", camera.zoom ), 2, 2*20, 20, BLACK); + // DrawText (TextFormat ("XOFF: %f", camera.offset.x ), 2, 3*20, 20, BLACK); + // DrawText (TextFormat ("YOFF: %f", camera.offset.y ), 2, 4*20, 20, BLACK); + // DrawText (TextFormat ("YTAR: %f", camera.target.x ), 2, 5*20, 20, BLACK); + // DrawText (TextFormat ("YTAR: %f", camera.target.y ), 2, 6*20, 20, BLACK); + EndDrawing (); + } + + CloseWindow (); +} + +struct overlay line_overlay = { .name = "line" }; +struct overlay type_overlay = { .name = "type" }; +struct overlay velocity_overlay = { .name = "velocity" }; +struct overlay velocity_error_overlay = { .name = "velocity error" }; +struct overlay velocity_error_alpha_overlay = { .name = "velocity error (alpha)" }; +struct overlay acceleration_overlay = { .name = "acceleration" }; +struct overlay acceleration_t_overlay = { .name = "tangential acceleration" }; +struct overlay acceleration_n_overlay = { .name = "normal acceleration" }; +struct overlay jerk_overlay = { .name = "jerk" }; +struct overlay jerk_alpha_overlay = { .name = "jerk (alpha)" }; + +void +add_sample (const struct motion_plan *plan, + const struct mp_sample *sample) +{ + struct point point = { + .c = { sample->p.x, -sample->p.y }, + .n = { sample->normal.x, -sample->normal.y }, + }; + if (sample->source_flags & PEF_TRAVERSING) { + point.n.x /= 2; + point.n.y /= 2; + } + DA_APPEND (points, point); + struct rgb32 red = { 0xff, 0x00, 0x00, 0xff }; + struct rgb32 blue = { 0x00, 0x00, 0xff, 0xff }; + struct rgb32 green = { 0x00, 0xff, 0x00, 0xff }; + struct rgb32 orange = { 0xff, 0x7f, 0x00, 0xff }; + struct rgb32 blank = { 0x00, 0x00, 0x00, 0x00 }; + if (sample->source_flags & PEF_TRAVERSING) { + DA_APPEND ( velocity_overlay, orange); + DA_APPEND (velocity_error_overlay, orange); + DA_APPEND (velocity_error_alpha_overlay, blank); + DA_APPEND (jerk_alpha_overlay, blank); + DA_APPEND ( acceleration_t_overlay, orange); + DA_APPEND ( acceleration_n_overlay, orange); + DA_APPEND ( jerk_overlay, orange); + } + else { + struct rgb32 black_red = { 0xff, 0x00, 0x00, 0x00 }; + double v_nominal = plan->segments[sample->segment_index].v_nominal; + double error = fabs (sample->v - v_nominal); + float t = Normalize (error, plan->v_min, v_nominal); + DA_APPEND (velocity_error_overlay, lerp_rgb32 (green, red, t)); + DA_APPEND (velocity_error_alpha_overlay, lerp_rgb32 (black_red, red, t)); + struct rgb32 jc = lerp_rgb32 (red, blue, Normalize (sample->j_abs, plan->j_min, plan->j_max)); + jc.a = 0xff*Clamp (Normalize (sample->j_abs, 0, sample->j_abs > 0 ? plan->j_max : plan->j_min), 0, 1); + DA_APPEND (jerk_alpha_overlay, jc); + } + + DA_APPEND ( velocity_overlay, lerp_rgb32 (red, blue, Normalize (sample->v, plan->v_min, plan->v_max))); + DA_APPEND (acceleration_t_overlay, lerp_rgb32 (red, blue, Normalize (sample->a_t, plan->a_min, plan->a_max))); + DA_APPEND (acceleration_n_overlay, lerp_rgb32 (red, blue, Normalize (sample->a_n, plan->a_min, plan->a_max))); + DA_APPEND ( jerk_overlay, lerp_rgb32 (red, blue, Normalize (sample->j_abs, plan->j_min, plan->j_max))); + + struct rgb32 colors[] = { + { 0xff, 0x00, 0x00, 0xff }, + { 0x00, 0xff, 0xff, 0xff }, + { 0x00, 0xff, 0x00, 0xff }, + { 0xff, 0x00, 0xff, 0xff }, + { 0x00, 0x00, 0xff, 0xff }, + { 0xff, 0xff, 0x00, 0xff }, + }; + DA_APPEND (line_overlay, colors[sample->source_index % ARRAY_LENGTH (colors)]); + + if (sample->source_flags & PEF_ARC) { + if (sample->source_flags & PEF_CCW) + DA_APPEND (type_overlay, red); + else + DA_APPEND (type_overlay, green); + } else { + if (sample->source_flags & PEF_TRAVERSING) + DA_APPEND (type_overlay, orange); + else + DA_APPEND (type_overlay, blue); + } +} + +void +build_overlays (const struct motion_plan *plan) +{ + double dt = .001; + + struct mp_sample smp; + for (double t = 0; t < plan->total_time; t += dt) { + mp_plan_sample (plan, t, &smp); + add_sample (plan, &smp); + } mp_plan_sample (plan, plan->total_time, &smp); + add_sample (plan, &smp); + + DA_APPEND (overlays, line_overlay); + DA_APPEND (overlays, type_overlay); + DA_APPEND (overlays, velocity_overlay); + DA_APPEND (overlays, velocity_error_overlay); + DA_APPEND (overlays, velocity_error_alpha_overlay); + DA_APPEND (overlays, acceleration_t_overlay); + DA_APPEND (overlays, acceleration_n_overlay); + DA_APPEND (overlays, jerk_overlay); + DA_APPEND (overlays, jerk_alpha_overlay); +} + +int +main (int argc, char *argv[]) +{ + progname = argv[0]; + + const char *filename; + int fd = 0; + if (argc == 1) { + filename = "-"; + } else if (argc == 2) { + filename = argv[1]; + fd = open (filename, O_RDONLY); + } else { + DIE ("too many arguments provided"); + } + + struct arena a = {0}; + struct arena t = {0}; + + struct sv rs274ngc = read_until_eof (&a, fd); + if (fd) close (fd); + + rs274ngc_lexer_compile_regexes (); + struct rs274ngc_lexer lexer = rs274ngc_lexer_from_sv (rs274ngc, filename); + + struct rs274ngc_cst_parser parser = { + .lexer = &lexer, + .output = &a, + .temporary = &t, + }; + + path = build_path (parser); + ASSERT (path.count > 0); + // print_path (path); + // draw_path (path); + // return 0; + + double initial_x = 0; + double initial_y = 0; + + struct mp_limits limits = { + .vmax = 80, + .rapid_vmax = 100, + .amax = 800, + .jmax = 16000, + .corner_tol = .05, + // .corner_tol = 1, + .min_segment_len = 1e-6, + .default_feed = 50, + + .straight_angle_tol = 0.02, + .stop_angle = M_PI/8, + .corner_speed_deadband = .002, + + .curvature_blend_len = 0.05, + }; + + cps = find_critical_points (&path); + uint32_t cpcs[5] = {0}; + for (uint32_t i = 0; i < cps.count; ++i) { + const struct critical_point *cp = &cps.items[i]; + cpcs[cp->type] += 1; + } + printf ("CPT_IN: %u\n", cpcs[CPT_IN]), + printf ("CPT_OUT: %u\n", cpcs[CPT_OUT]), + printf ("CPT_LOOP: %u\n", cpcs[CPT_LOOP]), + printf ("CPT_BEG: %u\n", cpcs[CPT_BEG]), + printf ("CPT_END: %u\n", cpcs[CPT_END]), + printf ("CPT_TOTAL: %u\n", cpcs[0] + cpcs[1] + cpcs[2] + cpcs[3] + cpcs[4]), + + comps = synthesize_compensations (&cps); + + struct motion_plan plan = {0}; + + ASSERT (path.count > 0); + int rc = mp_plan_build (&path, initial_x, initial_y, &limits, &plan); + if (rc) { + printf ("%d\n", rc); + return 1; + } + // FILE *csv = fopen ("motion-plan.csv", "w"); + // mp_plan_write_csv (&plan, 0.001, csv, 1); + // fclose (csv); + // mp_plan_free(&plan); + + printf ("total_length: %lg\n", plan.total_length); + printf ("total_time: %lg\n", plan.total_time); + printf ("v_min: %lg\n", plan.v_min); + printf ("v_max: %lg\n", plan.v_max); + printf ("a_min: %lg\n", plan.a_min); + printf ("a_max: %lg\n", plan.a_max); + printf ("j_min: %lg\n", plan.j_min); + printf ("j_max: %lg\n", plan.j_max); + + struct work_motion_stats stats = measure_work_motion_stats (&path, &plan, 0.001); + + printf ("work_active_time: %lg s\n", stats.active_time); + printf ("work_active_length: %lg mm\n", stats.active_length); + printf ("work_speed_error_max_abs: %lg mm/s\n", stats.speed_error_max_abs); + printf ("work_speed_error_mean_abs: %lg mm/s\n", stats.speed_error_mean_abs); + printf ("work_speed_error_rms: %lg mm/s\n", stats.speed_error_rms); + printf ("work_jerk_abs_integral: %lg mm/s^2\n", stats.jerk_abs_integral); + printf ("work_jerk_abs_mean: %lg mm/s^3\n", stats.jerk_abs_mean); + printf ("work_jerk_abs_max: %lg mm/s^3\n", stats.jerk_abs_max); + + build_overlays (&plan); + visualize (); + + return EXIT_SUCCESS; +} + +/// src/simulate.h ends here -- cgit v1.3.1