From cb070b2d3f2b6e241e3be1b7e0eeb90fc755255f Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Thu, 12 Nov 2026 01:28:13 +0300 Subject: publish --- src/arena.c | 469 +++++++++++++++++++ src/arena.h | 102 ++++ src/compensations.c | 181 +++++++ src/compensations.h | 42 ++ src/critical_points.c | 126 +++++ src/critical_points.h | 35 ++ src/da.h | 68 +++ src/diagnose.c | 123 +++++ src/diagnostics.c | 84 ++++ src/diagnostics.h | 19 + src/generator.c | 95 ++++ src/generator.h | 21 + src/motion_planner.c | 1245 +++++++++++++++++++++++++++++++++++++++++++++++++ src/motion_planner.h | 159 +++++++ src/parse.c | 98 ++++ src/path.c | 145 ++++++ src/path.h | 46 ++ src/rate.c | 134 ++++++ src/rate.h | 40 ++ src/rs274ngc_cst.c | 279 +++++++++++ src/rs274ngc_cst.h | 93 ++++ src/rs274ngc_lexeme.c | 22 + src/rs274ngc_lexeme.h | 75 +++ src/rs274ngc_lexer.c | 147 ++++++ src/rs274ngc_lexer.h | 35 ++ src/rs274ngc_state.c | 455 ++++++++++++++++++ src/rs274ngc_state.h | 204 ++++++++ src/simulate.c | 646 +++++++++++++++++++++++++ src/skywrite.c | 81 ++++ src/sv.h | 26 ++ src/transition.c | 777 ++++++++++++++++++++++++++++++ src/transition.h | 106 +++++ src/utils.c | 135 ++++++ src/utils.h | 132 ++++++ src/vec2.c | 67 +++ src/vec2.h | 18 + 36 files changed, 6530 insertions(+) create mode 100644 src/arena.c create mode 100644 src/arena.h create mode 100644 src/compensations.c create mode 100644 src/compensations.h create mode 100644 src/critical_points.c create mode 100644 src/critical_points.h create mode 100644 src/da.h create mode 100644 src/diagnose.c create mode 100644 src/diagnostics.c create mode 100644 src/diagnostics.h create mode 100644 src/generator.c create mode 100644 src/generator.h create mode 100644 src/motion_planner.c create mode 100644 src/motion_planner.h create mode 100644 src/parse.c create mode 100644 src/path.c create mode 100644 src/path.h create mode 100644 src/rate.c create mode 100644 src/rate.h create mode 100644 src/rs274ngc_cst.c create mode 100644 src/rs274ngc_cst.h create mode 100644 src/rs274ngc_lexeme.c create mode 100644 src/rs274ngc_lexeme.h create mode 100644 src/rs274ngc_lexer.c create mode 100644 src/rs274ngc_lexer.h create mode 100644 src/rs274ngc_state.c create mode 100644 src/rs274ngc_state.h create mode 100644 src/simulate.c create mode 100644 src/skywrite.c create mode 100644 src/sv.h create mode 100644 src/transition.c create mode 100644 src/transition.h create mode 100644 src/utils.c create mode 100644 src/utils.h create mode 100644 src/vec2.c create mode 100644 src/vec2.h (limited to 'src') diff --git a/src/arena.c b/src/arena.c new file mode 100644 index 0000000..461bc7a --- /dev/null +++ b/src/arena.c @@ -0,0 +1,469 @@ +/// src/arena.c --- chunked arena allocator +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#define _GNU_SOURCE // TODO(cmmm): remove hard dependency on GNU extensions +#include +#include + +// TODO(cmmm): rethink alignment in relation to coalescing, it seems +// really hard to get right... Verdict, use obstack (keeping track of +// base) for making sure fields are aligned (by adding extra padding). +// Coalescing stays the same and can still be used without obstack, if +// you know that there won't be need for extra alignment ensuring +// padding + +#include "arena.h" + +#ifndef ARENA_ASSERT +#include +#define ASSERT assert +#define ASSERT_PERROR assert_perror +#else +#define ASSERT ARENA_ASSERT +#endif + +#include +#define MALLOC malloc +#define ALIGNED_ALLOC aligned_alloc +#define FREE free + +#define MAX(A, B) ((A) > (B) ? (A) : (B)) + +// NOTE(cmmm): address of chunk == chunk's end +#define CHUNK_END(CHUNK) ((void *) (CHUNK)) + +static size_t +chunk_size (const struct arena_chunk *chunk) +{ + ASSERT (chunk != NULL); + + return CHUNK_END (chunk) - chunk->begin; +} + +static size_t +chunk_used (struct arena_chunk *chunk) +{ + ASSERT (chunk != NULL); + + return chunk->free - chunk->begin; +} + +static struct arena_chunk * +new_chunk (size_t size, size_t alignment) +{ + ASSERT ((alignment & (alignment + 1)) == 0); + + alignment += 1; + alignment += alignment % sizeof (void *); + + void *chunk_begin = + ALIGNED_ALLOC (alignment, size + sizeof (struct arena_chunk)); + ASSERT (chunk_begin != NULL); + + struct arena_chunk *chunk = chunk_begin + size; + chunk->next = NULL; + chunk->begin = chunk_begin; + chunk->free = chunk_begin; + + return chunk; +} + +static struct arena_chunk * +append_chunk (struct arena *arena, size_t size, size_t alignment) +{ + ASSERT (arena != NULL); + + size = arena->tail != NULL + ? MAX (ARENA_CHUNK_GROWTH_FACTOR*chunk_size (arena->tail), size) + : MAX (ARENA_FIRST_CHUNK_SIZE, size); + + struct arena_chunk *chunk = new_chunk (size, alignment); + + if (arena->tail != NULL) { + arena->tail->next = chunk; + arena->tail = chunk; + } else { + arena->head = chunk; + arena->tail = chunk; + } + + return chunk; +} + +static void * +alignto (void *ptr, size_t alignment) +{ + return (void *) ((ptrdiff_t) (ptr + alignment) & ~alignment); +} + +void * +arena_reserve (struct arena *arena, size_t size, size_t alignment) +{ + ASSERT (arena != NULL); + + if (arena->tail != NULL) { + void *aligned_free = alignto (arena->tail->free, alignment); + if (CHUNK_END (arena->tail) - aligned_free >= (ssize_t) size) { + return aligned_free; + } + } + + // FIXME(cmmm): use arena->tail->next when available + append_chunk (arena, size, alignment); + return alignto (arena->tail->free, alignment); +} + +void * +arena_allocate (struct arena *arena, size_t size, size_t alignment) +{ + ASSERT (arena != NULL); + + void *ptr = arena_reserve (arena, size, alignment); + arena->tail->free = ptr + size; + return ptr; +} + +void * +arena_allocate_fast (struct arena *arena, size_t size, size_t alignment) +{ + ASSERT (arena != NULL); + ASSERT (arena->tail != NULL); + + void *ptr = alignto (arena->tail->free, alignment); + arena->tail->free = ptr + size; + return ptr; +} + +size_t +arena_used (const struct arena *arena) +{ + ASSERT (arena != NULL); + + size_t used = 0; + const struct arena_chunk *chunk; + for (chunk = arena->head; chunk; chunk = chunk->next) + used += chunk_size (chunk); + + return used; +} + +size_t +arena_room (const struct arena *arena, size_t alignment) +{ + ASSERT (arena != NULL); + + if (arena->tail == NULL) + return 0; + + void *aligned_free = alignto (arena->tail->free, alignment); + return CHUNK_END (arena->tail) - aligned_free; +} + +static void * +next_free (const struct arena_chunk *chunk, size_t alignment) +{ + ASSERT (chunk != NULL); + + void *aligned_free = alignto (chunk->free, alignment); + if (aligned_free > CHUNK_END (chunk)) + aligned_free = alignto (chunk->next->begin, alignment); + + return aligned_free; +} + +// REVIEW(cmmm): probably bugged, contract unclear +void * +arena_next_free (const struct arena *a, size_t alignment) +{ + ASSERT (a != NULL); + ASSERT (a->tail != NULL); + + return next_free (a->tail, alignment); +} + +void * +arena_copy (struct arena *a, const void *from, + size_t size, size_t alignment) +{ + ASSERT (a != NULL); + ASSERT (from != NULL); + + void *ptr = arena_allocate (a, size, alignment); + memcpy (ptr, from, size); + return ptr; +} + +void * +arena_copy_fast (struct arena *a, const void *from, + size_t size, size_t alignment) +{ + ASSERT (a != NULL); + ASSERT (from != NULL); + + void *ptr = arena_allocate_fast (a, size, alignment); + memcpy (ptr, from, size); + return ptr; +} + +char * +arena_copy_cstr (struct arena *a, const char *cstr) +{ + ASSERT (a != NULL); + ASSERT (cstr != NULL); + + size_t size = strlen (cstr) + 1; + return arena_copy (a, cstr, size, 1); +} + +void +arena_reset (struct arena *a) +{ + ASSERT (a != NULL); + + if (a->head == NULL) + return; + + a->tail = a->head; + a->head->free = a->head->begin; +} + +void * +arena_pop (struct arena *a, size_t size) +{ + ASSERT (a != NULL); + + // FIXME(cmmm): handle chunk boundaries + a->tail->free -= size; + + ASSERT (a->tail->free >= a->tail->begin); + + return a->tail->free; +} + +struct arena_checkpoint +arena_checkpoint (struct arena *a, size_t alignment) +{ + ASSERT (a != NULL); + + if (a->tail == NULL) + arena_reserve (a, 0, alignment); + + void *aligned_free = alignto (a->tail->free, alignment); + if (aligned_free > CHUNK_END (a->tail)) { + arena_reserve (a, 0, alignment); + aligned_free = alignto (a->tail->free, alignment); + } + + struct arena_checkpoint cp = { + .tail = a->tail, + .free = a->tail->free, + .alignment = alignment, + }; + + a->tail->free = aligned_free; + return cp; +} + +void +arena_rollback_to (struct arena *a, struct arena_checkpoint cp) +{ + ASSERT (a != NULL); + ASSERT (cp.tail != NULL); + ASSERT (cp.free != NULL); + + a->tail = cp.tail; + a->tail->free = cp.free; +} + +size_t +arena_checkpoint_size_from (struct arena_checkpoint cp) +{ + ASSERT (cp.tail != NULL); + ASSERT (cp.free != NULL); + + size_t size = cp.tail->free == cp.free + ? 0 : cp.tail->free - alignto (cp.free, cp.alignment); + for (struct arena_chunk *chunk = cp.tail; chunk; chunk = chunk->next) + size += chunk_size (chunk); + return size; +} + +void * +arena_checkpoint_next_from (struct arena_checkpoint cp) +{ + ASSERT (cp.tail != NULL); + ASSERT (cp.free != NULL); + + void *aligned_free = alignto (cp.free, cp.alignment); + if (aligned_free > CHUNK_END (cp.tail)) + aligned_free = alignto (cp.tail->next->begin, cp.alignment); + + return aligned_free; +} + +void * +arena_coalesce_from (struct arena *a, struct arena_checkpoint cp) +{ + ASSERT (a != NULL); + + if (a->tail == cp.tail) // already coalesced + return cp.free; + + size_t size = arena_checkpoint_size_from (cp); + return arena_coalesce_from_fast (a, cp, size); +} + +void * +arena_coalesce_from_fast (struct arena *a, struct arena_checkpoint cp, + size_t size) +{ + ASSERT (a != NULL); + + if (a->tail == cp.tail) // already coalesced + return cp.free; + + // make new chunk, add old chunks after it + struct arena_chunk *chunk = new_chunk (size, cp.alignment); + chunk->next = cp.free == cp.tail->begin ? cp.tail : cp.tail->next; + + // copy old chunks into new chunk + // BUG(cmmm): check if data actually starts in checkpoints chunk + if (cp.free != cp.tail->free) { + size_t other_size = + alignto (cp.tail->free, cp.alignment) - arena_checkpoint_next_from (cp); + memcpy (chunk->free, cp.free, other_size); + chunk->free += other_size; + } + for (struct arena_chunk *other_chunk = cp.tail->next; + other_chunk; other_chunk = other_chunk->next) { + size_t other_size = chunk_used (other_chunk); + memcpy (chunk->free, other_chunk->begin, other_size); + chunk->free += other_size; + } + + // link in new chunk + for (struct arena_chunk **other_chunk = &a->head; + *other_chunk; other_chunk = &(*other_chunk)->next) { + if (*other_chunk != chunk->next) + continue; + *other_chunk = chunk; + break; + } + + return chunk->begin; +} + +void * +arena_coalesce_from_into (struct arena *a, struct arena_checkpoint cp, + struct arena *into) +{ + size_t size = arena_checkpoint_size_from (cp); + return arena_coalesce_from_into_fast (a, cp, into, size); +} + +// TODO(cmmm): Handle the case where we can just reassign one chunk to +// the other arena. +void * +arena_coalesce_from_into_fast (struct arena *a, struct arena_checkpoint cp, + struct arena *into, size_t size) +{ + ASSERT (a != NULL); + ASSERT (into != NULL); + + void *ptr = arena_allocate (into, size, cp.alignment); + + // copy chunks + void *free = ptr; + void *aligned_src = alignto (cp.free, cp.alignment); + if (aligned_src < cp.tail->free) { + size_t other_size = cp.tail->free - aligned_src; + memcpy (free, aligned_src, other_size); + free += other_size; + } + for (struct arena_chunk *other_chunk = cp.tail->next; + other_chunk != a->tail->next; other_chunk = other_chunk->next) { + size_t other_size = chunk_used (other_chunk); + memcpy (free, other_chunk->begin, other_size); + free += other_size; + } + + arena_rollback_to (a, cp); + return ptr; +} + +void +arena_trim (struct arena *a) +{ + ASSERT (a != NULL); + + if (a->tail == NULL) + return; + + struct arena_chunk *chunk = a->tail->next; + while (chunk) { + struct arena_chunk *next = chunk->next; + FREE (chunk->begin); + chunk = next; + } +} + +void +arena_free (struct arena *a) +{ + ASSERT (a != NULL); + + struct arena_chunk *chunk = a->head; + while (chunk) { + struct arena_chunk *next = chunk->next; + FREE (chunk->begin); + chunk = next; + } + + a->head = NULL; + a->tail = NULL; +} + +#ifndef ARENA_NO_STDIO +#include + +char * +arena_printf (struct arena *a, const char *format, ...) +{ + ASSERT (a != NULL); + ASSERT (format != NULL); + + va_list ap; + va_start (ap, format); + char *cstr = arena_vprintf (a, format, ap); + va_end (ap); + + return cstr; +} + +char * +arena_vprintf (struct arena *a, const char *format, va_list ap) +{ + ASSERT (a != NULL); + ASSERT (format != NULL); + + va_list ap_copy; + va_copy (ap_copy, ap); + int len = vsnprintf (NULL, 0, format, ap_copy); + va_end (ap_copy); + + ASSERT (len >= 0); + char *cstr = ARENA_ALLOCATE_ARRAY (a, len + 1, char); + vsnprintf (cstr, len + 1, format, ap); + + return cstr; +} +#endif + +/// src/arena.c ends here diff --git a/src/arena.h b/src/arena.h new file mode 100644 index 0000000..b87be87 --- /dev/null +++ b/src/arena.h @@ -0,0 +1,102 @@ +/// src/arena.h --- chunked arena allocator +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_ARENA_H +#define INCLUDED_ARENA_H + +#include + +// #define ARENA_NO_STDIO + +#ifndef ARENA_FIRST_CHUNK_SIZE +# define ARENA_FIRST_CHUNK_SIZE (4 << 10) +#endif + +#ifndef ARENA_CHUNK_GROWTH_FACTOR +# define ARENA_CHUNK_GROWTH_FACTOR 2 +#endif + +struct arena_chunk { + struct arena_chunk *next; + void *begin; + void *free; +}; + +struct arena { + struct arena_chunk *head; + struct arena_chunk *tail; +}; + +struct arena_checkpoint { + struct arena_chunk *tail; + void *free; + size_t alignment; +}; + +#ifndef ALIGNOF +# if _STDC_VERSION_ >= 202311L +# define ALIGNOF alignof +# elif _STDC_VERSION_ >= 201112L +# define ALIGNOF _Alignof +# else +# define ALIGNOF(O) offsetof (struct { char _; typeof (O) x; }, x) +# endif +#endif + +#define ARENA_RESERVE( A, T) arena_reserve ((A), sizeof (T), ALIGNOF (T) - 1) +#define ARENA_RESERVE_ARRAY( A, N, T) arena_reserve ((A), (N)*sizeof (T), ALIGNOF (T) - 1) +#define ARENA_ALLOCATE( A, T) arena_allocate ((A), sizeof (T), ALIGNOF (T) - 1) +#define ARENA_ALLOCATE_ARRAY( A, N, T) arena_allocate ((A), (N)*sizeof (T), ALIGNOF (T) - 1) +#define ARENA_ALLOCATE_FAST( A, T) arena_allocate_fast ((A), sizeof (T), ALIGNOF (T) - 1) +#define ARENA_ALLOCATE_ARRAY_FAST(A, N, T) arena_allocate_fast ((A), (N)*sizeof (T), ALIGNOF (T) - 1) +#define ARENA_ZERO( A, T) arena_zero ((A), sizeof (T), ALIGNOF (T) - 1) +#define ARENA_ZERO_ARRAY( A, N, T) arena_zero ((A), (N)*sizeof (T), ALIGNOF (T) - 1) +void *arena_reserve (struct arena *, size_t size, size_t alignment); +void *arena_allocate (struct arena *, size_t size, size_t alignment); +void *arena_allocate_fast (struct arena *, size_t size, size_t alignment); +void *arena_zero (struct arena *, size_t size, size_t alignment); + +size_t arena_used (const struct arena *); +size_t arena_room (const struct arena *, size_t alignment); +void *arena_next_free (const struct arena *, size_t alignment); + +#define ARENA_COPY( A, F ) arena_copy ((A), &(F), sizeof ( F), ALIGNOF ( F) - 1) +#define ARENA_COPY_FAST( A, F ) arena_copy_fast ((A), &(F), sizeof ( F), ALIGNOF ( F) - 1) +#define ARENA_COPY_ARRAY(A, F, N) arena_copy ((A), (F), (N)*sizeof (*F), ALIGNOF (*F) - 1) +void *arena_copy (struct arena *, const void *, size_t size, size_t alignment); +void *arena_copy_fast (struct arena *, const void *, size_t size, size_t alignment); +char *arena_copy_cstr (struct arena *, const char *); + +void arena_reset (struct arena *); + +// NOTE(cmmm): doesn't handle alignments +void *arena_pop (struct arena *, size_t size); + +struct arena_checkpoint arena_checkpoint (struct arena *, size_t alignment); +size_t arena_checkpoint_size_from (struct arena_checkpoint); +void *arena_checkpoint_next_from (struct arena_checkpoint); +void arena_rollback_to (struct arena *, struct arena_checkpoint); +void *arena_coalesce_from (struct arena *, struct arena_checkpoint); +void *arena_coalesce_from_fast (struct arena *, struct arena_checkpoint, size_t size); +void *arena_coalesce_from_into (struct arena *, struct arena_checkpoint, struct arena *); +void *arena_coalesce_from_into_fast (struct arena *, struct arena_checkpoint, struct arena *, size_t size); + +void arena_trim (struct arena *); +void arena_free (struct arena *); + +#ifndef ARENA_NO_STDIO +# include + char *arena_printf (struct arena *, const char *format, ...); + char *arena_vprintf (struct arena *, const char *format, va_list ap); +#endif + +#endif // INCLUDED_ARENA_H + +/// src/arena.h ends here diff --git a/src/compensations.c b/src/compensations.c new file mode 100644 index 0000000..5d87c22 --- /dev/null +++ b/src/compensations.c @@ -0,0 +1,181 @@ +#include "compensations.h" +#include +#include "da.h" +#include "transition.h" + +static double +distance_to_change_speed (double v0, double v1, double vmax, double amax, double jmax) +{ + double dv = fabs (v1 - v0); + if (dv <= 1e-12) + return 0; + + double dv_crit = amax*amax/jmax; + double t = dv <= dv_crit ? 2*sqrt (dv/jmax) : dv/amax + amax/jmax; + + return t*(v0 + v1)/2; +} + +double vmax = 100/1.41421356237; +double amax = 800/1.41421356237; +double jmax = 16000/1.41421356237; + +static struct compensation +synthesize_compensation_loop (const struct critical_point *cp) +{ + struct compensation comp = { + .initial_position = cp->r, + .from = cp->left, + .to = cp->left, + .replace = CR_FROM_END_TO_END, + }; + + // struct tr_transition tr; + // tr_build (&tr, cp->r, cp->r, cp->v_left, cp->v_right, vmax, amax, jmax); + // for (double s = 0.1; s < tr.length; s += 0.1) { + // struct tr_sample sample; + // tr_sample_at_s (&tr, s, &sample); + // DA_APPEND (comp.polyline, sample.r); + // } + + double s0 = distance_to_change_speed (cp->left->f, 0, vmax, amax, jmax); + double s1 = distance_to_change_speed (0, cp->right->f, vmax, amax, jmax); + + struct vec2 out = vec2_add (cp->r, vec2_scale (cp->t_left , s0)); + struct vec2 in = vec2_sub (cp->r, vec2_scale (cp->t_right, s1)); + + DA_APPEND (comp.polyline, out); + DA_APPEND (comp.polyline, in ); + DA_APPEND (comp.polyline, cp->r); + + return comp; +} + +static struct compensation +synthesize_compensation_transfer (const struct critical_point *cp_out, + const struct critical_point *cp_in) +{ + struct compensation comp = { + .initial_position = cp_out->r, + .from = cp_out->right, + .to = cp_in ->left, + .replace = CR_FROM_BEG_TO_END, + }; + + // struct tr_transition tr; + // tr_build (&tr, cp_out->r, cp_in->r, cp_out->v_left, cp_in->v_right, vmax, amax, jmax); + // for (double s = 0.1; s < tr.length; s += 0.1) { + // struct tr_sample sample; + // tr_sample_at_s (&tr, s, &sample); + // DA_APPEND (comp.polyline, sample.r); + // } + + double s0 = distance_to_change_speed (cp_out->left->f, 0, vmax, amax, jmax); + double s1 = distance_to_change_speed (0, cp_in->right->f, vmax, amax, jmax); + + struct vec2 out = vec2_add (cp_out->r, vec2_scale (cp_out->t_left , s0)); + struct vec2 in = vec2_sub (cp_in ->r, vec2_scale (cp_in ->t_right, s1)); + + DA_APPEND (comp.polyline, out); + DA_APPEND (comp.polyline, in ); + DA_APPEND (comp.polyline, cp_in->r); + + return comp; +} + +static struct compensation +synthesize_compensation_in (const struct critical_point *cp) +{ + struct compensation comp = { + .initial_position = cp->s, + .from = cp->left, + .to = cp->left, + .replace = CR_FROM_BEG_TO_END, + }; + + double s = distance_to_change_speed (0, cp->right->f, vmax, amax, jmax); + struct vec2 in = vec2_sub (cp->r, vec2_scale (cp->t_right, s)); + + DA_APPEND (comp.polyline, in); + DA_APPEND (comp.polyline, cp->r); + + return comp; +} + +static struct compensation +synthesize_compensation_beg (const struct critical_point *cp) +{ + struct compensation comp = { + .initial_position = cp->r, + .from = cp->right, + .to = cp->right, + .replace = CR_FROM_BEG_TO_BEG, + }; + + double s = distance_to_change_speed (0, cp->right->f, vmax, amax, jmax); + struct vec2 in = vec2_sub (cp->r, vec2_scale (cp->t_right, s)); + + DA_APPEND (comp.polyline, in); + DA_APPEND (comp.polyline, cp->r); + + return comp; +} + +static struct compensation +synthesize_compensation_end (const struct critical_point *cp) +{ + struct compensation comp = { + .initial_position = cp->r, + .from = cp->left, + .to = cp->left, + .replace = CR_FROM_END_TO_END, + }; + + double s = distance_to_change_speed (cp->left->f, 0, vmax, amax, jmax); + struct vec2 out = vec2_add (cp->r, vec2_scale (cp->t_left, s)); + + DA_APPEND (comp.polyline, out); + + return comp; +} + +struct compensations +synthesize_compensations (const struct critical_points *cps) +{ + struct compensations comps = {0}; + + for (uint32_t i = 0; i < cps->count; ++i) { + struct critical_point *cp = &cps->items[i]; + struct compensation comp = {0}; + switch (cp->type) { + case CPT_IN: { + comp = synthesize_compensation_in (cp); + } break; + case CPT_OUT: { // TRANSFER + i += 1; + if (i == cps->count) { + comp = synthesize_compensation_end (cp); + } else { + struct critical_point *out = cp; + struct critical_point *in = &cps->items[i]; + ASSERT (in->type == CPT_IN); + comp = synthesize_compensation_transfer (out, in); + } + } break; + case CPT_LOOP: { + comp = synthesize_compensation_loop (cp); + } break; + case CPT_BEG: { + comp = synthesize_compensation_beg (cp); + } break; + case CPT_END: { + comp = synthesize_compensation_end (cp); + } break; + default: ASSERT (!"unexpected critical point type"); + } + + DA_APPEND (comps, comp); + } + + return comps; +} diff --git a/src/compensations.h b/src/compensations.h new file mode 100644 index 0000000..f034abc --- /dev/null +++ b/src/compensations.h @@ -0,0 +1,42 @@ +#ifndef INCLUDED_COMPENSATIONS_H +#define INCLUDED_COMPENSATIONS_H + +#include "critical_points.h" + +enum compensation_replace { + CR_FROM_BEG_TO_BEG = 0b00, + CR_FROM_BEG_TO_END = 0b01, + CR_FROM_END_TO_BEG = 0b10, + CR_FROM_END_TO_END = 0b11, +}; + +enum compensation_type { + CT_IN, + CT_OUT, + CT_TRANSFER, + CT_LOOP, +}; + +struct polyline { + struct vec2 *items; + uint32_t count; + uint32_t capacity; +}; + +struct compensation { + struct vec2 initial_position; + struct polyline polyline; + struct path_element *from; + struct path_element *to; + enum compensation_replace replace; +}; + +struct compensations { + struct compensation *items; + uint32_t count; + uint32_t capacity; +}; + +struct compensations synthesize_compensations (const struct critical_points *); + +#endif // INCLUDED_COMPENSATIONS_H diff --git a/src/critical_points.c b/src/critical_points.c new file mode 100644 index 0000000..f11dfe7 --- /dev/null +++ b/src/critical_points.c @@ -0,0 +1,126 @@ +#include "critical_points.h" +#include +#include "da.h" + +static double +angle_sweep (double a0, double a1, int ccw) +{ + double sweep = a1 - a0; + + if (ccw) { + while (sweep <= 0) + sweep += 2*M_PI; + } else { + while (sweep >= 0) + sweep -= 2*M_PI; + } + + // NOTE(cmmm): might need some eps + + return sweep; +} + + +static struct vec2 +tangent_beg (struct vec2 p0, struct path_element *pe) +{ + ASSERT (pe); + + struct vec2 p1 = { pe->x, pe->y }; + if (~pe->flags & PEF_ARC) + return vec2_unit (vec2_sub (p1, p0)); + + struct vec2 c = { pe->i, pe->j }; + double a0 = vec2_angle0 (vec2_sub (p0, c)); + double a1 = vec2_angle0 (vec2_sub (p1, c)); + double sweep = angle_sweep (a0, a1, pe->flags & PEF_CCW); + double sgn = sweep < 0 ? -1 : 1; + double a = a0; + return (struct vec2) { -sgn*sin (a), sgn*cos (a) }; +} + +static struct vec2 +tangent_end (struct vec2 p0, struct path_element *pe) +{ + ASSERT (pe); + + struct vec2 p1 = { pe->x, pe->y }; + if (~pe->flags & PEF_ARC) + return vec2_unit (vec2_sub (p1, p0)); + + struct vec2 c = { pe->i, pe->j }; + double a0 = vec2_angle0 (vec2_sub (p0, c)); + double a1 = vec2_angle0 (vec2_sub (p1, c)); + double sweep = angle_sweep (a0, a1, pe->flags & PEF_CCW); + double sgn = sweep < 0 ? -1 : 1; + double a = a0 + sweep; + return (struct vec2) { -sgn*sin (a), sgn*cos (a) }; +} + +struct critical_points +find_critical_points (const struct path *path) +{ + struct critical_points cps = {0}; + + if (path->count == 0) + return cps; + + struct critical_point cp = { + .right = &path->items[0], + .r = { + .x = path->initial_x, + .y = path->initial_y, + } + }; + if (~cp.right->flags & PEF_TRAVERSING) { + cp.type = CPT_BEG; + cp.t_right = tangent_beg (cp.r, cp.right); + DA_APPEND (cps, cp); + } + + struct vec2 beg = cp.r; + for (uint32_t i = 1; i < path->count; ++i) { + cp.left = cp.right; + cp.right = &path->items[i]; + + cp.s = beg; + cp.r.x = cp.left->x; + cp.r.y = cp.left->y; + + if (cp.left ->flags & PEF_TRAVERSING && + cp.right->flags & PEF_TRAVERSING) { + goto next; + } + + struct vec2 end = { + .x = cp.right->x, + .y = cp.right->y, + }; + + cp.t_left = tangent_end (beg, cp.left ); + cp.t_right = tangent_beg (cp.r, cp.right); + + double min_turn = M_PI/16; + double turn = vec2_angle (cp.t_left, cp.t_right); + + if (cp.left ->flags & PEF_TRAVERSING) cp.type = CPT_IN; + else if (cp.right->flags & PEF_TRAVERSING) cp.type = CPT_OUT; + else if (turn < min_turn) goto next; + else cp.type = CPT_LOOP; + + DA_APPEND (cps, cp); + next: + beg = cp.r; + } + + cp.left = &DA_LAST (*path); + if (~cp.left->flags & PEF_TRAVERSING) { + cp.type = CPT_END; + cp.r.x = cp.left->x; + cp.r.y = cp.left->y; + cp.t_left = tangent_end (beg, cp.left); + DA_APPEND (cps, cp); + } + + return cps; +} diff --git a/src/critical_points.h b/src/critical_points.h new file mode 100644 index 0000000..b7e8cbb --- /dev/null +++ b/src/critical_points.h @@ -0,0 +1,35 @@ +#ifndef INCLUDED_CRITICAL_POINTS_H +#define INCLUDED_CRITICAL_POINTS_H + +#include "path.h" +#include "vec2.h" + +enum critical_point_type { + CPT_IN, + CPT_OUT, + CPT_LOOP, + CPT_BEG, + CPT_END, +}; + +struct critical_point { + enum critical_point_type type; + + struct path_element *left; + struct path_element *right; + + struct vec2 s; + struct vec2 r; + struct vec2 t_left; + struct vec2 t_right; +}; + +struct critical_points { + struct critical_point *items; + uint32_t count; + uint32_t capacity; +}; + +struct critical_points find_critical_points (const struct path *); + +#endif // INCLUDED_CRITICAL_POINTS_H diff --git a/src/da.h b/src/da.h new file mode 100644 index 0000000..8eb0237 --- /dev/null +++ b/src/da.h @@ -0,0 +1,68 @@ +// src/da.h --- Dynamic Array +#ifndef INCLUDED_DA_H +#define INCLUDED_DA_H + +#ifndef DA_REALLOC +void *realloc (void *_ptr, size_t _size); +#define DA_REALLOC realloc +#endif + +#ifndef DA_ASSERT +#include +#define DA_ASSERT assert +#endif + +#ifndef DA_INIT_CAP +#define DA_INIT_CAP 256 +#endif + +#define DA_ENSURE_CAPACITY(DA, COUNT) \ + ({ \ + if ((DA).count + (COUNT) > (DA).capacity) { \ + if ((DA).capacity == 0) \ + (DA).capacity = DA_INIT_CAP; \ + while ((DA).count + (COUNT) > (DA).capacity) \ + (DA).capacity *= 2; \ + (DA).items = DA_REALLOC ((DA).items, \ + (DA).capacity*sizeof (*(DA).items)); \ + DA_ASSERT((DA).items); \ + } \ + }) + +#define DA_SHRINK(DA) \ + ({ \ + (DA).capacity = (DA).count; \ + (DA).items = REALLOC((DA).items, \ + (DA).capacity * \ + sizeof (*(DA).items)); \ + DA_ASSERT((DA).items); \ + }) + +#define DA_APPEND(DA, ITEM) \ + ({ \ + DA_ENSURE_CAPACITY((DA), 1); \ + (DA).items[(DA).count++] = (ITEM); \ + }) + +#define DA_APPEND_MANY(DA, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DA_ENSURE_CAPACITY ((DA), (NEW_ITEMS_COUNT)); \ + memcpy ((DA).items + (DA).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DA).items)); \ + (DA).count += (NEW_ITEMS_COUNT); \ + }) + +#define DA_FIRST(DA) (DA).items[0] +#define DA_LAST(DA) (DA).items[(DA).count - 1] + +#define DA_RESET(DA) ({ (DA).count = 0; }) + +#define DA_FREE(DA) (void) DA_REALLOC ((DA).items, 0) + +#define DA_FOR_EACH(ITEM, DA) for ( \ + typeof ((DA).items) ITEM = (DA).items; \ + ITEM < (DA).items + (DA).count; ++ITEM) + +#endif // INCLUDED_DA_H + +// src/da.h ends here diff --git a/src/diagnose.c b/src/diagnose.c new file mode 100644 index 0000000..041019a --- /dev/null +++ b/src/diagnose.c @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "rs274ngc_lexer.h" +#include "rs274ngc_cst.h" +#include "path.h" +#include "motion_planner.h" +#include "diagnostics.h" + +static void +usage (const char *progname) +{ + fprintf (stderr, "usage: %s INPUT.ngc OUTPUT.csv [dt]\n", progname); +} + +static double +parse_dt (const char *s) +{ + char *end = NULL; + errno = 0; + double dt = strtod (s, &end); + + if (errno || end == s || *end != '\0' || !(dt > 0.0) || !isfinite (dt)) { + fprintf (stderr, "invalid dt: %s\n", s); + exit (EXIT_FAILURE); + } + + return dt; +} + +static struct path +read_path_from_file (struct arena *a, + struct arena *t, + const char *filename) +{ + int fd = open (filename, O_RDONLY); + if (fd < 0) { + perror (filename); + exit (EXIT_FAILURE); + } + + struct sv rs274ngc = read_until_eof (a, 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, + }; + + return build_path (parser); +} + +int +main (int argc, char **argv) +{ + progname = argv[0]; + + if (argc != 3 && argc != 4) { + usage (argv[0]); + return EXIT_FAILURE; + } + + const char *input_filename = argv[1]; + const char *output_filename = argv[2]; + double dt = argc == 4 ? parse_dt (argv[3]) : 0.001; + + struct arena a = {0}; + struct arena t = {0}; + + struct path path = read_path_from_file (&a, &t, input_filename); + if (path.count == 0u) { + fprintf (stderr, "%s: empty path\n", input_filename); + return EXIT_FAILURE; + } + + struct mp_limits limits = { + .vmax = 80, + .rapid_vmax = 125, + .amax = 800, + .jmax = 16000, + .corner_tol = .05, + .min_segment_len = 1e-6, + .default_feed = 50, + + .straight_angle_tol = 1e-5, + .stop_angle = M_PI/16, + .corner_speed_deadband = .02, + + .curvature_blend_len = 0.05, + }; + + struct motion_plan plan = {0}; + int rc = mp_plan_build (&path, 0.0, 0.0, &limits, &plan); + if (rc != MP_OK) { + fprintf (stderr, "%s: mp_plan_build failed: %d\n", input_filename, rc); + return EXIT_FAILURE; + } + + FILE *csv = fopen (output_filename, "w"); + if (!csv) { + perror (output_filename); + mp_plan_free (&plan); + return EXIT_FAILURE; + } + + motion_diag_write_csv (&plan, dt, csv, 1); + fclose (csv); + + fprintf (stderr, "%s: total_time=%g s, total_length=%g mm, dt=%g s\n", + output_filename, plan.total_time, plan.total_length, dt); + + mp_plan_free (&plan); + return EXIT_SUCCESS; +} diff --git a/src/diagnostics.c b/src/diagnostics.c new file mode 100644 index 0000000..458a0ad --- /dev/null +++ b/src/diagnostics.c @@ -0,0 +1,84 @@ +#include "diagnostics.h" + +#include +#include + +static double +diag_segment_v_cmd (const struct motion_plan *plan, + const struct mp_sample *sample) +{ + if (!plan || !sample) + return 0.0; + + if (sample->segment_index >= plan->segment_count) + return 0.0; + + return plan->segments[sample->segment_index].v_nominal; +} + +static void +diag_write_sample (const struct motion_plan *plan, + const struct mp_sample *sample, + FILE *out) +{ + int is_traverse = (sample->source_flags & PEF_TRAVERSING) != 0; + int is_work = !is_traverse; + + double v_cmd = diag_segment_v_cmd (plan, sample); + + /* На G0 ошибка скорости по определению равна нулю. */ + double v_ref = is_traverse ? sample->v : v_cmd; + double v_err = sample->v - v_ref; + double v_err_abs = fabs (v_err); + + fprintf (out, + "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f," + "%.9f,%.9f,%.9f,%.9f,%d,%d,%u,%u,%d\n", + sample->t, + sample->s, + sample->p.x, + sample->p.y, + sample->v, + v_cmd, + v_ref, + v_err, + v_err_abs, + sample->j_t, + sample->j_abs, + sample->jerk.x, + sample->jerk.y, + is_work, + is_traverse, + sample->segment_index, + sample->source_index, + sample->source_flags); +} + +void +motion_diag_write_csv (const struct motion_plan *plan, + double dt, + FILE *out, + int write_header) +{ + if (!plan || !out || !(dt > 0.0) || !isfinite (dt)) + return; + + if (write_header) { + fputs ("t,s,x,y,v,v_cmd,v_ref,v_err,v_err_abs," + "j_t,j_abs,jx,jy,is_work,is_traverse," + "segment_index,source_index,source_flags\n", out); + } + + if (plan->segment_count == 0u) + return; + + for (double t = 0.0; t < plan->total_time; t += dt) { + struct mp_sample sample; + mp_plan_sample (plan, t, &sample); + diag_write_sample (plan, &sample, out); + } + + struct mp_sample last; + mp_plan_sample (plan, plan->total_time, &last); + diag_write_sample (plan, &last, out); +} diff --git a/src/diagnostics.h b/src/diagnostics.h new file mode 100644 index 0000000..501abe6 --- /dev/null +++ b/src/diagnostics.h @@ -0,0 +1,19 @@ +#ifndef INCLUDED_DIAGNOSTICS_H +#define INCLUDED_DIAGNOSTICS_H + +#include +#include "motion_planner.h" + +/* + * CSV-выгрузка кинематической диагностики по времени. + * + * Скоростная ошибка считается только на рабочих участках. Для G0 она + * принудительно равна 0, потому что rapid-перемещения не задают качество + * обработки. + */ +void motion_diag_write_csv (const struct motion_plan *plan, + double dt, + FILE *out, + int write_header); + +#endif // INCLUDED_DIAGNOSTICS_H diff --git a/src/generator.c b/src/generator.c new file mode 100644 index 0000000..ac98b5b --- /dev/null +++ b/src/generator.c @@ -0,0 +1,95 @@ +#include "generator.h" +#include "da.h" +#include + +static struct replacement +generate_replacement (struct arena *a, const struct compensation *comp) +{ + ASSERT (comp->polyline.count > 0); + + struct replacement rep = {0}; + + int len = 1; + for (uint32_t i = 0; i < comp->polyline.count; ++i) { + struct vec2 to = comp->polyline.items[i]; + int n = snprintf (NULL, 0, "G0 X%f Y%f\n", to.x, to.y); + len += n; + } + + char *head = arena_allocate (a, len, 1); + rep.new.beg = head; + rep.new.end = head + len - 1; + + for (uint32_t i = 0; i < comp->polyline.count; ++i) { + struct vec2 to = comp->polyline.items[i]; + int n = snprintf (head, len, "G0 X%f Y%f\n", to.x, to.y); + head += n; + len -= n; + } + + switch (comp->replace) { + case CR_FROM_BEG_TO_BEG: { + rep.old.beg = comp->from->line.beg; + rep.old.end = comp->to ->line.beg; + } break; + case CR_FROM_BEG_TO_END: { + rep.old.beg = comp->from->line.beg; + rep.old.end = comp->to ->line.end; + } break; + case CR_FROM_END_TO_BEG: { + rep.old.beg = comp->from->line.end; + rep.old.end = comp->to ->line.beg; + } break; + case CR_FROM_END_TO_END: { + rep.old.beg = comp->from->line.end; + rep.old.end = comp->to ->line.end; + } break; + } + + return rep; +} + +struct replacements +generate_replacements (struct arena *a, const struct compensations *comps) +{ + struct replacements reps = {0}; + + for (uint32_t i = 0; i < comps->count; ++i) { + const struct compensation *comp = &comps->items[i]; + DA_APPEND (reps, generate_replacement (a, comp)); + } + + return reps; +} + +void +write_code_with_replacements (int fd, struct sv orig, + const struct replacements *reps) +{ + const char *head = orig.beg; + for (uint32_t i = 0; i < reps->count; ++i) { + const struct replacement *rep = &reps->items[i]; + struct sv before = { + .beg = head, + .end = rep->old.beg, + }; + head = rep->old.end; + // puts ("(v orig --)"); + printf (SV_FMT, SV_FMTA (before)); + // puts ("(^ orig --)"); + // puts ("(v old --)"); + // printf (SV_FMT, SV_FMTA (rep->old)); + // puts ("(^ old --)"); + // puts ("(v new --)"); + printf (SV_FMT, SV_FMTA (rep->new)); + // puts ("(^ new --)"); + } + + struct sv before = { + .beg = head, + .end = orig.end, + }; + // puts ("(v last orig --)"); + printf (SV_FMT, SV_FMTA (before)); + // puts ("(^ last orig --)"); +} diff --git a/src/generator.h b/src/generator.h new file mode 100644 index 0000000..cab8687 --- /dev/null +++ b/src/generator.h @@ -0,0 +1,21 @@ +#ifndef INCLUDED_GENERATOR_H +#define INCLUDED_GENERATOR_H + +#include "compensations.h" +#include "arena.h" + +struct replacement { + struct sv old; // replace this + struct sv new; // with this +}; + +struct replacements { + struct replacement *items; + uint32_t count; + uint32_t capacity; +}; + +struct replacements generate_replacements (struct arena *, const struct compensations *); +void write_code_with_replacements (int fd, struct sv original, const struct replacements *); + +#endif // INCLUDED_GENERATOR_H diff --git a/src/motion_planner.c b/src/motion_planner.c new file mode 100644 index 0000000..313e3e9 --- /dev/null +++ b/src/motion_planner.c @@ -0,0 +1,1245 @@ +#include "motion_planner.h" + +#include +#include +#include +#include + +static double +mp_clamp (double x, double lo, double hi) +{ + return x < lo ? lo : (x > hi ? hi : x); +} + +static int +mp_finite_pos (double x) +{ + return isfinite (x) && x > 0.0; +} + +static int +mp_limits_valid (const struct mp_limits *l) +{ + return l && + mp_finite_pos (l->vmax) && + mp_finite_pos (l->amax) && + mp_finite_pos (l->jmax) && + isfinite (l->rapid_vmax) && + isfinite (l->corner_tol) && + isfinite (l->min_segment_len) && + mp_finite_pos (l->default_feed) && + isfinite (l->straight_angle_tol) && + isfinite (l->stop_angle) && + isfinite (l->corner_speed_deadband) && + isfinite (l->curvature_blend_len); +} + +static double +mp_rapid_vmax (const struct mp_limits *l) +{ + return l->rapid_vmax > 0.0 ? l->rapid_vmax : l->vmax; +} + +static double +mp_straight_angle_tol (const struct mp_limits *l) +{ + return l->straight_angle_tol > 0.0 ? l->straight_angle_tol : 1e-5; +} + +static double +mp_stop_angle (const struct mp_limits *l) +{ + if (l->stop_angle > 0.0 && l->stop_angle < M_PI) + return l->stop_angle; + + return M_PI; +} + +static double +mp_corner_deadband (const struct mp_limits *l) +{ + return l->corner_speed_deadband > 0.0 ? l->corner_speed_deadband : 0.0; +} + +static double +mp_min_segment_len (const struct mp_limits *l) +{ + return l->min_segment_len > 0.0 ? l->min_segment_len : 1e-8; +} + +static struct mp_vec2 +mp_vec2 (double x, double y) +{ + struct mp_vec2 v; + v.x = x; + v.y = y; + return v; +} + +static struct mp_vec2 +mp_vec2_add (struct mp_vec2 a, struct mp_vec2 b) +{ + return mp_vec2 (a.x + b.x, a.y + b.y); +} + +static struct mp_vec2 +mp_vec2_sub (struct mp_vec2 a, struct mp_vec2 b) +{ + return mp_vec2 (a.x - b.x, a.y - b.y); +} + +static struct mp_vec2 +mp_vec2_mul (struct mp_vec2 a, double k) +{ + return mp_vec2 (a.x*k, a.y*k); +} + +static double +mp_vec2_dot (struct mp_vec2 a, struct mp_vec2 b) +{ + return a.x*b.x + a.y*b.y; +} + +static double +mp_vec2_cross (struct mp_vec2 a, struct mp_vec2 b) +{ + return a.x*b.y - a.y*b.x; +} + +static double +mp_vec2_len (struct mp_vec2 a) +{ + return hypot (a.x, a.y); +} + +static double +mp_vec2_dist (struct mp_vec2 a, struct mp_vec2 b) +{ + return mp_vec2_len (mp_vec2_sub (a, b)); +} + +static struct mp_vec2 +mp_vec2_unit (struct mp_vec2 a) +{ + double n = mp_vec2_len (a); + + if (!(n > MP_EPS)) + return mp_vec2 (1.0, 0.0); + + return mp_vec2_mul (a, 1.0/n); +} + +static int +mp_reserve_segments (struct motion_plan *p, uint32_t want) +{ + if (p->segment_capacity >= want) + return MP_OK; + + uint32_t cap = p->segment_capacity ? p->segment_capacity : 16u; + while (cap < want) + cap *= 2u; + + void *mem = realloc (p->segments, (size_t) cap * sizeof p->segments[0]); + if (!mem) + return MP_ERR_ALLOC; + + p->segments = (struct mp_segment *) mem; + p->segment_capacity = cap; + return MP_OK; +} + +static int +mp_reserve_nodes (struct motion_plan *p, uint32_t want) +{ + if (p->node_capacity >= want) + return MP_OK; + + uint32_t cap = p->node_capacity ? p->node_capacity : 16u; + while (cap < want) + cap *= 2u; + + void *mem = realloc (p->nodes, (size_t) cap * sizeof p->nodes[0]); + if (!mem) + return MP_ERR_ALLOC; + + p->nodes = (struct mp_node *) mem; + p->node_capacity = cap; + return MP_OK; +} + +static int +mp_reserve_phases (struct motion_plan *p, uint32_t want) +{ + if (p->phase_capacity >= want) + return MP_OK; + + uint32_t cap = p->phase_capacity ? p->phase_capacity : 64u; + while (cap < want) + cap *= 2u; + + void *mem = realloc (p->phases, (size_t) cap * sizeof p->phases[0]); + if (!mem) + return MP_ERR_ALLOC; + + p->phases = (struct mp_phase *) mem; + p->phase_capacity = cap; + return MP_OK; +} + +void +mp_plan_init (struct motion_plan *plan) +{ + if (plan) + memset (plan, 0, sizeof *plan); +} + +void +mp_plan_free (struct motion_plan *plan) +{ + if (!plan) + return; + + free (plan->segments); + free (plan->nodes); + free (plan->phases); + + memset (plan, 0, sizeof *plan); +} + +static void +mp_arc_sweep (struct mp_vec2 p0, + struct mp_vec2 p1, + struct mp_vec2 c, + int ccw, + double *a0_out, + double *sweep_out, + double *r_out) +{ + double r0 = mp_vec2_dist (p0, c); + double r1 = mp_vec2_dist (p1, c); + double a0 = atan2 (p0.y - c.y, p0.x - c.x); + double a1 = atan2 (p1.y - c.y, p1.x - c.x); + double sweep = a1 - a0; + + if (ccw) { + while (sweep <= 0) + sweep += 2*M_PI; + } else { + while (sweep >= 0) + sweep -= 2*M_PI; + } + + if (r0 > MP_EPS && mp_vec2_dist (p0, p1) <= 1e-7*r0) + sweep = ccw ? 2*M_PI : -2*M_PI; + + *a0_out = a0; + *sweep_out = sweep; + *r_out = (r0 + r1)/2; +} + +static struct mp_vec2 +mp_tangent_start (const struct mp_segment *g) +{ + if (g->type == MP_GEOM_LINE) + return mp_vec2_unit (mp_vec2_sub (g->p1, g->p0)); + + double sgn = g->sweep >= 0 ? 1 : -1; + double a = g->a0; + + return mp_vec2 (-sgn*sin (a), sgn*cos (a)); +} + +static struct mp_vec2 +mp_tangent_end (const struct mp_segment *g) +{ + if (g->type == MP_GEOM_LINE) + return mp_vec2_unit (mp_vec2_sub (g->p1, g->p0)); + + double sgn = g->sweep >= 0 ? 1 : -1; + double a = g->a0 + g->sweep; + + return mp_vec2 (-sgn*sin (a), sgn*cos (a)); +} + +static void +mp_geom_eval_frame (const struct mp_segment *g, double s, + struct mp_vec2 *pos_out, + struct mp_vec2 *tangent_out, + struct mp_vec2 *normal_out, + double *kappa_out) +{ + s = mp_clamp (s, 0.0, g->length); + + if (g->type == MP_GEOM_ARC) { + double u = g->length > MP_EPS ? s/g->length : 1.0; + double a = g->a0 + g->sweep*u; + double ca = cos (a); + double sa = sin (a); + double sgn = g->sweep >= 0.0 ? 1.0 : -1.0; + + *pos_out = mp_vec2 (g->c.x + g->r*ca, + g->c.y + g->r*sa); + *tangent_out = mp_vec2 (-sgn*sa, sgn*ca); + *normal_out = mp_vec2 (-ca, -sa); + *kappa_out = g->r > MP_EPS ? 1.0/g->r : 0.0; + return; + } + + double u = g->length > MP_EPS ? s/g->length : 1.0; + struct mp_vec2 d = mp_vec2_sub (g->p1, g->p0); + struct mp_vec2 t = mp_vec2_unit (d); + + *pos_out = mp_vec2 (g->p0.x + d.x*u, + g->p0.y + d.y*u); + *tangent_out = t; + *normal_out = mp_vec2 (-t.y, t.x); + *kappa_out = 0.0; +} + + +static double +mp_smoothstep (double x) +{ + x = mp_clamp (x, 0.0, 1.0); + return x*x*(3.0 - 2.0*x); +} + +static double +mp_segment_curvature (const struct mp_segment *g) +{ + if (g && g->type == MP_GEOM_ARC && g->r > MP_EPS) + return 1.0/g->r; + + return 0.0; +} + +static int +mp_node_allows_curvature_blend (const struct mp_node *node) +{ + if (!node) + return 0; + + if (node->flags & (MP_NODE_GEOM_GAP | MP_NODE_HARD_STOP)) + return 0; + + return 1; +} + +static double +mp_effective_kappa (const struct motion_plan *plan, + uint32_t segment_index, + double local_s, + double kappa_geom) +{ + if (!plan || !(plan->curvature_blend_len > 0.0) || !isfinite (plan->curvature_blend_len)) + return kappa_geom; + + if (segment_index >= plan->segment_count) + return kappa_geom; + + const struct mp_segment *cur = &plan->segments[segment_index]; + double kappa = kappa_geom; + double blend = plan->curvature_blend_len; + + if (segment_index > 0u && local_s < blend) { + const struct mp_node *node = &plan->nodes[segment_index]; + + if (mp_node_allows_curvature_blend (node)) { + const struct mp_segment *prev = &plan->segments[segment_index - 1u]; + double b = fmin (blend, 0.5*fmin (prev->length, cur->length)); + + if (b > MP_EPS && local_s < b) { + double k_prev = mp_segment_curvature (prev); + double w = mp_smoothstep (local_s/b); + kappa = (1.0 - w)*k_prev + w*kappa; + } + } + } + + if (segment_index + 1u < plan->segment_count && cur->length - local_s < blend) { + const struct mp_node *node = &plan->nodes[segment_index + 1u]; + + if (mp_node_allows_curvature_blend (node)) { + const struct mp_segment *next = &plan->segments[segment_index + 1u]; + double b = fmin (blend, 0.5*fmin (cur->length, next->length)); + double d = cur->length - local_s; + + if (b > MP_EPS && d < b) { + double k_next = mp_segment_curvature (next); + double w = mp_smoothstep (1.0 - d/b); + kappa = (1.0 - w)*kappa + w*k_next; + } + } + } + + return kappa; +} + +static double +mp_segment_speed_cap (const struct mp_segment *g, + const struct mp_limits *l, + double v) +{ + if (g->type == MP_GEOM_ARC && g->r > MP_EPS) { + double vc = sqrt (l->amax * g->r); + if (vc > 0.0 && isfinite (vc)) + v = fmin (v, vc); + } + + return v; +} + +static int +mp_push_segment (struct motion_plan *p, const struct mp_segment *g) +{ + int rc = mp_reserve_segments (p, p->segment_count + 1u); + if (rc != MP_OK) + return rc; + + p->segments[p->segment_count++] = *g; + return MP_OK; +} + +static int +mp_build_segments (const struct path *path, + double initial_x, + double initial_y, + const struct mp_limits *limits, + struct motion_plan *out) +{ + struct mp_vec2 p0 = mp_vec2 (initial_x, initial_y); + double min_len = mp_min_segment_len (limits); + double rapid = mp_rapid_vmax (limits); + + if (!(rapid > 0.0) || !isfinite (rapid)) + return MP_ERR_LIMITS; + + for (uint32_t i = 0; i < path->count; ++i) { + const struct path_element *el = &path->items[i]; + struct mp_vec2 p1 = mp_vec2 (el->x, el->y); + + struct mp_segment g; + memset (&g, 0, sizeof g); + + g.source_index = i; + g.flags = el->flags; + g.p0 = p0; + g.p1 = p1; + + if (el->flags & PEF_ARC) { + g.type = MP_GEOM_ARC; + g.c = mp_vec2 (el->i, el->j); + mp_arc_sweep (g.p0, g.p1, g.c, el->flags & PEF_CCW, &g.a0, &g.sweep, &g.r); + + if (!(g.r > MP_EPS) || !isfinite (g.r) || !isfinite (g.sweep)) + return MP_ERR_GEOMETRY; + + g.length = fabs (g.sweep) * g.r; + } else { + g.type = MP_GEOM_LINE; + g.length = mp_vec2_dist (g.p0, g.p1); + } + + p0 = p1; + + if (!(g.length > min_len)) + continue; + + if (el->flags & PEF_TRAVERSING) { + g.feed = rapid; + g.v_nominal = rapid; + } else { + g.feed = el->f > 0.0 ? el->f : limits->default_feed; + g.v_nominal = fmin (g.feed, limits->vmax); + } + + g.v_nominal = mp_segment_speed_cap (&g, limits, g.v_nominal); + + if (!(g.v_nominal > 0.0) || !isfinite (g.v_nominal)) + return MP_ERR_LIMITS; + + g.s_begin = out->total_length; + g.s_end = g.s_begin + g.length; + out->total_length = g.s_end; + + int rc = mp_push_segment (out, &g); + if (rc != MP_OK) + return rc; + } + + return MP_OK; +} + +static double +mp_junction_speed (const struct mp_segment *left, + const struct mp_segment *right, + const struct mp_limits *limits, + double *theta_out, + uint32_t *flags_out) +{ + double cap = fmin (left->v_nominal, right->v_nominal); + uint32_t flags = 0; + + if (!(cap > 0.0) || !isfinite (cap)) { + if (theta_out) *theta_out = 0.0; + if (flags_out) *flags_out = MP_NODE_HARD_STOP; + return 0.0; + } + + if (mp_vec2_dist (left->p1, right->p0) > 1e-5) { + if (theta_out) *theta_out = 0.0; + if (flags_out) *flags_out = MP_NODE_GEOM_GAP | MP_NODE_HARD_STOP; + return 0.0; + } + + struct mp_vec2 t0 = mp_tangent_end (left); + struct mp_vec2 t1 = mp_tangent_start (right); + double dot = mp_clamp (mp_vec2_dot (t0, t1), -1.0, 1.0); + double cross = mp_vec2_cross (t0, t1); + double theta = fabs (atan2 (cross, dot)); + + if (theta_out) + *theta_out = theta; + + if (theta <= mp_straight_angle_tol (limits)) { + flags = MP_NODE_STRAIGHT; + if (flags_out) *flags_out = flags; + return cap; + } + + if (theta >= mp_stop_angle (limits)) { + flags = MP_NODE_HARD_STOP | MP_NODE_CORNER_LIMIT; + if (flags_out) *flags_out = flags; + return 0; + } + + if (!(limits->corner_tol > 0.0)) { + flags = MP_NODE_HARD_STOP | MP_NODE_CORNER_LIMIT; + if (flags_out) *flags_out = flags; + return 0; + } + + double c = cos (theta/2); + double denom = 1 - c; + + if (denom <= MP_EPS) { + flags = MP_NODE_STRAIGHT; + if (flags_out) *flags_out = flags; + return cap; + } + + double r_virtual = limits->corner_tol*c/denom; + if (!(r_virtual > 0.0) || !isfinite (r_virtual)) { + flags = MP_NODE_HARD_STOP | MP_NODE_CORNER_LIMIT; + if (flags_out) *flags_out = flags; + return 0.0; + } + + double vj = sqrt (limits->amax * r_virtual); + double db = mp_corner_deadband (limits); + + if (vj >= cap*(1 - db)) { + flags = MP_NODE_STRAIGHT; + if (flags_out) *flags_out = flags; + return cap; + } + + flags = MP_NODE_CORNER_LIMIT; + if (flags_out) *flags_out = flags; + return cap; + return fmin (cap, vj); +} + +static int +mp_build_nodes (struct motion_plan *out, const struct mp_limits *limits) +{ + uint32_t nseg = out->segment_count; + int rc = mp_reserve_nodes (out, nseg + 1u); + if (rc != MP_OK) + return rc; + + out->node_count = nseg + 1u; + memset (out->nodes, 0, (size_t) out->node_count * sizeof out->nodes[0]); + + out->nodes[0].s = 0.0; + out->nodes[0].v_cap = 0.0; + out->nodes[0].v = 0.0; + out->nodes[0].flags = MP_NODE_START | MP_NODE_HARD_STOP | MP_NODE_KNOT; + + for (uint32_t i = 1; i < nseg; ++i) { + struct mp_node *node = &out->nodes[i]; + const struct mp_segment *left = &out->segments[i - 1u]; + const struct mp_segment *right = &out->segments[i]; + + uint32_t flags = 0; + double theta = 0.0; + double vcap = mp_junction_speed (left, right, limits, &theta, &flags); + + if (fabs (left->v_nominal - right->v_nominal) > 1e-8*fmax (1.0, fmax (left->v_nominal, right->v_nominal))) + flags |= MP_NODE_SPEED_CHANGE; + + node->s = left->s_end; + node->v_cap = vcap; + node->v = vcap; + node->theta = theta; + node->flags = flags; + } + + out->nodes[nseg].s = out->total_length; + out->nodes[nseg].v_cap = 0.0; + out->nodes[nseg].v = 0.0; + out->nodes[nseg].flags = MP_NODE_END | MP_NODE_HARD_STOP | MP_NODE_KNOT; + + return MP_OK; +} + +static double +mp_speed_change_distance_scurve (double v_from, + double v_to, + double amax, + double jmax) +{ + if (v_to <= v_from + MP_EPS) + return 0.0; + + double dv = v_to - v_from; + double dv_full = amax*amax/jmax; + double duration; + + if (dv <= dv_full) { + double tj = sqrt (dv/jmax); + duration = 2.0*tj; + } else { + double tj = amax/jmax; + double tc = dv/amax - tj; + duration = 2.0*tj + tc; + } + + return 0.5*(v_from + v_to)*duration; +} + +static double +mp_reachable_speed (double v0, + double length, + const struct mp_limits *limits, + double vcap) +{ + if (vcap <= v0) + return vcap; + + if (mp_speed_change_distance_scurve (v0, vcap, limits->amax, limits->jmax) <= length) + return vcap; + + double lo = v0; + double hi = vcap; + + for (int k = 0; k < 80; ++k) { + double mid = 0.5*(lo + hi); + double s = mp_speed_change_distance_scurve (v0, mid, limits->amax, limits->jmax); + + if (s <= length) + lo = mid; + else + hi = mid; + } + + return lo; +} + +static void +mp_apply_speed_lookahead (struct motion_plan *out, + const struct mp_limits *limits) +{ + uint32_t nseg = out->segment_count; + + for (uint32_t i = nseg; i-- > 0u;) { + double cap = out->segments[i].v_nominal; + double allowed = mp_reachable_speed (out->nodes[i + 1u].v, + out->segments[i].length, + limits, + cap); + if (out->nodes[i].v > allowed) + out->nodes[i].v = allowed; + } + + for (uint32_t i = 0; i < nseg; ++i) { + double cap = out->segments[i].v_nominal; + double allowed = mp_reachable_speed (out->nodes[i].v, + out->segments[i].length, + limits, + cap); + if (out->nodes[i + 1u].v > allowed) + out->nodes[i + 1u].v = allowed; + } +} + +static int +mp_node_should_be_knot (const struct motion_plan *p, + uint32_t node_index, + const struct mp_limits *limits) +{ + if (node_index == 0u || node_index + 1u == p->node_count) + return 1; + + const struct mp_node *node = &p->nodes[node_index]; + const struct mp_segment *left = &p->segments[node_index - 1u]; + const struct mp_segment *right = &p->segments[node_index]; + + if (node->flags & (MP_NODE_GEOM_GAP | MP_NODE_HARD_STOP)) + return 1; + + double cap = fmin (left->v_nominal, right->v_nominal); + double db = mp_corner_deadband (limits); + + if (node->v_cap < cap * (1.0 - db)) + return 1; + + return 0; +} + +static void +mp_mark_knots (struct motion_plan *p, const struct mp_limits *limits) +{ + for (uint32_t i = 0; i < p->node_count; ++i) { + if (mp_node_should_be_knot (p, i, limits)) + p->nodes[i].flags |= MP_NODE_KNOT; + else + p->nodes[i].flags &= ~((uint32_t) MP_NODE_KNOT); + } +} + +static double +mp_interval_vcap (const struct motion_plan *p, + uint32_t node_begin, + uint32_t node_end) +{ + double vcap = DBL_MAX; + + for (uint32_t i = node_begin; i < node_end; ++i) + vcap = fmin (vcap, p->segments[i].v_nominal); + + if (!(vcap < DBL_MAX)) + return 0.0; + + return vcap; +} + +static int +mp_append_phase (struct motion_plan *p, + double dt, + double a0, + double j, + double *s_cursor, + double *t_cursor, + double *v_cursor, + double *a_cursor) +{ + if (dt <= 1e-12) + return MP_OK; + + if (!isfinite (dt) || !isfinite (a0) || !isfinite (j)) + return MP_ERR_PROFILE; + + int rc = mp_reserve_phases (p, p->phase_count + 1u); + if (rc != MP_OK) + return rc; + + struct mp_phase *ph = &p->phases[p->phase_count++]; + + ph->t_begin = *t_cursor; + ph->dt = dt; + ph->s_begin = *s_cursor; + ph->v0 = *v_cursor; + ph->a0 = a0; + ph->j = j; + + double dt2 = dt*dt; + double dt3 = dt2*dt; + + double s1 = *s_cursor + (*v_cursor)*dt + 0.5*a0*dt2 + (j*dt3)/6.0; + double v1 = *v_cursor + a0*dt + 0.5*j*dt2; + double a1 = a0 + j*dt; + + ph->s_end = s1; + + *s_cursor = s1; + *t_cursor += dt; + *v_cursor = v1; + *a_cursor = a1; + + p->total_time = *t_cursor; + + p->v_min = fmin (p->v_min, fmin (ph->v0, v1)); + p->v_max = fmax (p->v_max, fmax (ph->v0, v1)); + + p->a_min = fmin (p->a_min, fmin (a0, a1)); + p->a_max = fmax (p->a_max, fmax (a0, a1)); + + p->j_min = fmin (p->j_min, j); + p->j_max = fmax (p->j_max, j); + + return MP_OK; +} + +static int +mp_append_speed_change_scurve (struct motion_plan *p, + double v_from, + double v_to, + const struct mp_limits *limits, + double *s_cursor, + double *t_cursor, + double *v_cursor, + double *a_cursor) +{ + double dv = fabs (v_to - v_from); + + if (dv <= 1e-10) { + *v_cursor = v_to; + *a_cursor = 0.0; + return MP_OK; + } + + double sign = v_to > v_from ? 1.0 : -1.0; + double dv_full = limits->amax*limits->amax/limits->jmax; + + if (dv <= dv_full) { + double tj = sqrt (dv/limits->jmax); + double ap = limits->jmax*tj; + + int rc = mp_append_phase (p, tj, 0.0, sign*limits->jmax, + s_cursor, t_cursor, v_cursor, a_cursor); + if (rc != MP_OK) return rc; + + return mp_append_phase (p, tj, sign*ap, -sign*limits->jmax, + s_cursor, t_cursor, v_cursor, a_cursor); + } + + double tj = limits->amax/limits->jmax; + double tc = dv/limits->amax - tj; + + int rc = mp_append_phase (p, tj, 0.0, sign*limits->jmax, + s_cursor, t_cursor, v_cursor, a_cursor); + if (rc != MP_OK) return rc; + + rc = mp_append_phase (p, tc, sign*limits->amax, 0.0, + s_cursor, t_cursor, v_cursor, a_cursor); + if (rc != MP_OK) return rc; + + return mp_append_phase (p, tj, sign*limits->amax, -sign*limits->jmax, + s_cursor, t_cursor, v_cursor, a_cursor); +} + +static int +mp_build_interval_scurve (struct motion_plan *p, + double length, + double v0, + double v1, + double vcap, + const struct mp_limits *limits, + double s_target, + double *s_cursor, + double *t_cursor, + double *v_cursor, + double *a_cursor) +{ + if (!(length > 1e-12)) { + *s_cursor = s_target; + *v_cursor = v1; + *a_cursor = 0.0; + return MP_OK; + } + + if (!(vcap > 0.0) || !isfinite (vcap)) + return MP_ERR_PROFILE; + + if (v0 > vcap + 1e-7 || v1 > vcap + 1e-7) + return MP_ERR_PROFILE; + + double vlo = fmax (v0, v1); + double vhi = fmax (vcap, vlo); + + double s_at_vhi = + mp_speed_change_distance_scurve (v0, vhi, limits->amax, limits->jmax) + + mp_speed_change_distance_scurve (v1, vhi, limits->amax, limits->jmax); + + double vp; + double cruise_len; + + if (s_at_vhi <= length + 1e-8) { + vp = vhi; + cruise_len = fmax (0.0, length - s_at_vhi); + } else { + double s_at_vlo = + mp_speed_change_distance_scurve (v0, vlo, limits->amax, limits->jmax) + + mp_speed_change_distance_scurve (v1, vlo, limits->amax, limits->jmax); + + if (s_at_vlo > length + 1e-6) + return MP_ERR_PROFILE; + + double lo = vlo; + double hi = vhi; + + for (int k = 0; k < 80; ++k) { + double mid = 0.5*(lo + hi); + double sm = + mp_speed_change_distance_scurve (v0, mid, limits->amax, limits->jmax) + + mp_speed_change_distance_scurve (v1, mid, limits->amax, limits->jmax); + + if (sm <= length) + lo = mid; + else + hi = mid; + } + + vp = lo; + cruise_len = 0.0; + } + + *v_cursor = v0; + *a_cursor = 0.0; + + int rc = mp_append_speed_change_scurve (p, v0, vp, limits, + s_cursor, t_cursor, v_cursor, a_cursor); + if (rc != MP_OK) + return rc; + + if (cruise_len > 1e-10) { + if (!(vp > 1e-12)) + return MP_ERR_PROFILE; + + rc = mp_append_phase (p, cruise_len/vp, 0.0, 0.0, + s_cursor, t_cursor, v_cursor, a_cursor); + if (rc != MP_OK) + return rc; + } + + rc = mp_append_speed_change_scurve (p, vp, v1, limits, + s_cursor, t_cursor, v_cursor, a_cursor); + if (rc != MP_OK) + return rc; + + *s_cursor = s_target; + *v_cursor = v1; + *a_cursor = 0.0; + + if (p->phase_count > 0u) + p->phases[p->phase_count - 1u].s_end = s_target; + + return MP_OK; +} + +static int +mp_build_global_phases (struct motion_plan *p, + const struct mp_limits *limits) +{ + p->phase_count = 0u; + p->total_time = 0.0; + + p->v_min = DBL_MAX; + p->v_max = -DBL_MAX; + p->a_min = DBL_MAX; + p->a_max = -DBL_MAX; + p->j_min = DBL_MAX; + p->j_max = -DBL_MAX; + + double s_cursor = 0.0; + double t_cursor = 0.0; + double v_cursor = 0.0; + double a_cursor = 0.0; + + uint32_t knot_begin = 0u; + + while (knot_begin + 1u < p->node_count) { + uint32_t knot_end = knot_begin + 1u; + + while (knot_end + 1u < p->node_count && + !(p->nodes[knot_end].flags & MP_NODE_KNOT)) + ++knot_end; + + double length = p->nodes[knot_end].s - p->nodes[knot_begin].s; + double v0 = p->nodes[knot_begin].v; + double v1 = p->nodes[knot_end].v; + double vcap = mp_interval_vcap (p, knot_begin, knot_end); + double s_target = p->nodes[knot_end].s; + + int rc = mp_build_interval_scurve (p, length, v0, v1, vcap, limits, + s_target, + &s_cursor, &t_cursor, &v_cursor, &a_cursor); + if (rc != MP_OK) + return rc; + + knot_begin = knot_end; + } + + p->total_time = t_cursor; + + if (p->phase_count == 0u) { + p->v_min = p->v_max = 0.0; + p->a_min = p->a_max = 0.0; + p->j_min = p->j_max = 0.0; + } + + return MP_OK; +} + +int +mp_plan_build (const struct path *path, + double initial_x, + double initial_y, + const struct mp_limits *limits, + struct motion_plan *out) +{ + if (!path || !out || !mp_limits_valid (limits)) + return MP_ERR_INVALID_ARG; + + mp_plan_free (out); + + out->curvature_blend_len = limits->curvature_blend_len > 0.0 + ? limits->curvature_blend_len + : 0.0; + + if (path->count == 0u) + return MP_OK; + + int rc = mp_build_segments (path, initial_x, initial_y, limits, out); + if (rc != MP_OK) { + mp_plan_free (out); + return rc; + } + + if (out->segment_count == 0u) + return MP_OK; + + rc = mp_build_nodes (out, limits); + if (rc != MP_OK) { + mp_plan_free (out); + return rc; + } + + mp_apply_speed_lookahead (out, limits); + mp_mark_knots (out, limits); + + rc = mp_build_global_phases (out, limits); + if (rc != MP_OK) { + mp_plan_free (out); + return rc; + } + + return MP_OK; +} + +void +mp_plan_eval_scalar (const struct motion_plan *plan, double t, + double *s_out, double *v_out, + double *a_out, double *j_out) +{ + if (!plan || plan->phase_count == 0u) { + if (s_out) *s_out = 0.0; + if (v_out) *v_out = 0.0; + if (a_out) *a_out = 0.0; + if (j_out) *j_out = 0.0; + return; + } + + if (t <= 0.0) { + const struct mp_phase *ph = &plan->phases[0]; + if (s_out) *s_out = ph->s_begin; + if (v_out) *v_out = ph->v0; + if (a_out) *a_out = ph->a0; + if (j_out) *j_out = ph->j; + return; + } + + if (t >= plan->total_time) { + if (s_out) *s_out = plan->total_length; + if (v_out) *v_out = 0.0; + if (a_out) *a_out = 0.0; + if (j_out) *j_out = 0.0; + return; + } + + uint32_t lo = 0u; + uint32_t hi = plan->phase_count; + + while (lo + 1u < hi) { + uint32_t mid = lo + (hi - lo)/2u; + const struct mp_phase *ph = &plan->phases[mid]; + + if (t < ph->t_begin + ph->dt) + hi = mid; + else + lo = mid; + } + + uint32_t idx = lo; + while (idx + 1u < plan->phase_count && + t >= plan->phases[idx].t_begin + plan->phases[idx].dt) + ++idx; + + const struct mp_phase *ph = &plan->phases[idx]; + double tau = t - ph->t_begin; + tau = mp_clamp (tau, 0.0, ph->dt); + + double s = ph->s_begin + ph->v0*tau + 0.5*ph->a0*tau*tau + (ph->j*tau*tau*tau)/6.0; + double v = ph->v0 + ph->a0*tau + 0.5*ph->j*tau*tau; + double a = ph->a0 + ph->j*tau; + + if (s_out) *s_out = mp_clamp (s, 0.0, plan->total_length); + if (v_out) *v_out = fmax (0.0, v); + if (a_out) *a_out = a; + if (j_out) *j_out = ph->j; +} + +static uint32_t +mp_find_segment_by_s (const struct motion_plan *plan, double s) +{ + if (plan->segment_count == 0u) + return 0u; + + if (s <= 0.0) + return 0u; + + if (s >= plan->total_length) + return plan->segment_count - 1u; + + uint32_t lo = 0u; + uint32_t hi = plan->segment_count; + + while (lo + 1u < hi) { + uint32_t mid = lo + (hi - lo)/2u; + + if (s < plan->segments[mid].s_end) + hi = mid; + else + lo = mid; + } + + while (lo + 1u < plan->segment_count && s >= plan->segments[lo].s_end) + ++lo; + + return lo; +} + +void +mp_plan_sample (const struct motion_plan *plan, double t, + struct mp_sample *out) +{ + if (!out) + return; + + memset (out, 0, sizeof *out); + + if (!plan || plan->segment_count == 0u) { + out->t = t; + return; + } + + double s = 0.0; + double v = 0.0; + double a_t = 0.0; + double j_t = 0.0; + + mp_plan_eval_scalar (plan, t, &s, &v, &a_t, &j_t); + + uint32_t si = mp_find_segment_by_s (plan, s); + const struct mp_segment *g = &plan->segments[si]; + double local_s = mp_clamp (s - g->s_begin, 0.0, g->length); + + struct mp_vec2 p; + struct mp_vec2 tangent; + struct mp_vec2 normal; + double kappa_geom; + + mp_geom_eval_frame (g, local_s, &p, &tangent, &normal, &kappa_geom); + + double kappa = mp_effective_kappa (plan, si, local_s, kappa_geom); + double a_n = v*v*kappa; + double a_abs = hypot (a_t, a_n); + + struct mp_vec2 vel = mp_vec2_mul (tangent, v); + struct mp_vec2 acc = mp_vec2_add (mp_vec2_mul (tangent, a_t), + mp_vec2_mul (normal, a_n)); + + double j_vec_t = j_t - v*v*v*kappa*kappa; + double j_vec_n = 3.0*v*a_t*kappa; + struct mp_vec2 jerk = mp_vec2_add (mp_vec2_mul (tangent, j_vec_t), + mp_vec2_mul (normal, j_vec_n)); + double j_abs = copysign (mp_vec2_len (jerk), j_t); + + out->t = mp_clamp (t, 0.0, plan->total_time); + out->s = s; + out->p = p; + out->tangent = tangent; + out->normal = normal; + out->kappa = kappa; + out->kappa_geom = kappa_geom; + out->v = v; + out->a_t = a_t; + out->j_t = j_t; + out->a_n = a_n; + out->a_abs = a_abs; + out->j_abs = j_abs; + out->vel = vel; + out->acc = acc; + out->jerk = jerk; + out->segment_index = si; + out->source_index = g->source_index; + out->source_flags = g->flags; +} + +void +mp_plan_write_csv (const struct motion_plan *plan, + double dt, + FILE *out, + int write_header) +{ + if (!plan || !out || !(dt > 0.0) || !isfinite (dt)) + return; + + if (write_header) { + fputs ("t,s,x,y,v,a_t,j_t,kappa,a_n,a_abs,j_abs," + "vx,vy,ax,ay,jx,jy,tx,ty,nx,ny,segment_index,source_index,source_flags\n", + out); + } + + if (plan->segment_count == 0u) + return; + + double t = 0.0; + + while (t < plan->total_time) { + struct mp_sample smp; + mp_plan_sample (plan, t, &smp); + + fprintf (out, + "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.12f,%.9f,%.9f,%.9f," + "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%u,%u,%d\n", + smp.t, smp.s, smp.p.x, smp.p.y, + smp.v, smp.a_t, smp.j_t, smp.kappa, + smp.a_n, smp.a_abs, smp.j_abs, + smp.vel.x, smp.vel.y, + smp.acc.x, smp.acc.y, + smp.jerk.x, smp.jerk.y, + smp.tangent.x, smp.tangent.y, + smp.normal.x, smp.normal.y, + smp.segment_index, smp.source_index, smp.source_flags); + + t += dt; + } + + struct mp_sample last; + mp_plan_sample (plan, plan->total_time, &last); + + fprintf (out, + "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.12f,%.9f,%.9f,%.9f," + "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%u,%u,%d\n", + last.t, last.s, last.p.x, last.p.y, + last.v, last.a_t, last.j_t, last.kappa, + last.a_n, last.a_abs, last.j_abs, + last.vel.x, last.vel.y, + last.acc.x, last.acc.y, + last.jerk.x, last.jerk.y, + last.tangent.x, last.tangent.y, + last.normal.x, last.normal.y, + last.segment_index, last.source_index, last.source_flags); +} diff --git a/src/motion_planner.h b/src/motion_planner.h new file mode 100644 index 0000000..0073f79 --- /dev/null +++ b/src/motion_planner.h @@ -0,0 +1,159 @@ +#ifndef INCLUDED_MOTION_PLANNER_H +#define INCLUDED_MOTION_PLANNER_H + +#include +#include +#include "path.h" + +#define MP_EPS 1e-9 + +enum mp_status { + MP_OK = 0, + MP_ERR_INVALID_ARG = -1, + MP_ERR_LIMITS = -2, + MP_ERR_ALLOC = -3, + MP_ERR_GEOMETRY = -4, + MP_ERR_PROFILE = -5 +}; + +enum mp_geom_type { + MP_GEOM_LINE = 1, + MP_GEOM_ARC = 2 +}; + +enum mp_node_flags { + MP_NODE_START = 1u << 0, + MP_NODE_END = 1u << 1, + MP_NODE_GEOM_GAP = 1u << 2, + MP_NODE_STRAIGHT = 1u << 3, + MP_NODE_CORNER_LIMIT = 1u << 4, + MP_NODE_HARD_STOP = 1u << 5, + MP_NODE_SPEED_CHANGE = 1u << 6, + MP_NODE_KNOT = 1u << 7 +}; + +struct mp_vec2 { + double x; + double y; +}; + +struct mp_limits { + double vmax; // mm/s: предел для рабочих G1-перемещений + double rapid_vmax; // mm/s: предел для G0; если <= 0, используется vmax + double amax; // mm/s^2: скалярное тангенциальное ускорение + double jmax; // mm/s^3: скалярный jerk; должен быть > 0 + double corner_tol; // mm: виртуальный допуск скругления углов + double min_segment_len; // mm: сегменты короче порога игнорируются + double default_feed; // mm/s: feed для G1, если path_element.f <= 0 + + double straight_angle_tol; // rad + double stop_angle; // rad + double corner_speed_deadband; // относительный deadband, например 0.02 + + double curvature_blend_len; // mm +}; + +struct mp_segment { + enum mp_geom_type type; + uint32_t source_index; + int flags; + + struct mp_vec2 p0; + struct mp_vec2 p1; + + struct mp_vec2 c; // центр дуги + double r; // радиус дуги + double a0; // начальный угол дуги + double sweep; // signed sweep, rad + + double length; // mm + double s_begin; // global mm + double s_end; // global mm + + double feed; // mm/s: командная скорость до ограничений + double v_nominal; // mm/s: скорость участка после ограничений +}; + +struct mp_node { + double s; // global mm + double v_cap; // mm/s: геометрический/командный предел узла + double v; // mm/s: скорость после lookahead + double theta; // rad: угол между касательными + uint32_t flags; // enum mp_node_flags +}; + +struct mp_phase { + double t_begin; // s + double dt; // s + + double s_begin; // mm + double s_end; // mm + + double v0; // mm/s + double a0; // mm/s^2 + double j; // mm/s^3 +}; + +struct motion_plan { + struct mp_segment *segments; + uint32_t segment_count; + uint32_t segment_capacity; + + struct mp_node *nodes; + uint32_t node_count; + uint32_t node_capacity; + + struct mp_phase *phases; + uint32_t phase_count; + uint32_t phase_capacity; + + double total_length; + double total_time; + + double curvature_blend_len; // mm + + double v_min; + double v_max; + double a_min; + double a_max; + double j_min; + double j_max; +}; + +struct mp_sample { + double t; + double s; + + struct mp_vec2 p; + struct mp_vec2 tangent; + struct mp_vec2 normal; + + double kappa; + double kappa_geom; + + double v; + double a_t; + double j_t; + + double a_n; + double a_abs; + double j_abs; + + struct mp_vec2 vel; + struct mp_vec2 acc; + struct mp_vec2 jerk; + + uint32_t segment_index; + uint32_t source_index; + int source_flags; +}; + +void mp_plan_init (struct motion_plan *plan); +void mp_plan_free (struct motion_plan *plan); + +int mp_plan_build (const struct path *path, double initial_x, double initial_y, const struct mp_limits *limits, struct motion_plan *out); +void mp_plan_eval_scalar (const struct motion_plan *plan, double t, double *s_out, double *v_out, double *a_out, double *j_out); +void mp_plan_sample (const struct motion_plan *plan, double t, struct mp_sample *out); +void mp_plan_write_csv (const struct motion_plan *plan, double dt, FILE *out, int write_header); + +#endif // INCLUDED_MOTION_PLANNER_H diff --git a/src/parse.c b/src/parse.c new file mode 100644 index 0000000..fb147be --- /dev/null +++ b/src/parse.c @@ -0,0 +1,98 @@ +/// src/parse.h +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#include +#include +#include +#include + +#include "utils.h" +#include "arena.h" +#include "sv.h" +#include "rs274ngc_lexer.h" +#include "rs274ngc_cst.h" + +#define INDENTATION 2 + +void +print_cst (struct arena *temp, struct rs274ngc_lexer *lexer, struct rs274ngc_cst_branch *root, size_t alignment) +{ + void *bottom = ARENA_COPY (temp, root); + ARENA_COPY (temp, alignment); + while (temp->tail->free != bottom) { + alignment = *(size_t *) arena_pop (temp, sizeof (alignment)); + void *node = *(void **) arena_pop (temp, sizeof (node )); + ASSERT (node); + if (RS274NGC_CST_NODE_KIND (node) < RS274NGC_CST_TERMINAL_COUNT) { // leaf + struct rs274ngc_cst_leaf *leaf = &RS274NGC_CST_NODE_PTR (node)->leaf; + struct location location = find_location (lexer->sv, leaf->sv); + print_location (lexer->filename, location, alignment, "- leaf: %s", + rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); + } else { // branch + struct rs274ngc_cst_branch *branch = &RS274NGC_CST_NODE_PTR (node)->branch; + if (1 || RS274NGC_CST_NODE_KIND_EQ (node, LINE)) { + struct location location = find_location (lexer->sv, branch->sv); + print_location (lexer->filename, location, alignment, "- branch: %s", + rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); + } + alignment += INDENTATION; + for (size_t i = branch->count; i > 0; --i) { + ASSERT (branch->children[i - 1]); + ARENA_COPY (temp, branch->children[i - 1]); + ARENA_COPY (temp, alignment); + } + } + } +} + +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); + + int base_alignment = strlen (filename) + 15; + + 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, + }; + struct rs274ngc_cst_branch *program = &RS274NGC_CST_PARSE (parser, PROGRAM)->branch; + // ensure no memory leaked + ASSERT (t.head == t.tail ); + ASSERT (t.head->free == t.head->begin); + printf ("Memory used %lu\n", arena_used (parser.output)); + + print_cst (&t, &lexer, program, base_alignment); + + return EXIT_SUCCESS; +} + +/// src/parse.h ends here diff --git a/src/path.c b/src/path.c new file mode 100644 index 0000000..7ded2d2 --- /dev/null +++ b/src/path.c @@ -0,0 +1,145 @@ +/// src/path.c +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +// Order of execution: +// 1. comment (includes message). +// 2. set feed rate mode (G93, G94 — inverse time or per minute). +// 3. set feed rate (F). +// 4. set spindle speed (S). +// 5. select tool (T). +// 6. change tool (M6). +// 7. spindle on or off (M3, M4, M5). +// 8. coolant on or off (M7, M8, M9). +// 9. enable or disable overrides (M48, M49). +// 10. dwell (G4). +// 11. set active plane (G17, G18, G19). +// 12. set length units (G20, G21). +// 13. cutter radius compensation on or off (G40, G41, G42) +// 14. cutter length compensation on or off (G43, G49) +// 15. coordinate system selection (G54, G55, G56, G57, G58, G59, +// G59.1, G59.2, G59.3). +// 16. set path control mode (G61, G61.1, G64) +// 17. set distance mode (G90, G91). +// 18. set retract mode (G98, G99). +// 19. home (G28, G30) or change coordinate system data (G10) or set +// axis offsets (G92, G92.1, G92.2, G94). +// 20. perform motion (G0 to G3, G80 to G89), as modified (possibly) by G53. +// 21. stop (M0, M1, M2, M30, M60). +// +/// Code: + +#include +#include "path.h" +#include "rs274ngc_state.h" +#include "da.h" + +struct path +build_path (struct rs274ngc_cst_parser parser) +{ + struct rs274ngc_state state = { + // optionally set defaults, but ZII seems to do the job + }; + + struct path path = {0}; + double prev_x = 0; + double prev_y = 0; + + while (rs274ngc_state_next (&state, parser)) { + // printf ("move %2d | %10.4lf | %10.4lf | %10.4lf | %.*s\n", state.current_motion_mode, state.x, state.y, state.f, SV_FMTA (state.line)); + if (state.words_set & (X_MASK | Y_MASK)) { + struct path_element pe = { .line = state.line }; + pe.line.end += 1; // HACK(cmmm): this should be fixed in parser + switch (state.distance_mode) { + case DISTANCE_MODE_ABSOLUTE: { + pe.x = state.x; + pe.y = state.y; + } break; + case DISTANCE_MODE_INCREMENTAL: { + pe.x = prev_x + state.x*((state.words_set & X_MASK) != 0); + pe.y = prev_y + state.y*((state.words_set & Y_MASK) != 0); + } break; + } + + if (state.current_motion_mode == MOTION_RAPID_POSITIONING) { + pe.flags |= PEF_TRAVERSING; + pe.f = 100; // TODO(cmmm): take as arg + } + else + pe.f = state.f/60; + + if (state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CW || + state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CCW) { + pe.flags |= PEF_ARC; + if (state.words_set & R_MASK) { + // NOTE(cmmm): maybe we can use just one sqrt + double x0 = prev_x; + double y0 = prev_y; + double x1 = state.x; + double y1 = state.y; + double r = state.r; + double hdx = (x1 - x0)/2; + double hdy = (y1 - y0)/2; + double d = sqrt (hdx*hdx + hdy*hdy); + double nx = -hdy/d; + double ny = hdx/d; + double h = sqrt (r*r - d*d); + if (r > 0 && state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CW || + r < 0 && state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CCW) { + h *= -1; // make center right + } + pe.i = prev_x + hdx + nx*h; + pe.j = prev_y + hdy + ny*h; + } else if (state.words_set & (I_MASK | J_MASK)) { + pe.i = prev_x + state.i; + pe.j = prev_y + state.j; + } + if (state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CCW) + pe.flags |= PEF_CCW; + + // printf ("move %2d | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %.*s\n", state.current_motion_mode, state.x, state.y, state.i, state.j, SV_FMTA (state.line)); + DA_APPEND (path, pe); + } else if (pe.x != prev_x || pe.y != prev_y) { + DA_APPEND (path, pe); + } + + switch (state.distance_mode) { + case DISTANCE_MODE_ABSOLUTE: { + prev_x = state.x; + prev_y = state.y; + } break; + case DISTANCE_MODE_INCREMENTAL: { + prev_x += ((state.words_set & X_MASK) != 0)*state.x; + prev_y += ((state.words_set & Y_MASK) != 0)*state.y; + } break; + } + } + + if (state.stopping == STOPPING_END) + break; + } + + return path; +} + +struct vec2 +path_element_start (const struct path *path, const struct path_element *pe) +{ + struct vec2 start; + + if (pe == path->items) { + start.x = path->initial_x; + start.y = path->initial_y; + } else { + start.x = pe[-1].x; + start.y = pe[-1].y; + } + + return start; +} + +/// src/path.c ends here diff --git a/src/path.h b/src/path.h new file mode 100644 index 0000000..2355021 --- /dev/null +++ b/src/path.h @@ -0,0 +1,46 @@ +/// src/path.h +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_PATH_H +#define INCLUDED_PATH_H + +#include "utils.h" +#include "rs274ngc_cst.h" +#include "vec2.h" + +#define PEF_TRAVERSING (1 << 0) // 0 means technological +#define PEF_ARC (1 << 1) // 0 means line +#define PEF_CCW (1 << 2) // 0 means CW +#define PEF_RELATIVE (1 << 3) // 0 means absolute +#define PEF_INCH (1 << 4) // 0 means mm +// ... + +struct path_element { + struct sv line; + double x, y; // end coords (abs mm) + double f; // feed rate (mm/s) + double i, j; // centers for arcs (abs mm) + int flags; +}; + +struct path { + struct path_element *items; + uint32_t count; + uint32_t capacity; + double initial_x; + double initial_y; +}; + +struct path build_path (struct rs274ngc_cst_parser parser); +struct vec2 path_element_start (const struct path *, const struct path_element *); + +#endif // INCLUDED_PATH_H + +/// src/path.h ends here diff --git a/src/rate.c b/src/rate.c new file mode 100644 index 0000000..33def16 --- /dev/null +++ b/src/rate.c @@ -0,0 +1,134 @@ +#include "rate.h" +#include +#include +#include + +static int +work_motion_is_working_pe (const struct path_element *pe) +{ + if (!pe) + return 0; + + return ~pe->flags & PEF_TRAVERSING; +} + +static double +work_motion_clamp (double x, double lo, double hi) +{ + return x < lo ? lo : (x > hi ? hi : x); +} + +/* + * Находит время t, в которое глобальная координата траектории равна s. + * Нужно, чтобы интегрировать строго по рабочим segment.s_begin..segment.s_end, + * а не смешивать рабочие и холостые участки одним временным шагом. + */ +static double +work_motion_time_at_s (const struct motion_plan *plan, double s) +{ + if (!plan || !(plan->total_time > 0.0)) + return 0.0; + + if (s <= 0.0) + return 0.0; + + if (s >= plan->total_length) + return plan->total_time; + + double lo = 0.0; + double hi = plan->total_time; + + for (int i = 0; i < 80; ++i) { + double mid = 0.5*(lo + hi); + double smid = 0.0; + + mp_plan_eval_scalar (plan, mid, &smid, NULL, NULL, NULL); + + if (smid < s) + lo = mid; + else + hi = mid; + } + + return 0.5*(lo + hi); +} + +/* + * dt -- шаг численного интегрирования в секундах. + * Для текущей визуализации можно использовать 0.001. + */ +struct work_motion_stats +measure_work_motion_stats (const struct path *path, + const struct motion_plan *plan, + double dt) +{ + ASSERT (path); + ASSERT (plan); + ASSERT (plan->segment_count > 0); + ASSERT (plan->total_time > 0); + ASSERT (dt > 0); + ASSERT (isfinite (dt)); + + struct work_motion_stats out = {0}; + out.dt = dt; + + for (uint32_t si = 0; si < plan->segment_count; ++si) { + const struct mp_segment *seg = &plan->segments[si]; + + ASSERT (seg->source_index < path->count); + + const struct path_element *pe = &path->items[seg->source_index]; + + if (!work_motion_is_working_pe (pe)) + continue; + + double t0 = work_motion_time_at_s (plan, seg->s_begin); + double t1 = work_motion_time_at_s (plan, seg->s_end); + + t0 = work_motion_clamp (t0, 0, plan->total_time); + t1 = work_motion_clamp (t1, 0, plan->total_time); + + if (!(t1 > t0)) + continue; + + out.active_segment_count += 1; + out.active_length += seg->length; + + for (double t = t0; t < t1;) { + double h = fmin (dt, t1 - t); + double tm = t + h/2; + + struct mp_sample sample; + mp_plan_sample (plan, tm, &sample); + + /* + * Берём v_nominal именно у текущего рабочего сегмента. + * Это устойчивее, чем брать sample.segment_index на границе сегментов. + */ + double v_ref = seg->v_nominal; + double e = sample.v - v_ref; + // double e = (sample.v - v_ref)/v_ref; + double e_abs = fabs (e); + + out.speed_error_abs_integral += e_abs*h; + out.speed_error_sq_integral += e*e*h; + out.speed_error_max_abs = fmax (out.speed_error_max_abs, e_abs); + + out.jerk_abs_integral += fabs (sample.j_abs)*h; + out.jerk_abs_max = fmax (out.jerk_abs_max, fabs (sample.j_abs)); + + out.active_time += h; + out.sample_count += 1; + + t += h; + } + } + + if (out.active_time > 0) { + out.speed_error_mean_abs = out.speed_error_abs_integral/out.active_time; + out.speed_error_rms = sqrt (out.speed_error_sq_integral/out.active_time); + out.jerk_abs_mean = out.jerk_abs_integral/out.active_time; + } + + return out; +} diff --git a/src/rate.h b/src/rate.h new file mode 100644 index 0000000..b75b064 --- /dev/null +++ b/src/rate.h @@ -0,0 +1,40 @@ +#ifndef INCLUDED_RATE_H +#define INCLUDED_RATE_H + +#include "motion_planner.h" + +struct work_motion_stats { + double dt; + + double active_time; /* s */ + double active_length; /* mm */ + uint32_t active_segment_count; + uint32_t sample_count; + + /* + * Отклонение скорости на рабочих участках. + * + * Ошибка считается как: + * e(t) = sample.v - segment.v_nominal + */ + double speed_error_max_abs; /* mm/s */ + double speed_error_mean_abs; /* mm/s */ + double speed_error_rms; /* mm/s */ + + double speed_error_abs_integral; /* mm, т.к. integral |e| dt */ + double speed_error_sq_integral; /* mm^2/s, т.к. integral e^2 dt */ + + /* + * Общий рывок на рабочих участках. + * + * Используется sample.j_abs, то есть модуль полного векторного рывка, + * а не только тангенциальный j_t. + */ + double jerk_abs_integral; /* mm/s^2, т.к. integral |j| dt */ + double jerk_abs_mean; /* mm/s^3 */ + double jerk_abs_max; /* mm/s^3 */ +}; + +struct work_motion_stats measure_work_motion_stats (const struct path *, const struct motion_plan *, double dt); + +#endif // INCLUDED_RATE_H diff --git a/src/rs274ngc_cst.c b/src/rs274ngc_cst.c new file mode 100644 index 0000000..b2dd582 --- /dev/null +++ b/src/rs274ngc_cst.c @@ -0,0 +1,279 @@ +/// src/rs274ngc_cst.c --- RS274NGC Concrete Syntax Tree +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#include +#include +#include +#include "utils.h" +#include "rs274ngc_cst.h" + +#ifndef ARENA_ASSERT +#include +#define ASSERT assert +#else +#define ASSERT ARENA_ASSERT +#endif + +#define X(SYM, ...) [RS274NGC_CST_NODE_KIND_##SYM] = #SYM, +const char *rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND_COUNT] = { + [RS274NGC_CST_NODE_KIND_INVALID ] = "INVALID", + [RS274NGC_CST_NODE_KIND_END_OF_LINE] = "END_OF_LINE", + [RS274NGC_CST_NODE_KIND_END_OF_FILE] = "END_OF_FILE", + RS274NGC_CST_NODE_KINDS () +}; +#undef X + +static void +print_error (struct rs274ngc_lexer *lexer, const char *point, + const char *format, ...) +{ + int row = 1; + int col = 1; + + for (const char *head = lexer->sv.beg; head < point; ++head) { + col += 1; + if (*head == '\n') { + row += 1; + col = 1; + } + }; + + fprintf (stderr, "%s:%d:%d: error: ", lexer->filename, row, col); + + va_list ap; + va_start (ap, format); + vfprintf (stderr, format, ap); + va_end (ap); + + putc ('\n', stderr); +} + +#define PARSE_BRANCH_NODE(P, B, K) \ + parse_branch_node (P, B, RS274NGC_CST_NODE_KIND_##K) +#define PARSE_BRANCH_NODE_IF(P, B, K, L) \ + (((P).lexer->lexeme.kind == RS274NGC_LEXEME_KIND_##L) \ + ? parse_branch_node (P, B, RS274NGC_CST_NODE_KIND_##K) : false) +#define PARSE_BRANCH_NODE_IF_SELF(P, B, L) \ + (((P).lexer->lexeme.kind == RS274NGC_LEXEME_KIND_##L) \ + ? parse_branch_node (P, B, RS274NGC_CST_NODE_KIND_##L) : false) +static bool +parse_branch_node (struct rs274ngc_cst_parser parser, + struct rs274ngc_cst_branch *branch, + enum rs274ngc_cst_node_kind kind) +{ + union rs274ngc_cst_node *node = rs274ngc_cst_parse_node (parser, kind); + + if (node == NULL) + return false; + + ARENA_COPY (parser.temporary, node); + branch->count += 1; + + return true; +} + +#define LEXEME_MATCHES(P, K) \ + ((P).lexer->lexeme.kind == RS274NGC_LEXEME_KIND_##K) + +struct rs274ngc_cst_leaf * +rs274ngc_cst_parse_leaf (struct rs274ngc_cst_parser parser, + enum rs274ngc_cst_node_kind kind) +{ + ASSERT (kind < RS274NGC_CST_TERMINAL_COUNT); + + if (parser.lexer->lexeme.kind != (enum rs274ngc_lexeme_kind) kind) + return NULL; + + struct rs274ngc_cst_leaf leaf = { .sv = parser.lexer->lexeme.sv }; + void *ptr = ARENA_COPY (parser.output, leaf); + rs274ngc_lexer_next_lexeme (parser.lexer); + + return (struct rs274ngc_cst_leaf *) RS274NGC_CST_TAG_NODE (ptr, kind); +} + +struct rs274ngc_cst_branch * +rs274ngc_cst_parse_branch (struct rs274ngc_cst_parser parser, + enum rs274ngc_cst_node_kind kind) +{ + ASSERT (kind >= RS274NGC_CST_TERMINAL_COUNT); + ASSERT (kind < RS274NGC_CST_NODE_KIND_COUNT); + + // printf ("Parsing: %s\n", rs274ngc_cst_node_kind_names[kind]); + + struct rs274ngc_cst_branch branch = { + .sv.beg = parser.lexer->lexeme.sv.beg + }; + + const char *cursor = parser.lexer->cursor; + struct arena_checkpoint children = + arena_checkpoint (parser.temporary, ALIGNOF (void *) - 1); + switch (kind) { + case RS274NGC_CST_NODE_KIND_PROGRAM: { + while (!LEXEME_MATCHES (parser, END_OF_FILE)) { + if (PARSE_BRANCH_NODE (parser, &branch, LINE)) + continue; + + struct location location = + find_location (parser.lexer->sv, parser.lexer->lexeme.sv); + print_location (parser.lexer->filename, location, 0, "failed: " SV_FMT, + SV_FMTA (parser.lexer->lexeme.sv)); + for (;;) { + rs274ngc_lexer_next_lexeme (parser.lexer); + if (LEXEME_MATCHES (parser, END_OF_FILE)) break; + if (LEXEME_MATCHES (parser, END_OF_LINE)) { + rs274ngc_lexer_next_lexeme (parser.lexer); + break; + } + } + } + } break; + case RS274NGC_CST_NODE_KIND_LINE: { + PARSE_BRANCH_NODE_IF (parser, &branch, BLOCK_DELETE, SLASH); + PARSE_BRANCH_NODE_IF_SELF (parser, &branch, LINE_NUMBER); + while (!LEXEME_MATCHES (parser, END_OF_LINE) && + !LEXEME_MATCHES (parser, END_OF_FILE)) { + if (!PARSE_BRANCH_NODE (parser, &branch, SEGMENT)) goto fail; + } rs274ngc_lexer_next_lexeme (parser.lexer); // skip END_OF_LINE + } break; + case RS274NGC_CST_NODE_KIND_SEGMENT: { + if (PARSE_BRANCH_NODE_IF (parser, &branch, WORD, WORD_LETTER )) break; + if (PARSE_BRANCH_NODE_IF (parser, &branch, PARAMETER_SETTING, PARAMETER_SIGN)) break; + if (PARSE_BRANCH_NODE (parser, &branch, COMMENT )) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_WORD: { + if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, WORD_LETTER)) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; + } break; + case RS274NGC_CST_NODE_KIND_PARAMETER_INDEX: { + if (PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE)) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_REAL_VALUE: { + if (PARSE_BRANCH_NODE (parser, &branch, REAL_NUMBER )) break; + if (PARSE_BRANCH_NODE (parser, &branch, EXPRESSION )) break; + if (PARSE_BRANCH_NODE_IF (parser, &branch, PARAMETER_VALUE, PARAMETER_SIGN)) break; + if (PARSE_BRANCH_NODE (parser, &branch, UNARY_COMBO )) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_REAL_NUMBER: { + if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, MINUS)) + PARSE_BRANCH_NODE_IF_SELF (parser, &branch, PLUS); + if (PARSE_BRANCH_NODE (parser, &branch, REAL_NUMBER_NO_SIGN)) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_EXPRESSION: { + if (!PARSE_BRANCH_NODE (parser, &branch, BRACKET_LEFT)) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; + while (!LEXEME_MATCHES (parser, BRACKET_RIGHT)) { + if (!PARSE_BRANCH_NODE (parser, &branch, BINARY_OPERATION)) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; + } + if (!PARSE_BRANCH_NODE (parser, &branch, BRACKET_RIGHT)) goto fail; + } break; + case RS274NGC_CST_NODE_KIND_COMMENT: { + if (PARSE_BRANCH_NODE (parser, &branch, ORDINARY_COMMENT)) break; + if (PARSE_BRANCH_NODE (parser, &branch, MESSAGE )) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_BINARY_OPERATION: { + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, POWER )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, TIMES )) break; + if (PARSE_BRANCH_NODE_IF (parser, &branch, DIVIDED_BY, SLASH)) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, MODULO )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, PLUS )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, MINUS )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, EXCLUSIVE_OR )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, NON_EXCLUSIVE_OR )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, AND )) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_BLOCK_DELETE: + case RS274NGC_CST_NODE_KIND_DIVIDED_BY: { + if (PARSE_BRANCH_NODE (parser, &branch, SLASH)) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_PARAMETER_VALUE: { + if (!PARSE_BRANCH_NODE (parser, &branch, PARAMETER_SIGN)) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; + } break; + case RS274NGC_CST_NODE_KIND_UNARY_COMBO: { + if (PARSE_BRANCH_NODE (parser, &branch, ORDINARY_UNARY_COMBO)) break; + if (PARSE_BRANCH_NODE (parser, &branch, ARC_TANGENT_COMBO )) break; + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_ORDINARY_UNARY_COMBO: { + do { + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ABSOLUTE_VALUE)) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ARC_COSINE )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ARC_SINE )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, COSINE )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, SINE )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, E_RAISED_TO )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, NATURAL_LOG_OF)) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, FIX_DOWN )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, FIX_UP )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ROUND )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, SQUARE_ROOT )) break; + if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, TANGENT )) break; + } while (0); + if (!PARSE_BRANCH_NODE (parser, &branch, EXPRESSION)) + goto fail; + } break; + case RS274NGC_CST_NODE_KIND_ARC_TANGENT_COMBO: { + if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ARC_TANGENT )) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, EXPRESSION )) goto fail; + if (!PARSE_BRANCH_NODE_IF (parser, &branch, DIVIDED_BY, SLASH)) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, EXPRESSION )) goto fail; + } break; + case RS274NGC_CST_NODE_KIND_PARAMETER_SETTING: { + if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, PARAMETER_SIGN )) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, PARAMETER_INDEX)) goto fail; + if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, EQUAL_SIGN )) goto fail; + if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; + } break; + default: return NULL; + } + + if (branch.count == 0) + return NULL; + size_t children_size = branch.count*sizeof (*branch.children); + struct rs274ngc_cst_branch *ptr = + arena_reserve (parser.output, sizeof (branch) + children_size, ALIGNOF (*ptr) - 1); + ASSERT (ptr != NULL); + ARENA_COPY_FAST (parser.output, branch); + void *other = arena_coalesce_from_into_fast (parser.temporary, children, + parser.output, children_size); + ptr->sv.end = RS274NGC_CST_NODE_PTR (ptr->children[ptr->count - 1])->sv.end; + + // struct location location = find_location (parser.lexer->sv, ptr->sv); + // print_location (parser.lexer->filename, location, 0, "parsed: %s", + // rs274ngc_cst_node_kind_names[kind]); + + return (void *) RS274NGC_CST_TAG_NODE (ptr, kind); + + fail: + // printf ("Failed to parse: %s\n", rs274ngc_node_kind_names[kind]); + parser.lexer->cursor = cursor; + if (branch.count) + arena_rollback_to (parser.temporary, children); + return NULL; +} + +union rs274ngc_cst_node * +rs274ngc_cst_parse_node (struct rs274ngc_cst_parser parser, + enum rs274ngc_cst_node_kind kind) +{ + return (kind < RS274NGC_CST_TERMINAL_COUNT + ? (void *) rs274ngc_cst_parse_leaf (parser, kind) + : (void *) rs274ngc_cst_parse_branch (parser, kind)); +} + +/// src/rs274ngc_cst.c ends here diff --git a/src/rs274ngc_cst.h b/src/rs274ngc_cst.h new file mode 100644 index 0000000..6e93c93 --- /dev/null +++ b/src/rs274ngc_cst.h @@ -0,0 +1,93 @@ +/// src/rs274ngc_cst.h --- RS274NGC Concrete Syntax Tree +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_RS274NGC_CST_H +#define INCLUDED_RS274NGC_CST_H + +#define RS274NGC_CST_NODE_KINDS() \ + RS274NGC_LEXEME_KINDS() \ + X (PROGRAM ) \ + X (LINE ) \ + X (BLOCK_DELETE ) \ + X (SEGMENT ) \ + X (WORD ) \ + X (COMMENT ) \ + X (PARAMETER_SETTING ) \ + X (PARAMETER_INDEX ) \ + X (REAL_VALUE ) \ + X (REAL_NUMBER ) \ + X (EXPRESSION ) \ + X (PARAMETER_VALUE ) \ + X (UNARY_COMBO ) \ + X (ORDINARY_UNARY_COMBO) \ + X (ARC_TANGENT_COMBO ) \ + X (BINARY_OPERATION ) \ + X (DIVIDED_BY ) + +#include "rs274ngc_lexer.h" +#include "arena.h" + +#define RS274NGC_CST_TAG_NODE(PTR, TAG) ((union rs274ngc_cst_node *) ((uintptr_t) (TAG) << 48 | (uintptr_t) (PTR))) +#define RS274NGC_CST_NODE_KIND(PTR) ((enum rs274ngc_cst_node_kind) ((uintptr_t) (PTR) >> 48)) +#define RS274NGC_CST_NODE_PTR(PTR) ((union rs274ngc_cst_node *) ((uintptr_t) (PTR) & (((uintptr_t) 1 << 48) - 1))) + +#define RS274NGC_CST_NODE_KIND_EQ(PTR, KIND) (RS274NGC_CST_NODE_KIND (PTR) == RS274NGC_CST_NODE_KIND_##KIND) + +#define X(SYM, ...) RS274NGC_CST_NODE_KIND_##SYM, +enum rs274ngc_cst_node_kind { + RS274NGC_CST_NODE_KIND_INVALID, + RS274NGC_CST_NODE_KIND_END_OF_LINE, + RS274NGC_CST_NODE_KIND_END_OF_FILE, + RS274NGC_CST_NODE_KINDS () + RS274NGC_CST_NODE_KIND_COUNT, +}; +#undef X + +#define RS274NGC_CST_TERMINAL_COUNT \ + ((enum rs274ngc_cst_node_kind) RS274NGC_LEXEME_KIND_COUNT) + +extern const char *rs274ngc_cst_node_kind_names[ + RS274NGC_CST_NODE_KIND_COUNT]; + +union rs274ngc_cst_node; + +struct rs274ngc_cst_leaf { + struct sv sv; +}; + +struct rs274ngc_cst_branch { + struct sv sv; + uint64_t count; + union rs274ngc_cst_node *children[]; +}; + +union rs274ngc_cst_node { + struct sv sv; + struct rs274ngc_cst_leaf leaf; + struct rs274ngc_cst_branch branch; +}; + +struct rs274ngc_cst_parser { + struct rs274ngc_lexer *lexer; + struct arena *output; + struct arena *temporary; +}; + +#define RS274NGC_CST_PARSE(P, K) \ + (RS274NGC_CST_NODE_KIND_##K < RS274NGC_CST_TERMINAL_COUNT \ + ? (union rs274ngc_cst_node *) rs274ngc_cst_parse_leaf (P, RS274NGC_CST_NODE_KIND_##K) \ + : (union rs274ngc_cst_node *) rs274ngc_cst_parse_branch (P, RS274NGC_CST_NODE_KIND_##K)) +union rs274ngc_cst_node *rs274ngc_cst_parse_node (struct rs274ngc_cst_parser, enum rs274ngc_cst_node_kind); +struct rs274ngc_cst_leaf *rs274ngc_cst_parse_leaf (struct rs274ngc_cst_parser, enum rs274ngc_cst_node_kind); +struct rs274ngc_cst_branch *rs274ngc_cst_parse_branch (struct rs274ngc_cst_parser, enum rs274ngc_cst_node_kind); + +#endif // INCLUDED_RS274NGC_CST_H + +/// src/rs274ngc_cst.h ends here diff --git a/src/rs274ngc_lexeme.c b/src/rs274ngc_lexeme.c new file mode 100644 index 0000000..1b4bbad --- /dev/null +++ b/src/rs274ngc_lexeme.c @@ -0,0 +1,22 @@ +/// src/rs274ngc_lexeme.c --- RS274NGC lexeme +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#include "rs274ngc_lexeme.h" + +#define X(SYM, ...) [RS274NGC_LEXEME_KIND_##SYM] = #SYM, +const char *rs274ngc_lexeme_kind_names[RS274NGC_LEXEME_KIND_COUNT] = { + [RS274NGC_LEXEME_KIND_INVALID ] = "INVALID", + [RS274NGC_LEXEME_KIND_END_OF_LINE] = "END_OF_LINE", + [RS274NGC_LEXEME_KIND_END_OF_FILE] = "END_OF_FILE", + RS274NGC_LEXEME_KINDS () +}; +#undef X + +/// src/rs274ngc_lexeme.c ends here diff --git a/src/rs274ngc_lexeme.h b/src/rs274ngc_lexeme.h new file mode 100644 index 0000000..337d244 --- /dev/null +++ b/src/rs274ngc_lexeme.h @@ -0,0 +1,75 @@ +/// src/rs274ngc_lexeme.h --- RS274NGC lexeme +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED__RS274NGC__LEXEME__H +#define INCLUDED__RS274NGC__LEXEME__H + +#include +#include +#include "sv.h" + +#define RS274NGC_LEXEME_KINDS() \ + X (MESSAGE, "\\([ \t]*[Mm][ \t]*[Ss][ \t]*[Gg][ \t]*," \ + "[^()]*\\)" ) \ + X (ORDINARY_COMMENT, ";[^\n]*|\\([^()]*\\)" ) \ + X (MODULO, "[Mm][ \t]*[Oo][ \t]*[Dd]" ) \ + X (NATURAL_LOG_OF, "[Ll][ \t]*[Nn]" ) \ + X (NON_EXCLUSIVE_OR, "[Oo][ \t]*[Rr]" ) \ + X (ABSOLUTE_VALUE, "[Aa][ \t]*[Bb][ \t]*[Ss]" ) \ + X (AND, "[Aa][ \t]*[Nn][ \t]*[Dd]" ) \ + X (ARC_COSINE, "[Aa][ \t]*[Cc][ \t]*[Oo][ \t]*[Ss]" ) \ + X (ARC_SINE, "[Aa][ \t]*[Ss][ \t]*[Ii][ \t]*[Nn]" ) \ + X (ARC_TANGENT, "[Aa][ \t]*[Tt][ \t]*[Aa][ \t]*[Nn]" ) \ + X (COSINE, "[Cc][ \t]*[Oo][ \t]*[Ss]" ) \ + X (EXCLUSIVE_OR, "[Xx][ \t]*[Oo][ \t]*[Rr]" ) \ + X (E_RAISED_TO, "[Ee][ \t]*[Xx][ \t]*[Pp]" ) \ + X (FIX_DOWN, "[Ff][ \t]*[Ii][ \t]*[Xx]" ) \ + X (FIX_UP, "[Ff][ \t]*[Uu][ \t]*[Pp]" ) \ + X (ROUND, "[Rr][ \t]*[Oo][ \t]*[Uu][ \t]*[Nn][ \t]*[Dd]" ) \ + X (SINE, "[Ss][ \t]*[Ii][ \t]*[Nn]" ) \ + X (SQUARE_ROOT, "[Ss][ \t]*[Qq][ \t]*[Rr][ \t]*[Tt]" ) \ + X (TANGENT, "[Tt][ \t]*[Aa][ \t]*[Nn]" ) \ + X (WORD_LETTER, "[ABCDFGHIJKLMPQRSTXYZabcdfghijklmpqrstxyz]" ) \ + X (REAL_NUMBER_NO_SIGN, "[0-9 \t]*(\\.[0-9 \t]*)?" ) \ + X (LINE_NUMBER, "[Nn][0-9 \t]+" ) \ + X (PARAMETER_SIGN, "#" ) \ + X (BRACKET_RIGHT, "\\]" ) \ + X (BRACKET_LEFT, "\\[" ) \ + X (EQUAL_SIGN, "=" ) \ + X (MINUS, "-" ) \ + X (PLUS, "\\+" ) \ + X (POWER, "\\*\\*" ) \ + X (TIMES, "\\*" ) \ + X (SLASH, "/" ) \ + +#define X(SYM, ...) RS274NGC_LEXEME_KIND_##SYM, +enum rs274ngc_lexeme_kind { + RS274NGC_LEXEME_KIND_INVALID, + RS274NGC_LEXEME_KIND_END_OF_LINE, + RS274NGC_LEXEME_KIND_END_OF_FILE, + RS274NGC_LEXEME_KINDS () + RS274NGC_LEXEME_KIND_COUNT, +}; +#undef X + +extern const char *rs274ngc_lexeme_kind_names[RS274NGC_LEXEME_KIND_COUNT]; + +#define RS274NGC_LEXEME_REGEX_OFFSET 3 +#define RS274NGC_LEXEME_REGEX_COUNT \ + (RS274NGC_LEXEME_KIND_COUNT - RS274NGC_LEXEME_REGEX_OFFSET) + +struct rs274ngc_lexeme { + struct sv sv; + enum rs274ngc_lexeme_kind kind; +}; + +#endif // INCLUDED_RS274NGC_LEXEME_H + +/// src/rs274ngc_lexeme.h ends here diff --git a/src/rs274ngc_lexer.c b/src/rs274ngc_lexer.c new file mode 100644 index 0000000..cbc7ade --- /dev/null +++ b/src/rs274ngc_lexer.c @@ -0,0 +1,147 @@ +/// src/rs274ngc_lexer.c --- RS274NGC lexer +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#include "rs274ngc_lexer.h" +#include +#include +#include +#include +#include +#include + +#define X(SYM, REG, ...) \ + [RS274NGC_LEXEME_KIND_##SYM - RS274NGC_LEXEME_REGEX_OFFSET] = "^(" REG ")", +static const char *lexeme_regex_strings[RS274NGC_LEXEME_REGEX_COUNT] = { + RS274NGC_LEXEME_KINDS () +}; +#undef X + +static regex_t lexeme_regexes[RS274NGC_LEXEME_REGEX_COUNT]; + +static void +print_regex_error (const regex_t *comp, const char *regex, int errcode) +{ + size_t length = regerror (errcode, comp, NULL, 0); + char *buffer = malloc (length); + regerror (errcode, comp, buffer, length); + fprintf (stderr, "error: regcomp (\"%s\"): %s\n", regex, buffer); + free (buffer); +} + +void +rs274ngc_lexer_compile_regexes (void) +{ + bool errored = false; + + for (int i = 0; i < RS274NGC_LEXEME_REGEX_COUNT; ++i) { + regex_t *compiled = &lexeme_regexes[i]; + const char *pattern = lexeme_regex_strings[i]; + int errcode = regcomp (compiled, pattern, REG_EXTENDED); + if (errcode) { + print_regex_error (compiled, pattern, errcode); + errored = true; + } + } + + if (errored) + exit (EXIT_FAILURE); +} + +struct rs274ngc_lexer +rs274ngc_lexer_from_sv (struct sv sv, const char *filename) +{ + struct rs274ngc_lexer lexer = { + .sv = sv, + .cursor = sv.beg, + .filename = filename, + }; + + rs274ngc_lexer_next_lexeme (&lexer); + return lexer; +} + +static void +skip_whitespace (struct rs274ngc_lexer *lexer) +{ + while (lexer->cursor < lexer->sv.end && (*lexer->cursor == ' ' || + *lexer->cursor == '\t')) + lexer->cursor += 1; +} + +void +rs274ngc_lexer_next_lexeme (struct rs274ngc_lexer *lexer) +{ + skip_whitespace (lexer); + lexer->lexeme = (struct rs274ngc_lexeme) { .sv.beg = lexer->cursor }; + + if (lexer->cursor >= lexer->sv.end) { + lexer->lexeme.kind = RS274NGC_LEXEME_KIND_END_OF_FILE; + lexer->lexeme.sv.end = lexer->sv.end; + return; + } + + if (*lexer->cursor == '\r') { + lexer->cursor += 1; + if (*lexer->cursor == '\n') + lexer->cursor += 1; + + lexer->lexeme.kind = RS274NGC_LEXEME_KIND_END_OF_LINE; + lexer->lexeme.sv.end = lexer->cursor; + return; + } + + if (*lexer->cursor == '\n') { + lexer->cursor += 1; + lexer->lexeme.kind = RS274NGC_LEXEME_KIND_END_OF_LINE; + lexer->lexeme.sv.end = lexer->cursor; + return; + } + + regmatch_t regmatch; + int longest_matching_regex = RS274NGC_LEXEME_REGEX_COUNT; + int longest_matching_regex_length = 0; + for (int i = 0; i < RS274NGC_LEXEME_REGEX_COUNT; ++i) { + if (regexec (&lexeme_regexes[i], lexer->cursor, 1, ®match, 0)) continue; + if (regmatch.rm_eo <= longest_matching_regex_length) continue; + + longest_matching_regex_length = regmatch.rm_eo; + longest_matching_regex = i; + +#ifdef RS274NGC_LEXER_FIRST_MATCH + break; +#endif + } + + if (longest_matching_regex != RS274NGC_LEXEME_REGEX_COUNT) { + lexer->lexeme.kind = longest_matching_regex + RS274NGC_LEXEME_REGEX_OFFSET; + lexer->lexeme.sv.end = lexer->cursor += longest_matching_regex_length; + +#ifdef RS274NGC_LEXER_TRIM + while (lexer->lexeme.sv.end > lexer->lexeme.sv.beg && + (lexer->lexeme.sv.end[-1] == ' ' || + lexer->lexeme.sv.end[-1] == '\t')) { + lexer->lexeme.sv.end -= 1; + } +#endif + + switch (lexer->lexeme.kind) { +#ifdef RS274NGC_LEXER_FILTER_COMMENTS + case RS274NGC_LEXEME_KIND_COMMENT: + return rs274ngc_lexer_next_lexeme (lexer); +#endif + default: return; + } + } + + // INVALID + lexer->lexeme.sv.end = ++lexer->cursor; +} + +/// src/rs274ngc_lexer.c ends here diff --git a/src/rs274ngc_lexer.h b/src/rs274ngc_lexer.h new file mode 100644 index 0000000..e8ee9a4 --- /dev/null +++ b/src/rs274ngc_lexer.h @@ -0,0 +1,35 @@ +/// src/rs274ngc_lexer.h --- RS274NGC lexer +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_RS274NGC_LEXER_H +#define INCLUDED_RS274NGC_LEXER_H + +#include +#include "sv.h" +#include "rs274ngc_lexeme.h" + +#define RS274NGC_LEXER_FIRST_MATCH +#define RS274NGC_LEXER_TRIM +// #define RS274NGC_LEXER_FILTER_COMMENTS + +struct rs274ngc_lexer { + struct sv sv; + const char *cursor; + const char *filename; + struct rs274ngc_lexeme lexeme; +}; + +void rs274ngc_lexer_compile_regexes (void); +struct rs274ngc_lexer rs274ngc_lexer_from_sv (struct sv, const char *filename); +void rs274ngc_lexer_next_lexeme (struct rs274ngc_lexer *); + +#endif // INCLUDED_RS274NGC_LEXER_H + +/// src/rs274ngc_lexer.h ends here diff --git a/src/rs274ngc_state.c b/src/rs274ngc_state.c new file mode 100644 index 0000000..5ab17c2 --- /dev/null +++ b/src/rs274ngc_state.c @@ -0,0 +1,455 @@ +#include "rs274ngc_state.h" + +#include +#include + +#include "utils.h" +#include "da.h" + +#define INDENTATION 2 +#define EPS 0.0001 + +static void +print_cst (struct arena *temp, struct rs274ngc_lexer *lexer, + struct rs274ngc_cst_branch *root, size_t alignment) +{ + void *bottom = ARENA_COPY (temp, root); + ARENA_COPY (temp, alignment); + while (temp->tail->free != bottom) { + alignment = *(size_t *) arena_pop (temp, sizeof (alignment)); + void *node = *(void **) arena_pop (temp, sizeof (node )); + ASSERT (node); + if (RS274NGC_CST_NODE_KIND (node) < RS274NGC_CST_TERMINAL_COUNT) { // leaf + struct rs274ngc_cst_leaf *leaf = &RS274NGC_CST_NODE_PTR (node)->leaf; + struct location location = find_location (lexer->sv, leaf->sv); + print_location (lexer->filename, location, alignment, "- leaf: %s", + rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); + } else { // branch + struct rs274ngc_cst_branch *branch = &RS274NGC_CST_NODE_PTR (node)->branch; + if (1 || RS274NGC_CST_NODE_KIND_EQ (node, LINE)) { + struct location location = find_location (lexer->sv, branch->sv); + print_location (lexer->filename, location, alignment, "- branch: %s", + rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); + } + alignment += INDENTATION; + for (size_t i = branch->count; i > 0; --i) { + ASSERT (branch->children[i - 1]); + ARENA_COPY (temp, branch->children[i - 1]); + ARENA_COPY (temp, alignment); + } + } + } +} + +struct binding_power { + int left, right; +}; + +static struct binding_power +kind_to_binding_power (enum rs274ngc_cst_node_kind kind) +{ + switch (kind) { + case RS274NGC_CST_NODE_KIND_POWER: return (struct binding_power) { 3, 3 }; + case RS274NGC_CST_NODE_KIND_TIMES: return (struct binding_power) { 2, 2 }; + case RS274NGC_CST_NODE_KIND_DIVIDED_BY: return (struct binding_power) { 2, 2 }; + case RS274NGC_CST_NODE_KIND_MODULO: return (struct binding_power) { 2, 2 }; + case RS274NGC_CST_NODE_KIND_PLUS: return (struct binding_power) { 1, 1 }; + case RS274NGC_CST_NODE_KIND_MINUS: return (struct binding_power) { 1, 1 }; + case RS274NGC_CST_NODE_KIND_EXCLUSIVE_OR: return (struct binding_power) { 1, 1 }; + case RS274NGC_CST_NODE_KIND_NON_EXCLUSIVE_OR: return (struct binding_power) { 1, 1 }; + case RS274NGC_CST_NODE_KIND_AND: return (struct binding_power) { 1, 1 }; + default: DIE ("invalid binop"); + } +} + +static double +apply_binop (enum rs274ngc_cst_node_kind kind, double lhs, double rhs) +{ + switch (kind) { + case RS274NGC_CST_NODE_KIND_POWER: return pow (lhs, rhs); + case RS274NGC_CST_NODE_KIND_TIMES: return lhs * rhs; + case RS274NGC_CST_NODE_KIND_DIVIDED_BY: return lhs / rhs; + case RS274NGC_CST_NODE_KIND_MODULO: return fmod (lhs, rhs); + case RS274NGC_CST_NODE_KIND_PLUS: return lhs + rhs; + case RS274NGC_CST_NODE_KIND_MINUS: return lhs - rhs; + case RS274NGC_CST_NODE_KIND_EXCLUSIVE_OR: return (lhs != 0) ^ (rhs != 0); + case RS274NGC_CST_NODE_KIND_NON_EXCLUSIVE_OR: return (lhs != 0) || (rhs != 0); + case RS274NGC_CST_NODE_KIND_AND: return (lhs != 0) && (rhs != 0); + default: DIE ("invalid binop"); + } +} + +double eval_real_value (struct rs274ngc_state *, struct rs274ngc_cst_branch *real_value); + +double +eval_expression (struct rs274ngc_state *state, + struct rs274ngc_cst_branch *expression, + size_t *i, int min_bp) +{ + struct rs274ngc_cst_branch *lhsn = &expression->children[(*i)++]->branch; + ASSERT (RS274NGC_CST_NODE_KIND_EQ (lhsn, REAL_VALUE)); + lhsn = &RS274NGC_CST_NODE_PTR (lhsn)->branch; + double lhs = eval_real_value (state, lhsn); + for (;;) { + struct rs274ngc_cst_branch *binop = &expression->children[*i]->branch; + if (RS274NGC_CST_NODE_KIND_EQ (binop, BRACKET_RIGHT)) + break; + ASSERT (RS274NGC_CST_NODE_KIND_EQ (binop, BINARY_OPERATION)); + binop = &RS274NGC_CST_NODE_PTR (binop)->branch; + enum rs274ngc_cst_node_kind kind = RS274NGC_CST_NODE_KIND (binop->children[0]); + struct binding_power bp = kind_to_binding_power (kind); + if (bp.left < min_bp) + break; + *i += 1; + double rhs = eval_expression (state, expression, i, bp.right); + // printf ("[%02lu] %lg %s %lg", *i, lhs, rs274ngc_cst_node_kind_names[kind], rhs); + lhs = apply_binop (kind, lhs, rhs); + // printf (" = %lg\n", lhs); + } + + return lhs; +} + +static double +apply_unary (enum rs274ngc_cst_node_kind kind, double arg) +{ + switch (kind) { + case RS274NGC_CST_NODE_KIND_ABSOLUTE_VALUE: return fabs (arg); + case RS274NGC_CST_NODE_KIND_ARC_COSINE: return acos (arg)/M_PI*180; + case RS274NGC_CST_NODE_KIND_ARC_SINE: return asin (arg)/M_PI*180; + case RS274NGC_CST_NODE_KIND_ARC_TANGENT: return atan (arg)/M_PI*180; + case RS274NGC_CST_NODE_KIND_COSINE: return cos (arg/180*M_PI); + case RS274NGC_CST_NODE_KIND_SINE: return sin (arg/180*M_PI); + case RS274NGC_CST_NODE_KIND_TANGENT: return tan (arg/180*M_PI); + case RS274NGC_CST_NODE_KIND_E_RAISED_TO: return exp (arg); + case RS274NGC_CST_NODE_KIND_NATURAL_LOG_OF: return log (arg); + case RS274NGC_CST_NODE_KIND_FIX_DOWN: return floor (arg); + case RS274NGC_CST_NODE_KIND_FIX_UP: return ceil (arg); + case RS274NGC_CST_NODE_KIND_ROUND: return round (arg); + case RS274NGC_CST_NODE_KIND_SQUARE_ROOT: return sqrt (arg); + default: DIE ("invalid binop"); + } +} + +static double +svtod (struct sv sv) +{ + double v = 0; + + while (sv.beg < sv.end && *sv.beg != '.') { + v *= 10; + v += *sv.beg - '0'; + sv.beg += 1; + } + + sv.beg += 1; + double d = 10; + while (sv.beg < sv.end) { + v += (*sv.beg - '0')/d; + d *= 10; + sv.beg += 1; + } + + return v; +} + +double +eval_real_value (struct rs274ngc_state *state, struct rs274ngc_cst_branch *real_value) +{ + double value; + + ASSERT (real_value->count == 1); + switch (RS274NGC_CST_NODE_KIND (real_value->children[0])) { + case RS274NGC_CST_NODE_KIND_REAL_NUMBER: { + struct rs274ngc_cst_branch *real_number = + &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; + double sign = 1; + struct rs274ngc_cst_leaf *real_number_no_sign; + if (real_number->count == 2) { + real_number_no_sign = &RS274NGC_CST_NODE_PTR (real_number->children[1])->leaf; + if (RS274NGC_CST_NODE_KIND_EQ (real_number->children[0], MINUS)) + sign = -1; + } else { + real_number_no_sign = &RS274NGC_CST_NODE_PTR (real_number->children[0])->leaf; + } + + char *tail = NULL; + // value = sign*strtod (real_number_no_sign->sv.beg, &tail); + value = sign*svtod (real_number_no_sign->sv); + } break; + case RS274NGC_CST_NODE_KIND_EXPRESSION: { + struct rs274ngc_cst_branch *expression = + &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; + ASSERT (RS274NGC_CST_NODE_KIND_EQ (expression->children[0], BRACKET_LEFT)); + size_t i = 1; + value = eval_expression (state, expression, &i, 0); + } break; + case RS274NGC_CST_NODE_KIND_PARAMETER_VALUE: { + struct rs274ngc_cst_branch *parameter_value = + &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; + struct rs274ngc_cst_branch *real_parameter_value = + &RS274NGC_CST_NODE_PTR (parameter_value->children[1])->branch; + double i = eval_real_value (state, real_parameter_value); + int nbi = nearbyint (i); + ASSERT (fabs (i - nbi) < EPS); + ASSERT (nbi <= (int) ARRAY_LENGTH (state->parameter_values)); + value = state->parameter_values[nbi - 1]; + } break; + case RS274NGC_CST_NODE_KIND_UNARY_COMBO: { + struct rs274ngc_cst_branch *unary_combo = + &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; + switch (RS274NGC_CST_NODE_KIND (unary_combo->children[0])) { + case RS274NGC_CST_NODE_KIND_ORDINARY_UNARY_COMBO: { + struct rs274ngc_cst_branch *ordinary_unary_combo = + &RS274NGC_CST_NODE_PTR (unary_combo->children[0])->branch; + enum rs274ngc_cst_node_kind uniop = RS274NGC_CST_NODE_KIND (ordinary_unary_combo->children[0]); + struct rs274ngc_cst_branch *expression = + &RS274NGC_CST_NODE_PTR (ordinary_unary_combo->children[1])->branch; + size_t i = 1; + double arg = eval_expression (state, expression, &i, 0); + value = apply_unary (uniop, arg); + } break; + case RS274NGC_CST_NODE_KIND_ARC_TANGENT_COMBO: { + struct rs274ngc_cst_branch *arc_tangent_combo = + &RS274NGC_CST_NODE_PTR (unary_combo->children[0])->branch; + struct rs274ngc_cst_branch *arg = &RS274NGC_CST_NODE_PTR (arc_tangent_combo->children[1])->branch; + struct rs274ngc_cst_branch *div = &RS274NGC_CST_NODE_PTR (arc_tangent_combo->children[3])->branch; + size_t i = 1; + double argv = eval_expression (state, arg, &i, 0); + i = 1; + double divv = eval_expression (state, div, &i, 0); + value = atan (argv)/M_PI*180/divv; + } break; + default: DIE ("invalid unary combo"); + } + } break; + default: DIE ("invalid real value"); + } + + return value; +} + +static void +eval_word (struct rs274ngc_state *state, struct rs274ngc_cst_branch *word) +{ + ASSERT (word->count == 2); + struct rs274ngc_cst_leaf *word_letter = &word->children[0]->leaf; + struct rs274ngc_cst_branch *real_value = &word->children[1]->branch; + ASSERT (RS274NGC_CST_NODE_KIND_EQ (word_letter, WORD_LETTER)); + ASSERT (RS274NGC_CST_NODE_KIND_EQ (real_value, REAL_VALUE )); + word_letter = &RS274NGC_CST_NODE_PTR (word_letter)->leaf; + ASSERT (SV_LENGTH (word_letter->sv) == 1); + char word_letter_char = toupper (word_letter->sv.beg[0]); + + // print_cst (parser.temporary, parser.lexer, real_value, 80); + real_value = &RS274NGC_CST_NODE_PTR (real_value)->branch; + double value = eval_real_value (state, real_value); + // printf ("%c%g\n", word_letter_char, value); + + switch (word_letter_char) { + case 'A': state->a = value; state->words_set |= A_MASK; break; + case 'B': state->b = value; state->words_set |= B_MASK; break; + case 'C': state->c = value; state->words_set |= C_MASK; break; + case 'D': state->d = value; state->words_set |= D_MASK; break; + case 'H': state->h = value; state->words_set |= H_MASK; break; + case 'I': state->i = value; state->words_set |= I_MASK; break; + case 'J': state->j = value; state->words_set |= J_MASK; break; + case 'K': state->k = value; state->words_set |= K_MASK; break; + case 'L': state->l = value; state->words_set |= L_MASK; break; + case 'N': state->n = value; state->words_set |= N_MASK; break; + case 'P': state->p = value; state->words_set |= P_MASK; break; + case 'Q': state->q = value; state->words_set |= Q_MASK; break; + case 'R': state->r = value; state->words_set |= R_MASK; break; + case 'F': state->f = value; state->words_set |= F_MASK; break; + case 'S': state->s = value; state->words_set |= S_MASK; break; + case 'T': state->t = value; state->words_set |= T_MASK; break; + case 'X': state->x = value; state->words_set |= X_MASK; break; + case 'Y': state->y = value; state->words_set |= Y_MASK; break; + case 'Z': state->z = value; state->words_set |= Z_MASK; break; + case 'G': { + switch ((int) nearbyint (10*value)) { + case 40: state->non_modal = NON_MODAL_DWELL; break; + case 100: state->non_modal = NON_MODAL_SET_COORDINATE_SYSTEM_DATA; break; + case 280: state->non_modal = NON_MODAL_RETURN_TO_HOME; break; + case 300: state->non_modal = NON_MODAL_RETURN_TO_SECONDARY_HOME; break; + case 530: state->non_modal = NON_MODAL_MOTION_IN_MACHINE_COORDINATE_SYSTEM; break; + case 920: state->non_modal = NON_MODAL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS; break; + case 921: state->non_modal = NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS_TO_ZERO; break; + case 922: state->non_modal = NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_BUT_DO_NOT_RESET_PARAMETERS; break; + case 923: state->non_modal = NON_MODAL_APPLY_PARAMETERS_TO_OFFSET_COORDINATE_SYSTEMS; break; + + case 0: state->current_motion_mode = MOTION_RAPID_POSITIONING; break; + case 10: state->current_motion_mode = MOTION_LINEAR_INTERPOLATION; break; + case 20: state->current_motion_mode = MOTION_CIRCULAR_INTERPOLATION_CW; break; + case 30: state->current_motion_mode = MOTION_CIRCULAR_INTERPOLATION_CCW; break; + case 382: state->current_motion_mode = MOTION_STRAIGHT_PROBE; break; + case 800: state->current_motion_mode = MOTION_CANCEL_MOTION_MODE; break; + case 810: state->current_motion_mode = MOTION_CANNED_CYCLE_DRILLING; break; + case 820: state->current_motion_mode = MOTION_CANNED_CYCLE_DRILLING_WITH_DWELL; break; + case 830: state->current_motion_mode = MOTION_CANNED_CYCLE_PECK_DRILLING; break; + case 840: state->current_motion_mode = MOTION_CANNED_CYCLE_RIGHT_HAND_TAPPING; break; + case 850: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_NO_DWELL_FEED_OUT; break; + case 860: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_RAPID_OUT; break; + case 870: state->current_motion_mode = MOTION_CANNED_CYCLE_BACK_BORING; break; + case 880: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_MANUAL_OUT; break; + case 890: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_DWELL_FEED_OUT; break; + + case 170: state->plane_selection = PLANE_SELECTION_XY; break; + case 180: state->plane_selection = PLANE_SELECTION_XZ; break; + case 190: state->plane_selection = PLANE_SELECTION_YZ; break; + + case 900: state->distance_mode = DISTANCE_MODE_ABSOLUTE; break; + case 910: state->distance_mode = DISTANCE_MODE_INCREMENTAL; break; + + case 930: state->feed_rate_mode = FEED_RATE_MODE_INVERSE_TIME; break; + case 940: state->feed_rate_mode = FEED_RATE_MODE_UNITS_PER_MINUTE; break; + + case 200: state->units = UNITS_INCH; break; + case 210: state->units = UNITS_MM; break; + + case 400: state->cutter_radius_compensation = CUTTER_RADIUS_COMPENSATION_CANCEL; break; + case 410: state->cutter_radius_compensation = CUTTER_RADIUS_COMPENSATION_START_LEFT; break; + case 420: state->cutter_radius_compensation = CUTTER_RADIUS_COMPENSATION_START_RIGHT; break; + + case 430: state->tool_length_offset = TOOL_LENGTH_OFFSET_PLUS; break; + case 490: state->tool_length_offset = TOOL_LENGTH_OFFSET_CANCEL; break; + + case 980: state->return_mode_in_canned_cycles = RETURN_MODE_IN_CANNED_CYCLES_INITIAL; break; + case 990: state->return_mode_in_canned_cycles = RETURN_MODE_IN_CANNED_CYCLES_R_POINT; break; + + case 540: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_1; break; + case 550: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_2; break; + case 560: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_3; break; + case 570: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_4; break; + case 580: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_5; break; + case 590: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_6; break; + case 591: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_7; break; + case 592: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_8; break; + case 593: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_9; break; + + case 610: state->path_control_mode = PATH_CONTROL_MODE_EXACT_PATH; break; + case 611: state->path_control_mode = PATH_CONTROL_MODE_EXACT_STOP; break; + case 640: state->path_control_mode = PATH_CONTROL_MODE_CONTINUOS; break; + + default: DIE ("invalid G-command: " SV_FMT, SV_FMTA (word->sv)); + }; + } break; + case 'M': { + switch ((int) value) { + case 0: state->stopping = STOPPING_STOP; break; + case 1: state->stopping = STOPPING_STOP_OPTIONAL; break; + case 2: state->stopping = STOPPING_END; break; + case 30: state->stopping = STOPPING_EXCHANGE_PALLETE_SHUTES_AND_END; break; + case 60: state->stopping = STOPPING_EXCHANGE_PALLETE_SHUTES_AND_STOP; break; + + case 6: state->tool_change = TOOL_CHANGE; break; + + case 3: state->spindle_turning = SPINDLE_TURNING_START_CW; break; + case 4: state->spindle_turning = SPINDLE_TURNING_START_CCW; break; + case 5: state->spindle_turning = SPINDLE_TURNING_STOP; break; + + case 7: state->coolant = state->coolant == COOLANT_ON_FLOOD ? COOLANT_ON_BOTH : COOLANT_ON_MIST; break; + case 8: state->coolant = state->coolant == COOLANT_ON_MIST ? COOLANT_ON_BOTH : COOLANT_ON_FLOOD; break; + case 9: state->coolant = COOLANT_OFF; break; + + case 48: state->override_switches = OVERRIDE_SWITCHES_ENABLE; break; + case 49: state->override_switches = OVERRIDE_SWITCHES_DISABLE; break; + default: DIE ("invalid M-command: " SV_FMT, SV_FMTA (word->sv)); + }; + } break; + } + // puts (""); +} + +struct parameter_spec { + int index; + double value; +}; + +static struct parameter_spec +eval_parameter_setting (struct rs274ngc_state *state, + struct rs274ngc_cst_branch *parameter_setting) +{ + // print_cst (parser.temporary, parser.lexer, &(*segment)->branch, 52); + struct rs274ngc_cst_branch *index = &RS274NGC_CST_NODE_PTR (parameter_setting->children[1])->branch; + struct rs274ngc_cst_branch *index_value = &RS274NGC_CST_NODE_PTR ( index->children[0])->branch; + struct rs274ngc_cst_branch *value = &RS274NGC_CST_NODE_PTR (parameter_setting->children[3])->branch; + double i = eval_real_value (state, index_value); + double v = eval_real_value (state, value); + int nbi = nearbyint (i); + ASSERT (fabs (i - nbi) < EPS); + ASSERT (nbi <= (int) ARRAY_LENGTH (state->parameter_values)); + // printf ("%d = %g\n", nbi, v); + return (struct parameter_spec) { nbi - 1, v }; +} + +int +rs274ngc_state_next (struct rs274ngc_state *state, + struct rs274ngc_cst_parser parser) +{ + // NOTE(cmmm): we might want to free this buffer at some point + static struct parameter_buffer { + struct parameter_spec *items; + uint32_t count; + uint32_t capacity; + } pb = {0}; + + // NOTE(cmmm): alignment should be passed to coalesce, not checkpoint + struct arena_checkpoint cp = arena_checkpoint (parser.output, 1); + while (parser.lexer->lexeme.kind != RS274NGC_LEXEME_KIND_END_OF_FILE) { + arena_rollback_to (parser.output, cp); + + struct rs274ngc_cst_branch *line = + &RS274NGC_CST_NODE_PTR (RS274NGC_CST_PARSE (parser, LINE))->branch; + if (!line) + continue; + union rs274ngc_cst_node **child = &line->children[0]; + union rs274ngc_cst_node **child_end = &line->children[line->count]; + // printf (SV_FMT "\n", SV_FMTA (line->sv)); + + if (RS274NGC_CST_NODE_KIND_EQ (*child, BLOCK_DELETE)) + continue; + + if (RS274NGC_CST_NODE_KIND_EQ (*child, LINE_NUMBER)) + child += 1; + + DA_RESET (pb); + state->non_modal = NON_MODAL_NIL; + state->words_set = 0; + state->i = 0; + state->j = 0; + state->k = 0; + + state->line = line->sv; + + for (; child < child_end; ++child) { + ASSERT (RS274NGC_CST_NODE_KIND_EQ (*child, SEGMENT)); + struct rs274ngc_cst_branch *child_ptr = &RS274NGC_CST_NODE_PTR (*child)->branch; + union rs274ngc_cst_node **segment = &child_ptr->children[0]; + union rs274ngc_cst_node **segment_end = &child_ptr->children[child_ptr->count]; + for (; segment < segment_end; ++segment) { + struct rs274ngc_cst_branch *segment_ptr = + &RS274NGC_CST_NODE_PTR (*segment)->branch; + switch (RS274NGC_CST_NODE_KIND (*segment)) { + case RS274NGC_CST_NODE_KIND_WORD: + eval_word (state, segment_ptr); + break; + case RS274NGC_CST_NODE_KIND_PARAMETER_SETTING: + DA_APPEND (pb, eval_parameter_setting (state, segment_ptr)); + break; + case RS274NGC_CST_NODE_KIND_COMMENT: + break; + default: + DIE ("malformed segment"); + } + } + } + + DA_FOR_EACH (spec, pb) + state->parameter_values[spec->index] = spec->value; + + return 1; + } + + return 0; +} diff --git a/src/rs274ngc_state.h b/src/rs274ngc_state.h new file mode 100644 index 0000000..477c207 --- /dev/null +++ b/src/rs274ngc_state.h @@ -0,0 +1,204 @@ +/// src/rs274ngc_state.h +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_RS274NGC_STATE_H +#define INCLUDED_RS274NGC_STATE_H + +#include "rs274ngc_cst.h" + +#define A_MASK (1 << 0) +#define B_MASK (1 << 1) +#define C_MASK (1 << 2) +#define D_MASK (1 << 3) +#define H_MASK (1 << 4) +#define I_MASK (1 << 5) +#define J_MASK (1 << 6) +#define K_MASK (1 << 7) +#define L_MASK (1 << 8) +#define N_MASK (1 << 9) +#define P_MASK (1 << 10) +#define Q_MASK (1 << 11) +#define R_MASK (1 << 12) +#define F_MASK (1 << 13) +#define S_MASK (1 << 14) +#define T_MASK (1 << 15) +#define X_MASK (1 << 16) +#define Y_MASK (1 << 17) +#define Z_MASK (1 << 18) + +#define AXIS_MASK (A_MASK | B_MASK | C_MASK | X_MASK | Y_MASK | Z_MASK) + +struct rs274ngc_state { + struct sv line; + + enum non_modal { // group 0 + NON_MODAL_NIL, + NON_MODAL_DWELL, // G4 + NON_MODAL_SET_COORDINATE_SYSTEM_DATA, // G10 + NON_MODAL_RETURN_TO_HOME, // G28 + NON_MODAL_RETURN_TO_SECONDARY_HOME, // G30 + NON_MODAL_MOTION_IN_MACHINE_COORDINATE_SYSTEM, // G53 + NON_MODAL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS, // G92 + NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS_TO_ZERO, // G92.1 + NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_BUT_DO_NOT_RESET_PARAMETERS, // G92.2 + NON_MODAL_APPLY_PARAMETERS_TO_OFFSET_COORDINATE_SYSTEMS, // G92.3 + } non_modal; + + enum motion { // group 1 + MOTION_RAPID_POSITIONING, // G0 + MOTION_LINEAR_INTERPOLATION, // G1 + MOTION_CIRCULAR_INTERPOLATION_CW, // G2 + MOTION_CIRCULAR_INTERPOLATION_CCW, // G3 + MOTION_STRAIGHT_PROBE, // G38.2 + MOTION_CANCEL_MOTION_MODE, // G80 (including any canned cycle) + MOTION_CANNED_CYCLE_DRILLING, // G81 + MOTION_CANNED_CYCLE_DRILLING_WITH_DWELL, // G82 + MOTION_CANNED_CYCLE_PECK_DRILLING, // G83 + MOTION_CANNED_CYCLE_RIGHT_HAND_TAPPING, // G84 + MOTION_CANNED_CYCLE_BORING_NO_DWELL_FEED_OUT, // G85 + MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_RAPID_OUT, // G86 + MOTION_CANNED_CYCLE_BACK_BORING, // G87 + MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_MANUAL_OUT, // G88 + MOTION_CANNED_CYCLE_BORING_DWELL_FEED_OUT, // G89 + } current_motion_mode; + + enum plane_selection { // group 2 + PLANE_SELECTION_XY, // G17 + PLANE_SELECTION_XZ, // G18 + PLANE_SELECTION_YZ, // G19 + } plane_selection; + + enum distance_mode { // group 3 + DISTANCE_MODE_ABSOLUTE, // G90 + DISTANCE_MODE_INCREMENTAL, // G91 + } distance_mode; + + enum feed_rate_mode { // group 5 + FEED_RATE_MODE_INVERSE_TIME, // G93 + FEED_RATE_MODE_UNITS_PER_MINUTE, // G94 + } feed_rate_mode; + + enum units { // group 6 + UNITS_INCH, // G20 + UNITS_MM, // G21 + } units; + + enum cutter_radius_compensation { // group 7 + CUTTER_RADIUS_COMPENSATION_CANCEL, // G40 + CUTTER_RADIUS_COMPENSATION_START_LEFT, // G41 + CUTTER_RADIUS_COMPENSATION_START_RIGHT, // G42 + } cutter_radius_compensation; + + enum tool_length_offset { // group 8 + TOOL_LENGTH_OFFSET_PLUS, // G43 + TOOL_LENGTH_OFFSET_CANCEL, // G49 + } tool_length_offset; + + enum return_mode_in_canned_cycles { // group 10 + RETURN_MODE_IN_CANNED_CYCLES_INITIAL, // G98 + RETURN_MODE_IN_CANNED_CYCLES_R_POINT, // G99 + } return_mode_in_canned_cycles; + + enum coordinate_system { // group 12 + COORDINATE_SYSTEM_PRESET_WORK_1, // G54 + COORDINATE_SYSTEM_PRESET_WORK_2, // G55 + COORDINATE_SYSTEM_PRESET_WORK_3, // G56 + COORDINATE_SYSTEM_PRESET_WORK_4, // G57 + COORDINATE_SYSTEM_PRESET_WORK_5, // G58 + COORDINATE_SYSTEM_PRESET_WORK_6, // G59 + COORDINATE_SYSTEM_PRESET_WORK_7, // G59.1 + COORDINATE_SYSTEM_PRESET_WORK_8, // G59.2 + COORDINATE_SYSTEM_PRESET_WORK_9, // G59.3 + } coordinate_system; + + enum path_control_mode { // group 13 + PATH_CONTROL_MODE_EXACT_PATH, // G61 + PATH_CONTROL_MODE_EXACT_STOP, // G61.1 + PATH_CONTROL_MODE_CONTINUOS, // G64 + } path_control_mode; + + enum stopping { // group 4 + STOPPING_NIL, + STOPPING_STOP, // M0 + STOPPING_STOP_OPTIONAL, // M1 + STOPPING_END, // M2 + STOPPING_EXCHANGE_PALLETE_SHUTES_AND_END, // M30 + STOPPING_EXCHANGE_PALLETE_SHUTES_AND_STOP, // M60 + } stopping; + + enum tool_change { // group 6 + TOOL_CHANGE_NIL, + TOOL_CHANGE, // M6 + } tool_change; + + enum spindle_turning { // group 7 + SPINDLE_TURNING_NIL, + SPINDLE_TURNING_START_CW, // M3 + SPINDLE_TURNING_START_CCW, // M4 + SPINDLE_TURNING_STOP, // M5 + } spindle_turning; + + // NOTE(cmmm):special case: M7 and M8 may be active at the same time + enum coolant { // group 8 + COOLANT_OFF, // M9 + COOLANT_ON_MIST, // M7 + COOLANT_ON_FLOOD, // M8 + COOLANT_ON_BOTH, + } coolant; + + enum override_switches { // group 9 + OVERRIDE_SWITCHES_DISABLE, // M49 + OVERRIDE_SWITCHES_ENABLE, // M48 + } override_switches; + + int words_set; + + double a; // A-axis of machine + double b; // B-axis of machine + double c; // C-axis of machine + + double d; // tool radius compensation number + double h; // tool length offset index + + double i; // X-axis offset for arcs / X offset in G87 canned cycle + double j; // Y-axis offset for arcs / Y offset in G87 canned cycle + double k; // Z-axis offset for arcs / Z offset in G87 canned cycle + + double l; // number of repetitions in canned cycles, key used with G10 + + double n; // line number + + double p; // dwell time in canned cycles, dwell time with G4, key used with G10 + + double q; // feed increment in G83 canned cycle + + double r; // arc radius, canned cycle plane + + double f; // feed rate + double s; // spindle speed + double t; // tool selection + + double x; // X-axis of machine + double y; // Y-axis of machine + double z; // Z-axis of machine + + struct coordinate_system_data { + double x, y, z; + double a, b, c; + } coordinate_system_data[9]; + + double parameter_values[5400]; +}; + +int rs274ngc_state_next (struct rs274ngc_state *, struct rs274ngc_cst_parser); + +#endif // INCLUDED_RS274NGC_STATE_H + +/// src/rs274ngc_state.h ends here 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 diff --git a/src/skywrite.c b/src/skywrite.c new file mode 100644 index 0000000..196ac78 --- /dev/null +++ b/src/skywrite.c @@ -0,0 +1,81 @@ +/// src/skywrite.h +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#include +#include +#include +#include + +#include "utils.h" +#include "da.h" +#include "rs274ngc_lexer.h" +#include "rs274ngc_cst.h" +#include "path.h" +#include "critical_points.h" +#include "compensations.h" +#include "generator.h" + +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)); + } +} + +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, + }; + + struct path path = build_path (parser); + struct critical_points cps = find_critical_points (&path); + struct compensations comps = synthesize_compensations (&cps); + struct replacements reps = generate_replacements (&a, &comps); + write_code_with_replacements (0, rs274ngc, &reps); + + return EXIT_SUCCESS; +} + +/// src/skywrite.h ends here diff --git a/src/sv.h b/src/sv.h new file mode 100644 index 0000000..c01b0d1 --- /dev/null +++ b/src/sv.h @@ -0,0 +1,26 @@ +/// src/sv.h --- simple String View library +// +// Copyright (C) 2026 by Martin Michalec +// +// SPDX-License-Identifier: MIT +// +/// Commentary: +// +/// Code: + +#ifndef INCLUDED_SV_H +#define INCLUDED_SV_H + +#define SV_LENGTH(SV) ((SV).end - (SV).beg) + +#define SV_FMT "%.*s" +#define SV_FMTA(SV) (int) SV_LENGTH (SV), (SV).beg + +struct sv { + const char *beg; + const char *end; +}; + +#endif // INCLUDED_SV_H + +/// src/sv.h ends here diff --git a/src/transition.c b/src/transition.c new file mode 100644 index 0000000..9910b27 --- /dev/null +++ b/src/transition.c @@ -0,0 +1,777 @@ +#include "transition.h" + +#include +#include +#include + +#define TR_EPS 1e-10 +#define TR_TIME_EPS 1e-9 +#define TR_SOL_EPS 1e-8 +#define TR_MAX_SCAN 2048 +#define TR_MAX_BISECT 96 +#define TR_INF 1e100 + +static double +tr_abs (double x) +{ + return x < 0.0 ? -x : x; +} + +static int +tr_finite_pos (double x) +{ + return isfinite (x) && x > 0.0; +} + +static double +tr_clamp (double x, double lo, double hi) +{ + return x < lo ? lo : (x > hi ? hi : x); +} + +static int +tr_limits_valid (double vmax, double amax, double jmax) +{ + return tr_finite_pos (vmax) && tr_finite_pos (amax) && tr_finite_pos (jmax); +} + +struct tr_axis_limits { + double vmax; + double amax; + double jmax; +}; + +struct tr_change { + double dt; + double ds; +}; + +static struct tr_change +tr_speed_change (double v0, double v1, const struct tr_axis_limits *l) +{ + struct tr_change c = {0}; + double dv = tr_abs (v1 - v0); + + if (dv <= TR_EPS) + return c; + + double dv_tri = l->amax*l->amax/l->jmax; + + if (dv <= dv_tri) { + double tj = sqrt (dv/l->jmax); + c.dt = 2.0*tj; + } else { + double tj = l->amax/l->jmax; + double ta = dv/l->amax - tj; + c.dt = 2.0*tj + ta; + } + + c.ds = 0.5*(v0 + v1)*c.dt; + return c; +} + +static double +tr_axis_fixed_f (double vm, + double q0, + double q1, + double v0, + double v1, + double T, + const struct tr_axis_limits *l, + int *admissible_out) +{ + struct tr_change c0 = tr_speed_change (v0, vm, l); + struct tr_change c1 = tr_speed_change (vm, v1, l); + double tc = T - c0.dt - c1.dt; + + if (admissible_out) + *admissible_out = tc >= -1e-8; + + return c0.ds + c1.ds + vm*tc - (q1 - q0); +} + +static int +tr_fixed_vm_candidate (double vm, + double q0, + double q1, + double v0, + double v1, + double T, + const struct tr_axis_limits *l, + double *err_out, + double *tc_out) +{ + if (vm < -l->vmax - 1e-9 || vm > l->vmax + 1e-9) + return 0; + + struct tr_change c0 = tr_speed_change (v0, vm, l); + struct tr_change c1 = tr_speed_change (vm, v1, l); + double tc = T - c0.dt - c1.dt; + if (tc < -1e-8) + return 0; + + double q = c0.ds + c1.ds + vm*tc; + double err = q - (q1 - q0); + + if (err_out) *err_out = err; + if (tc_out) *tc_out = tc > 0.0 ? tc : 0.0; + return 1; +} + +static int +tr_find_fixed_vm (double q0, + double q1, + double v0, + double v1, + double T, + const struct tr_axis_limits *l, + double *vm_out, + double *tc_out) +{ + double best_vm = 0.0; + double best_tc = 0.0; + double best_abs = TR_INF; + int found_exact = 0; + + double prev_vm = 0.0; + double prev_f = 0.0; + int prev_ok = 0; + + for (int i = 0; i <= TR_MAX_SCAN; ++i) { + double u = (double) i / (double) TR_MAX_SCAN; + double vm = -l->vmax + 2.0*l->vmax*u; + double f = 0.0; + double tc = 0.0; + int ok = tr_fixed_vm_candidate (vm, q0, q1, v0, v1, T, l, &f, &tc); + + if (ok) { + double af = tr_abs (f); + if (af < best_abs) { + best_abs = af; + best_vm = vm; + best_tc = tc; + } + + if (af <= TR_SOL_EPS*fmax (1.0, tr_abs (q1 - q0))) { + *vm_out = vm; + *tc_out = tc; + return 1; + } + + if (prev_ok && ((prev_f <= 0.0 && f >= 0.0) || (prev_f >= 0.0 && f <= 0.0))) { + double lo = prev_vm; + double hi = vm; + double flo = prev_f; + double fhi = f; + + for (int k = 0; k < TR_MAX_BISECT; ++k) { + double mid = 0.5*(lo + hi); + int adm = 0; + double fm = tr_axis_fixed_f (mid, q0, q1, v0, v1, T, l, &adm); + if (!adm) { + /* This should not normally happen inside an admissible bracket. */ + break; + } + + if (tr_abs (fm) <= TR_SOL_EPS*fmax (1.0, tr_abs (q1 - q0))) { + double ignored_err = 0.0; + tr_fixed_vm_candidate (mid, q0, q1, v0, v1, T, l, &ignored_err, &tc); + *vm_out = mid; + *tc_out = tc; + return 1; + } + + if ((flo <= 0.0 && fm >= 0.0) || (flo >= 0.0 && fm <= 0.0)) { + hi = mid; + fhi = fm; + } else { + lo = mid; + flo = fm; + } + (void) fhi; + } + + double mid = 0.5*(lo + hi); + double ignored_err = 0.0; + tr_fixed_vm_candidate (mid, q0, q1, v0, v1, T, l, &ignored_err, &tc); + *vm_out = mid; + *tc_out = tc; + return 1; + } + } + + prev_vm = vm; + prev_f = f; + prev_ok = ok; + } + + if (best_abs <= 1e-6*fmax (1.0, tr_abs (q1 - q0))) { + *vm_out = best_vm; + *tc_out = best_tc; + found_exact = 1; + } + + return found_exact; +} + +static int +tr_axis_feasible_at (double q0, + double q1, + double v0, + double v1, + double T, + const struct tr_axis_limits *l) +{ + double vm, tc; + return tr_find_fixed_vm (q0, q1, v0, v1, T, l, &vm, &tc); +} + +static int +tr_axis_min_duration (double q0, + double q1, + double v0, + double v1, + const struct tr_axis_limits *l, + double *T_out) +{ + if (tr_abs (v0) > l->vmax + 1e-8 || tr_abs (v1) > l->vmax + 1e-8) + return TR_ERR_INFEASIBLE; + + double lo = 0.0; + double hi = 1e-9; + + /* Lower bound must at least allow the velocity change through some vm. */ + struct tr_change direct = tr_speed_change (v0, v1, l); + lo = 0.0; + hi = fmax (direct.dt, 1e-6); + + while (!tr_axis_feasible_at (q0, q1, v0, v1, hi, l)) { + hi *= 2.0; + if (!(hi < 1e9) || !isfinite (hi)) + return TR_ERR_NO_PROFILE; + } + + for (int k = 0; k < TR_MAX_BISECT; ++k) { + double mid = 0.5*(lo + hi); + if (tr_axis_feasible_at (q0, q1, v0, v1, mid, l)) + hi = mid; + else + lo = mid; + } + + *T_out = hi; + return TR_OK; +} + +static int +tr_axis_push_phase (struct tr_axis_plan *p, + double dt, + double j, + double *q, + double *v, + double *a, + double *t) +{ + if (dt <= 1e-10) + return TR_OK; + + if (p->count >= (uint32_t) (sizeof p->phases / sizeof p->phases[0])) + return TR_ERR_NUMERIC; + + struct tr_axis_phase *ph = &p->phases[p->count++]; + ph->t_begin = *t; + ph->dt = dt; + ph->q0 = *q; + ph->v0 = *v; + ph->a0 = *a; + ph->j = j; + + double dt2 = dt*dt; + double dt3 = dt2*dt; + *q = *q + (*v)*dt + 0.5*(*a)*dt2 + (j*dt3)/6.0; + *v = *v + (*a)*dt + 0.5*j*dt2; + *a = *a + j*dt; + *t = *t + dt; + return TR_OK; +} + +static int +tr_axis_append_speed_change (struct tr_axis_plan *p, + double v_to, + const struct tr_axis_limits *l, + double *q, + double *v, + double *a, + double *t) +{ + double dv = v_to - *v; + double adv = tr_abs (dv); + if (adv <= 1e-10) { + *v = v_to; + *a = 0.0; + return TR_OK; + } + + double sgn = dv >= 0.0 ? 1.0 : -1.0; + double dv_tri = l->amax*l->amax/l->jmax; + + if (adv <= dv_tri) { + double tj = sqrt (adv/l->jmax); + int rc = tr_axis_push_phase (p, tj, sgn*l->jmax, q, v, a, t); + if (rc != TR_OK) return rc; + rc = tr_axis_push_phase (p, tj, -sgn*l->jmax, q, v, a, t); + if (rc != TR_OK) return rc; + } else { + double tj = l->amax/l->jmax; + double ta = adv/l->amax - tj; + int rc = tr_axis_push_phase (p, tj, sgn*l->jmax, q, v, a, t); + if (rc != TR_OK) return rc; + rc = tr_axis_push_phase (p, ta, 0.0, q, v, a, t); + if (rc != TR_OK) return rc; + rc = tr_axis_push_phase (p, tj, -sgn*l->jmax, q, v, a, t); + if (rc != TR_OK) return rc; + } + + *v = v_to; + *a = 0.0; + return TR_OK; +} + +static int +tr_axis_build_fixed (struct tr_axis_plan *out, + double q0, + double q1, + double v0, + double v1, + double T, + const struct tr_axis_limits *l) +{ + if (tr_abs (v0) > l->vmax + 1e-8 || tr_abs (v1) > l->vmax + 1e-8) + return TR_ERR_INFEASIBLE; + + double vm = 0.0; + double tc = 0.0; + if (!tr_find_fixed_vm (q0, q1, v0, v1, T, l, &vm, &tc)) + return TR_ERR_NO_PROFILE; + + memset (out, 0, sizeof *out); + out->duration = T; + out->q0 = q0; + out->q1 = q1; + out->v0 = v0; + out->v1 = v1; + + double q = q0; + double v = v0; + double a = 0.0; + double t = 0.0; + + int rc = tr_axis_append_speed_change (out, vm, l, &q, &v, &a, &t); + if (rc != TR_OK) return rc; + + rc = tr_axis_push_phase (out, tc, 0.0, &q, &v, &a, &t); + if (rc != TR_OK) return rc; + + rc = tr_axis_append_speed_change (out, v1, l, &q, &v, &a, &t); + if (rc != TR_OK) return rc; + + /* Clamp accumulated numerical error at the boundary. */ + if (out->count > 0u) { + out->duration = T; + } + + if (tr_abs (t - T) > 2e-6*fmax (1.0, T)) + return TR_ERR_NUMERIC; + if (tr_abs (q - q1) > 2e-5*fmax (1.0, tr_abs (q1 - q0))) + return TR_ERR_NUMERIC; + if (tr_abs (v - v1) > 2e-6*fmax (1.0, tr_abs (v1))) + return TR_ERR_NUMERIC; + if (tr_abs (a) > 2e-6*fmax (1.0, l->amax)) + return TR_ERR_NUMERIC; + + return TR_OK; +} + +static void +tr_axis_eval (const struct tr_axis_plan *p, + double t, + double *q_out, + double *v_out, + double *a_out, + double *j_out) +{ + if (!p || p->count == 0u) { + if (q_out) *q_out = p ? p->q0 : 0.0; + if (v_out) *v_out = p ? p->v0 : 0.0; + if (a_out) *a_out = 0.0; + if (j_out) *j_out = 0.0; + return; + } + + if (t <= 0.0) { + if (q_out) *q_out = p->q0; + if (v_out) *v_out = p->v0; + if (a_out) *a_out = 0.0; + if (j_out) *j_out = 0.0; + return; + } + + if (t >= p->duration) { + if (q_out) *q_out = p->q1; + if (v_out) *v_out = p->v1; + if (a_out) *a_out = 0.0; + if (j_out) *j_out = 0.0; + return; + } + + const struct tr_axis_phase *ph = &p->phases[p->count - 1u]; + for (uint32_t i = 0; i < p->count; ++i) { + const struct tr_axis_phase *cand = &p->phases[i]; + if (t < cand->t_begin + cand->dt + 1e-12) { + ph = cand; + break; + } + } + + double tau = tr_clamp (t - ph->t_begin, 0.0, ph->dt); + double tau2 = tau*tau; + double tau3 = tau2*tau; + + if (q_out) *q_out = ph->q0 + ph->v0*tau + 0.5*ph->a0*tau2 + (ph->j*tau3)/6.0; + if (v_out) *v_out = ph->v0 + ph->a0*tau + 0.5*ph->j*tau2; + if (a_out) *a_out = ph->a0 + ph->j*tau; + if (j_out) *j_out = ph->j; +} + + +static double +tr_speed_at_time (const struct tr_transition *tr, double t) +{ + double vx = 0.0; + double vy = 0.0; + + tr_axis_eval (&tr->x, t, NULL, &vx, NULL, NULL); + tr_axis_eval (&tr->y, t, NULL, &vy, NULL, NULL); + + return hypot (vx, vy); +} + +static double +tr_integrate_speed (const struct tr_transition *tr, double t0, double t1) +{ + if (!tr || !(t1 > t0)) + return 0.0; + + /* 16-point Gauss-Legendre rule on [t0, t1]. On every joint phase interval + * vx(t) and vy(t) are quadratic polynomials, so the integrand is smooth. + */ + static const double x[8] = { + 0.095012509837637440185, + 0.281603550779258913230, + 0.458016777657227386342, + 0.617876244402643748447, + 0.755404408355003033895, + 0.865631202387831743880, + 0.944575023073232576078, + 0.989400934991649932596 + }; + static const double w[8] = { + 0.189450610455068496285, + 0.182603415044923588867, + 0.169156519395002538189, + 0.149595988816576732081, + 0.124628971255533872052, + 0.095158511682492784810, + 0.062253523938647892863, + 0.027152459411754094852 + }; + + double c = 0.5*(t0 + t1); + double h = 0.5*(t1 - t0); + double sum = 0.0; + + for (int i = 0; i < 8; ++i) { + double dx = h*x[i]; + sum += w[i] * (tr_speed_at_time (tr, c - dx) + + tr_speed_at_time (tr, c + dx)); + } + + return h*sum; +} + +static double +tr_lookup_time_in_dense_table (const double *ts, + const double *ss, + uint32_t n, + double s) +{ + if (!ts || !ss || n == 0u) + return 0.0; + + if (s <= ss[0]) + return ts[0]; + if (s >= ss[n - 1u]) + return ts[n - 1u]; + + uint32_t lo = 0u; + uint32_t hi = n - 1u; + + while (lo + 1u < hi) { + uint32_t mid = lo + (hi - lo)/2u; + if (ss[mid] <= s) + lo = mid; + else + hi = mid; + } + + double s0 = ss[lo]; + double s1 = ss[hi]; + double t0 = ts[lo]; + double t1 = ts[hi]; + + if (!(s1 > s0)) + return t0; + + double u = (s - s0)/(s1 - s0); + return t0 + u*(t1 - t0); +} + +static int +tr_build_s_table (struct tr_transition *tr) +{ + if (!tr) + return TR_ERR_INVALID_ARG; + + tr->length = 0.0; + tr->s_node_count = 0u; + tr->s_step = 0.0; + + if (!(tr->duration > 0.0) || !isfinite (tr->duration)) { + tr->s_node_count = 1u; + tr->s_nodes[0].s = 0.0; + tr->s_nodes[0].t = 0.0; + return TR_OK; + } + + /* First build a dense cumulative table in time. This is done once at build + * time. Runtime sampling by s does not integrate and does not bisect with + * quadrature anymore. + */ + double ts[TR_S_TABLE_CAP]; + double ss[TR_S_TABLE_CAP]; + const uint32_t n = TR_S_TABLE_CAP; + + ts[0] = 0.0; + ss[0] = 0.0; + + double s_acc = 0.0; + double t_prev = 0.0; + + for (uint32_t i = 1u; i < n; ++i) { + double t = tr->duration * ((double) i / (double) (n - 1u)); + double ds = tr_integrate_speed (tr, t_prev, t); + + if (!isfinite (ds) || ds < -1e-9) + return TR_ERR_NUMERIC; + + if (ds < 0.0) + ds = 0.0; + + s_acc += ds; + ts[i] = t; + ss[i] = s_acc; + t_prev = t; + } + + tr->length = s_acc; + + if (!(tr->length > 0.0) || !isfinite (tr->length)) { + tr->s_node_count = 1u; + tr->s_step = 0.0; + tr->s_nodes[0].s = 0.0; + tr->s_nodes[0].t = 0.0; + return TR_OK; + } + + tr->s_node_count = n; + tr->s_step = tr->length / (double) (n - 1u); + + for (uint32_t i = 0u; i < n; ++i) { + double s_target = tr->s_step * (double) i; + if (i + 1u == n) + s_target = tr->length; + + tr->s_nodes[i].s = s_target; + tr->s_nodes[i].t = tr_lookup_time_in_dense_table (ts, ss, n, s_target); + } + + tr->s_nodes[0].s = 0.0; + tr->s_nodes[0].t = 0.0; + tr->s_nodes[n - 1u].s = tr->length; + tr->s_nodes[n - 1u].t = tr->duration; + + return TR_OK; +} + +double +tr_length_at_time (const struct tr_transition *tr, double t) +{ + if (!tr || tr->s_node_count == 0u) + return 0.0; + + if (tr->length <= 0.0) + return 0.0; + + t = tr_clamp (t, 0.0, tr->duration); + + if (t <= 0.0) + return 0.0; + if (t >= tr->duration) + return tr->length; + + uint32_t lo = 0u; + uint32_t hi = tr->s_node_count - 1u; + + while (lo + 1u < hi) { + uint32_t mid = lo + (hi - lo)/2u; + if (tr->s_nodes[mid].t <= t) + lo = mid; + else + hi = mid; + } + + const struct tr_s_node *a = &tr->s_nodes[lo]; + const struct tr_s_node *b = &tr->s_nodes[hi]; + + if (!(b->t > a->t)) + return a->s; + + double u = (t - a->t)/(b->t - a->t); + return tr_clamp (a->s + u*(b->s - a->s), 0.0, tr->length); +} + +double +tr_time_at_length (const struct tr_transition *tr, double s) +{ + if (!tr || tr->s_node_count == 0u) + return 0.0; + + if (tr->length <= 0.0) + return 0.0; + + s = tr_clamp (s, 0.0, tr->length); + + if (s <= 0.0) + return 0.0; + if (s >= tr->length) + return tr->duration; + + /* The table is uniform by arclength, so the common path is O(1). */ + double u = s / tr->s_step; + uint32_t i = (uint32_t) floor (u); + + if (i + 1u >= tr->s_node_count) + return tr->duration; + + double f = u - (double) i; + const struct tr_s_node *a = &tr->s_nodes[i]; + const struct tr_s_node *b = &tr->s_nodes[i + 1u]; + + return a->t + f*(b->t - a->t); +} + +void +tr_sample_at_s (const struct tr_transition *tr, double s, struct tr_sample *out) +{ + if (!out) + return; + + memset (out, 0, sizeof *out); + if (!tr) + return; + + double s_clamped = tr_clamp (s, 0.0, tr->length); + double t = tr_time_at_length (tr, s_clamped); + tr_sample (tr, t, out); + out->s = s_clamped; +} + +int +tr_build (struct tr_transition *out, + struct vec2 r0, + struct vec2 r1, + struct vec2 v0, + struct vec2 v1, + double vmax, + double amax, + double jmax) +{ + if (!out) + return TR_ERR_INVALID_ARG; + if (!tr_limits_valid (vmax, amax, jmax)) + return TR_ERR_LIMITS; + + memset (out, 0, sizeof *out); + out->vmax = vmax; + out->amax = amax; + out->jmax = jmax; + + struct tr_axis_limits lim = { vmax, amax, jmax }; + + double tx = 0.0; + double ty = 0.0; + int rc = tr_axis_min_duration (r0.x, r1.x, v0.x, v1.x, &lim, &tx); + if (rc != TR_OK) return rc; + rc = tr_axis_min_duration (r0.y, r1.y, v0.y, v1.y, &lim, &ty); + if (rc != TR_OK) return rc; + + double T = fmax (tx, ty); + + /* Add a tiny numerical margin so the shorter axis can be reconstructed at T. */ + T += 1e-8*fmax (1.0, T); + + rc = tr_axis_build_fixed (&out->x, r0.x, r1.x, v0.x, v1.x, T, &lim); + if (rc != TR_OK) return rc; + rc = tr_axis_build_fixed (&out->y, r0.y, r1.y, v0.y, v1.y, T, &lim); + if (rc != TR_OK) return rc; + + out->duration = T; + + rc = tr_build_s_table (out); + if (rc != TR_OK) + return rc; + + return TR_OK; +} + +void +tr_sample (const struct tr_transition *tr, double t, struct tr_sample *out) +{ + if (!out) + return; + + memset (out, 0, sizeof *out); + if (!tr) + return; + + t = tr_clamp (t, 0.0, tr->duration); + out->t = t; + out->s = tr_length_at_time (tr, t); + + tr_axis_eval (&tr->x, t, &out->r.x, &out->v.x, &out->a.x, &out->j.x); + tr_axis_eval (&tr->y, t, &out->r.y, &out->v.y, &out->a.y, &out->j.y); +} + +const char * +tr_status_string (int status) +{ + switch (status) { + case TR_OK: return "ok"; + case TR_ERR_INVALID_ARG: return "invalid argument"; + case TR_ERR_LIMITS: return "invalid limits"; + case TR_ERR_INFEASIBLE: return "infeasible boundary state"; + case TR_ERR_NUMERIC: return "numeric failure"; + case TR_ERR_NO_PROFILE: return "no transition profile found"; + default: return "unknown transition status"; + } +} diff --git a/src/transition.h b/src/transition.h new file mode 100644 index 0000000..70b3ae9 --- /dev/null +++ b/src/transition.h @@ -0,0 +1,106 @@ +#ifndef INCLUDED_TRANSITION_V3_SPARAM_H +#define INCLUDED_TRANSITION_V3_SPARAM_H + +#include +#include "vec2.h" + +/* + * Time-optimal jerk-limited transition for independent X/Y axes. + * + * The planner treats X and Y as independent 1D axes with identical symmetric + * limits for both directions: + * |v_axis| <= vmax, |a_axis| <= amax, |j_axis| <= jmax. + * + * Boundary acceleration is fixed to zero on both axes. Jerk is a bounded + * control, not a state; tr_sample() reports j=0 outside the motion interval, + * but the time-optimal profile may jump from 0 to +/-jmax at t=0 and jump back + * to 0 at t=T. If continuous jerk is required, the problem is snap-limited, + * not jerk-limited. + * + * The transition can be sampled either by time t or by travelled arclength s. + * Arclength is computed as + * s(t) = integral_0^t hypot(vx(tau), vy(tau)) d tau. + * + * For fast repeated sampling by s, tr_transition stores an internal monotone + * lookup table parameterized by arclength. The dynamic profile is still stored + * as time-polynomial axis phases; the s-table only maps s -> t. + */ + +#define TR_S_TABLE_CAP 2049u + +#define TR_S_PARAM_TABLE_UNIFORM_BY_LENGTH 1 + +enum tr_status { + TR_OK = 0, + TR_ERR_INVALID_ARG = -1, + TR_ERR_LIMITS = -2, + TR_ERR_INFEASIBLE = -3, + TR_ERR_NUMERIC = -4, + TR_ERR_NO_PROFILE = -5 +}; + +struct tr_axis_phase { + double t_begin; + double dt; + double q0; + double v0; + double a0; + double j; +}; + +struct tr_axis_plan { + struct tr_axis_phase phases[16]; + uint32_t count; + double duration; + double q0, q1; + double v0, v1; +}; + +struct tr_s_node { + double s; + double t; +}; + +struct tr_transition { + struct tr_axis_plan x; + struct tr_axis_plan y; + double duration; + double length; + + /* Uniform arclength parameterization: s_nodes[i].s is approximately + * i*length/(s_node_count-1), and s_nodes[i].t is the corresponding time. + */ + uint32_t s_node_count; + double s_step; + struct tr_s_node s_nodes[TR_S_TABLE_CAP]; + + double vmax, amax, jmax; +}; + +struct tr_sample { + double t; + double s; + struct vec2 r; + struct vec2 v; + struct vec2 a; + struct vec2 j; +}; + +int tr_build (struct tr_transition *out, + struct vec2 r0, + struct vec2 r1, + struct vec2 v0, + struct vec2 v1, + double vmax, + double amax, + double jmax); + +void tr_sample (const struct tr_transition *tr, double t, struct tr_sample *out); +void tr_sample_at_s (const struct tr_transition *tr, double s, struct tr_sample *out); + +double tr_length_at_time (const struct tr_transition *tr, double t); +double tr_time_at_length (const struct tr_transition *tr, double s); + +const char *tr_status_string (int status); + +#endif /* INCLUDED_TRANSITION_V3_SPARAM_H */ diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..67d0a84 --- /dev/null +++ b/src/utils.c @@ -0,0 +1,135 @@ +// src/utils.c +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +const char *progname; + +struct sv +mmap_whole (int fd) +{ + struct sv sv; + + struct stat st; + int ret = fstat (fd, &st); + UNUSED (ret); + ASSERT_MSG (ret != -1, "fstat: %s", strerror (errno)); + ASSERT (S_ISREG (st.st_mode)); + + posix_fadvise (fd, 0, st.st_size, POSIX_FADV_SEQUENTIAL | + POSIX_FADV_WILLNEED | + POSIX_FADV_NOREUSE); + + sv.beg = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE | + MAP_POPULATE | + MAP_NONBLOCK, fd, 0); + ASSERT_MSG (sv.beg != MAP_FAILED, "mmap: %s", strerror (errno)); + posix_madvise ((void *) sv.beg, st.st_size, MADV_HUGEPAGE | MADV_WILLNEED); + + sv.end = sv.beg + st.st_size; + + return sv; +} + +struct sv +read_until_eof (struct arena *a, int fd) +{ + struct arena_checkpoint cp = arena_checkpoint (a, 1); + size_t reserve = 4096; + + size_t read_total = 0; + for (;;) { + arena_reserve (a, reserve, 1); + ssize_t bytes_read = + read (fd, arena_next_free (a, 1), arena_room (a, 1)); + + if (bytes_read < 0) { + DEBUG ("read: %s", strerror (errno)); + arena_rollback_to (a, cp); + return (struct sv) {0}; + } + + if (bytes_read == 0) + break; + + read_total += bytes_read; + + arena_allocate_fast (a, bytes_read, 1); + reserve *= 2; + } + + if (a->tail->free == cp.free) + return (struct sv) {0}; + + char *ptr = arena_coalesce_from_fast (a, cp, read_total); + return (struct sv) { + .beg = ptr, + .end = ptr + read_total, + }; +} + +struct location +find_location (struct sv haystack, struct sv needle) +{ + ASSERT (needle.beg >= haystack.beg); + ASSERT (needle.end <= haystack.end); + + struct location loc = { .beg = { 1, 1 } }; + + const char *head; + for (head = haystack.beg; head < needle.beg; ++head) { + loc.beg.column += 1; + if (*head == '\n') { + loc.beg.line += 1; + loc.beg.column = 1; + } + } + + loc.end.line = loc.beg.line; + loc.end.column = loc.beg.column - 1; + + for (; head < needle.end; ++head) { + loc.end.column += 1; + if (*head == '\n') { + loc.end.line += 1; + loc.end.column = 1; + } + } + + return loc; +} + +void +print_location (const char *filename, struct location loc, + int alignment, const char *format, ...) +{ + int printed = 0; + + printed += printf ("%s:", filename); + if (loc.end.line > loc.beg.line) { + printed += printf ("%d-%d", loc.beg.line, loc.end.line); + } else { + printed += printf ("%d:%d-%d", loc.beg.line, loc.beg.column, + loc.end.column); + } printed += printf (": info: "); + + while (printed < alignment) { + putchar (' '); + printed += 1; + } + + va_list ap; + va_start (ap, format); + vprintf (format, ap); + va_end (ap); + printf ("\n"); +} + +// src/utils.c ends here diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..b6c38d5 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,132 @@ +// src/utils.h + +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include +#include + +#include "sv.h" +#include "arena.h" + +#define NOP() do {} while (0) + +#define ARRAY_LENGTH(ARR) (sizeof (ARR)/sizeof (*(ARR))) + +#ifndef NDEBUG +#include +#define ASSERT assert +#else +#define ASSERT(...) NOP () +#endif + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free + +#define UNUSED(EXP) ((void) EXP) + +#define FALLTHROUGH __attribute__ ((__fallthrough__)) + +#define STRINGIFY(ARG) #ARG +#define TO_STRING(ARG) STRINGIFY (ARG) + +#ifndef NDEBUG +#define DEBUG(FMT, ...) \ + fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ + __func__, ##__VA_ARGS__) +#define LOG(FMT, ...) \ + fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ + __func__, ##__VA_ARGS__) +#else +#define DEBUG(...) NOP () +#define LOG(FMT, ...) \ + fprintf (stderr, "%s: " FMT "\n", progname, ##__VA_ARGS__) +#endif + +#define FATAL(FMT, ...) LOG ("fatal: " FMT, ##__VA_ARGS__) +#define ERROR(FMT, ...) LOG ("error: " FMT, ##__VA_ARGS__) +#define WARNING(FMT, ...) LOG ("warning: " FMT, ##__VA_ARGS__) +#define NOTICE(FMT, ...) LOG ("notice: " FMT, ##__VA_ARGS__) +#define INFO(FMT, ...) LOG ("info: " FMT, ##__VA_ARGS__) + +#define DIE(FMT, ...) do { \ + FATAL (FMT, ##__VA_ARGS__); \ + exit (EXIT_FAILURE); \ + } while (0) + +#ifndef NDEBUG +#define ASSERT_MSG(EXP, FMT, ...) do if (!(EXP)) { \ + DEBUG (FMT, ##__VA_ARGS__); \ + exit (EXIT_FAILURE); \ + } while (0) +#else +#define ASSERT_MSG(EXP, FMT, ...) NOP () +#endif + +#define MEASURE(FMT, ...) \ + for (struct timespec _ts0, _ts1, *_once = NULL; \ + clock_gettime (CLOCK_MONOTONIC, &_ts0), !_once; \ + clock_gettime (CLOCK_MONOTONIC, &_ts1), \ + DEBUG (FMT " %.6fs\n", ##__VA_ARGS__, \ + (_ts1.tv_sec - _ts0.tv_sec ) + \ + (_ts1.tv_nsec - _ts0.tv_nsec) / 1e9), \ + _once += 1) + +#define MIN(A, B) ((A) <= (B) ? (A) : (B)) + +struct timer_scope { + char *fmt; + struct timespec start; +}; + +static void +timer_end (struct timer_scope *t) +{ + struct timespec end; + clock_gettime (CLOCK_MONOTONIC, &end); + + double s = ((end.tv_sec - t->start.tv_sec) + + (end.tv_nsec - t->start.tv_nsec)/1e9); + + fprintf (stderr, t->fmt, s); + if (t->fmt[strlen (t->fmt) - 1] != ' ') + putc (' ', stderr); + fprintf (stderr, "took %.6fs\n", s); + free (t->fmt); +} + +#define MEASURE_SCOPE(FMT, ...) \ + __attribute__ ((cleanup (timer_end))) struct timer_scope __ts; \ + asprintf (&__ts.fmt, \ + __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT, \ + __func__, ##__VA_ARGS__); \ + clock_gettime (CLOCK_MONOTONIC, &__ts.start) + +struct location { + struct { + int line; + int column; + } beg; + struct { + int line; + int column; + } end; +}; + +extern const char *progname; + +struct sv mmap_whole (int fd); +struct sv read_until_eof (struct arena *, int fd); + +struct location find_location (struct sv haystack, struct sv needle); +void print_location (const char *filename, struct location, int alignment, const char *format, ...); + +void print_back_trace (int skip); + +#endif // INCLUDED_UTILS_H + +// src/utils.h ends here diff --git a/src/vec2.c b/src/vec2.c new file mode 100644 index 0000000..7c325fe --- /dev/null +++ b/src/vec2.c @@ -0,0 +1,67 @@ +#include "vec2.h" +#include + +struct vec2 +vec2_add (struct vec2 a, struct vec2 b) +{ + return (struct vec2) { a.x + b.x, a.y + b.y }; +} + +struct vec2 +vec2_sub (struct vec2 a, struct vec2 b) +{ + return (struct vec2) { a.x - b.x, a.y - b.y }; +} + +struct vec2 +vec2_scale (struct vec2 a, double k) +{ + return (struct vec2) { a.x*k, a.y*k }; +} + +double +vec2_dot (struct vec2 a, struct vec2 b) +{ + return a.x*b.x + a.y*b.y; +} + +double +vec2_norm (struct vec2 a) +{ + return hypot (a.x, a.y); +} + +double +vec2_dist (struct vec2 a, struct vec2 b) +{ + return vec2_norm (vec2_sub (a, b)); +} + +struct vec2 +vec2_unit (struct vec2 a) +{ + double n = vec2_norm (a); + + // if (n <= VEC2_EPS) + // return (struct vec2) { 0, 0 }; + + return vec2_scale (a, 1/n); +} + +double +vec2_angle0 (struct vec2 a) +{ + return atan2 (a.y, a.x); +} + +static double +clampd (double x, double lo, double hi) +{ + return x < lo ? lo : (x > hi ? hi : x); +} + +double +vec2_angle (struct vec2 a, struct vec2 b) +{ + return acos (clampd (vec2_dot (a, b)/(vec2_norm (a)*vec2_norm (b)), 0, 1)); +} diff --git a/src/vec2.h b/src/vec2.h new file mode 100644 index 0000000..95dc3b6 --- /dev/null +++ b/src/vec2.h @@ -0,0 +1,18 @@ +#ifndef INCLUDED_VEC2_H +#define INCLUDED_VEC2_H + +struct vec2 { + double x, y; +}; + +double vec2_norm (struct vec2 a); +struct vec2 vec2_unit (struct vec2 a); +struct vec2 vec2_scale (struct vec2 a, double k); +struct vec2 vec2_add (struct vec2 a, struct vec2 b); +struct vec2 vec2_sub (struct vec2 a, struct vec2 b); +double vec2_dot (struct vec2 a, struct vec2 b); +double vec2_dist (struct vec2 a, struct vec2 b); +double vec2_angle (struct vec2 a, struct vec2 b); +double vec2_angle0 (struct vec2 a); + +#endif // INCLUDED_VEC2_H -- cgit v1.3.1