From 231ceb70f2dd7e83db3bd2bea961c73401ab6e21 Mon Sep 17 00:00:00 2001 From: Phil Howard Date: Wed, 6 Sep 2023 09:40:38 +0100 Subject: [PATCH] PicoVector: Add basic polygon center of mass function. --- micropython/modules/picovector/picovector.c | 2 ++ micropython/modules/picovector/picovector.cpp | 18 ++++++++++++++++++ micropython/modules/picovector/picovector.h | 1 + 3 files changed, 21 insertions(+) diff --git a/micropython/modules/picovector/picovector.c b/micropython/modules/picovector/picovector.c index 3cbfacdfd..eb6dfd1f7 100644 --- a/micropython/modules/picovector/picovector.c +++ b/micropython/modules/picovector/picovector.c @@ -3,10 +3,12 @@ /* Polygon */ STATIC MP_DEFINE_CONST_FUN_OBJ_1(POLYGON__del__obj, POLYGON__del__); +STATIC MP_DEFINE_CONST_FUN_OBJ_1(POLYGON_centroid_obj, POLYGON_centroid); STATIC const mp_rom_map_elem_t POLYGON_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&POLYGON__del__obj) }, + { MP_ROM_QSTR(MP_QSTR_centroid), MP_ROM_PTR(&POLYGON_centroid_obj) }, }; STATIC MP_DEFINE_CONST_DICT(POLYGON_locals_dict, POLYGON_locals_dict_table); diff --git a/micropython/modules/picovector/picovector.cpp b/micropython/modules/picovector/picovector.cpp index 11dcdddd0..9654c342b 100644 --- a/micropython/modules/picovector/picovector.cpp +++ b/micropython/modules/picovector/picovector.cpp @@ -214,6 +214,24 @@ mp_obj_t POLYGON_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, return self; } +mp_obj_t POLYGON_centroid(mp_obj_t self_in) { + _POLYGON_obj_t *self = MP_OBJ_TO_PTR2(self_in, _POLYGON_obj_t); + + pretty_poly::point_t sum(0, 0); + + for(auto i = 0u; i < self->contour.count; i++) { + sum += self->contour.points[i]; + } + + sum /= (float)self->contour.count; + + mp_obj_t tuple[2]; + tuple[0] = mp_obj_new_int((int)(sum.x)); + tuple[1] = mp_obj_new_int((int)(sum.y)); + + return mp_obj_new_tuple(2, tuple); +} + void POLYGON_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; _POLYGON_obj_t *self = MP_OBJ_TO_PTR2(self_in, _POLYGON_obj_t); diff --git a/micropython/modules/picovector/picovector.h b/micropython/modules/picovector/picovector.h index 2fc58ac35..a4158e88e 100644 --- a/micropython/modules/picovector/picovector.h +++ b/micropython/modules/picovector/picovector.h @@ -10,6 +10,7 @@ extern mp_obj_t POLYGON_make_new(const mp_obj_type_t *type, size_t n_args, size_ extern mp_obj_t REGULAR_POLYGON_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args); extern mp_obj_t RECTANGLE_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args); extern void POLYGON_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind); +extern mp_obj_t POLYGON_centroid(mp_obj_t self_in); extern mp_obj_t POLYGON_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf); extern mp_obj_t POLYGON__del__(mp_obj_t self_in);