From 738085071596a4209565e7834aba3f0496c0277c Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Mon, 16 Nov 2026 15:50:11 -0800 Subject: [PATCH 1/2] Make vectorio subclassable and add round rects vectorio rounded rectangles save a bunch of memory over the bitmap based solution. --- ports/espressif/lvgl/lv_conf.h | 6 + .../electronut_labs_blip/mpconfigboard.mk | 1 + .../stm/boards/meowbit_v121/mpconfigboard.mk | 1 + ports/zephyr-cp/tests/test_vectorio.py | 384 +++++++++++++++++- shared-bindings/vectorio/Circle.c | 106 ++++- shared-bindings/vectorio/Circle.h | 9 +- shared-bindings/vectorio/Polygon.c | 28 +- shared-bindings/vectorio/Rectangle.c | 160 +++++++- shared-bindings/vectorio/Rectangle.h | 12 +- shared-module/vectorio/Circle.c | 63 ++- shared-module/vectorio/Circle.h | 5 + shared-module/vectorio/Rectangle.c | 100 ++++- shared-module/vectorio/Rectangle.h | 10 + shared-module/vectorio/lvgl/VectorShape.c | 70 +++- 14 files changed, 899 insertions(+), 56 deletions(-) diff --git a/ports/espressif/lvgl/lv_conf.h b/ports/espressif/lvgl/lv_conf.h index 00f178c4ef9..b27603011d6 100644 --- a/ports/espressif/lvgl/lv_conf.h +++ b/ports/espressif/lvgl/lv_conf.h @@ -29,6 +29,12 @@ #define LV_USE_PPA_IMG 1 /* Leave regular PSRAM arbitration gaps for the DSI framebuffer scanout DMA. */ #define LV_PPA_BURST_LENGTH 64 + +/* Rounded rectangles are drawn from cached corner alpha tables, keyed by radius. A rounded + * shape with an outline uses two entries (the outer radius and the inner one), so the default + * of 4 fills up after two shapes with different radii. Each entry is a few hundred bytes to a + * couple of KB, and a UI with a few corner radii then never rasterizes a corner again. */ +#define LV_DRAW_SW_CIRCLE_CACHE_SIZE 8 /* LVGL 9.6 checks this before defining it, which trips -Wundef. */ #define LV_PPA_NONBLOCKING_OPS 0 #define LV_DRAW_BUF_ALIGN 64 diff --git a/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk b/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk index fc59a101e45..87d3c8c25c5 100644 --- a/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk +++ b/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk @@ -10,5 +10,6 @@ CIRCUITPY_BUILD_EXTENSIONS = hex INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_AUDIOIO = 0 CIRCUITPY_DISPLAYIO = 1 +CIRCUITPY_GIFIO = 0 CIRCUITPY_STAGE = 1 CIRCUITPY_DIGITALINOUT_PROTOCOL = 0 diff --git a/ports/stm/boards/meowbit_v121/mpconfigboard.mk b/ports/stm/boards/meowbit_v121/mpconfigboard.mk index 271c4cd775c..1f48d75207e 100644 --- a/ports/stm/boards/meowbit_v121/mpconfigboard.mk +++ b/ports/stm/boards/meowbit_v121/mpconfigboard.mk @@ -29,6 +29,7 @@ CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BLEIO_HCI = 0 CIRCUITPY_EPAPERDISPLAY = 0 CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_GIFIO = 0 CIRCUITPY_I2CDISPLAYBUS = 0 CIRCUITPY_KEYPAD_DEMUX = 0 CIRCUITPY_MSGPACK = 0 diff --git a/ports/zephyr-cp/tests/test_vectorio.py b/ports/zephyr-cp/tests/test_vectorio.py index 5237d50db3e..bbefb56a263 100644 --- a/ports/zephyr-cp/tests/test_vectorio.py +++ b/ports/zephyr-cp/tests/test_vectorio.py @@ -16,13 +16,17 @@ background there while the legacy compositor fills whole pixels. The band around the outline is skipped, everything else has to match exactly. -Two differences between the two implementations are known and are not tested +Three differences between the two implementations are known and are not tested here: - LVGL antialiases the outline of a circle, the legacy compositor does not. - The legacy compositor does not scale vectorio shapes with the scale of the group they are in, while the LVGL one does. A shape in a scaled group is therefore bigger on an LVGL display. +- An outline color index that names a transparent palette entry leaves the + outline band unpainted on the legacy compositor, while LVGL treats it as no + outline and lets the fill reach the edge. Set outline_color_index to None to + remove an outline instead of making its palette entry transparent. """ import math @@ -288,3 +292,381 @@ def test_vectorio_move_and_hide(circuitpython): # cleared again. assert _pixel_at(after, 110, 45) == black assert _pixel_at(after, 160, 45) == green + + +# Corner radius, outlines and the geometry that display_shapes needs. Both +# compositors answer contains() from the same coverage test, so this is the same +# on both even though they rasterize differently. +ROUNDED_CODE = """\ +import displayio +import vectorio + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +# A shape's position is its top left corner, so contains() at (10 + dx, 10 + dy) +# asks about the shape's own pixel (dx, dy). +rectangle = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=10, y=10, + radius=12, color_index=1, outline_width=4, outline_color_index=2) +print('defaults', rectangle.radius, rectangle.outline_width, + rectangle.outline_color_index, rectangle.color_index) + +# The corners are cut out of the coverage: the corner pixel is not covered, and +# the middle of each side still is. +print('corners', rectangle.contains(10, 10), rectangle.contains(12, 12), + rectangle.contains(18, 18), rectangle.contains(10, 30), rectangle.contains(89, 30)) + +# Radius and outline width must not exceed half of the shortest side. Invalid +# construction and assignments raise ValueError and leave existing values unchanged. +try: + vectorio.Rectangle(pixel_shader=palette, width=20, height=20, radius=11) +except ValueError: + print('constructor radius limit: ValueError') +try: + vectorio.Rectangle(pixel_shader=palette, width=20, height=20, outline_width=11) +except ValueError: + print('constructor outline limit: ValueError') +try: + rectangle.radius = 21 +except ValueError: + print('radius limit: ValueError') +try: + rectangle.outline_width = 21 +except ValueError: + print('outline limit: ValueError') +try: + rectangle.width = 20 +except ValueError: + print('resize limit: ValueError') +print('limits', rectangle.radius, rectangle.outline_width, rectangle.width) + +# The outline is inside the bounds, so it covers the same pixels whether it is set +# or not: contains() only answers coverage, not which color the pixel gets. +rectangle.outline_width = 4 +print('band', rectangle.contains(11, 30), rectangle.contains(13, 30), + rectangle.contains(14, 30), rectangle.contains(14, 14), rectangle.contains(18, 18)) +rectangle.outline_color_index = None +print('no outline color', rectangle.contains(11, 30), rectangle.outline_color_index) +rectangle.outline_color_index = 2 + +# Zero outline width is the same coverage with no outline at all. +rectangle.outline_width = 0 +print('no outline', rectangle.contains(11, 30), rectangle.outline_width) + +# A transparent palette entry draws nothing, which is how a shape gets a +# transparent fill. +palette.make_transparent(1) +print('transparent fill', rectangle.contains(50, 30)) + +# The circle ring behaves the same way. +circle = vectorio.Circle(pixel_shader=palette, radius=20, x=100, y=100, + color_index=2, outline_width=4, outline_color_index=3) +print('ring', circle.outline_width, circle.outline_color_index, + circle.contains(100, 84), circle.contains(100, 100), + circle.contains(100, 79), circle.contains(100, 121)) +circle.outline_width = 0 +print('no ring', circle.contains(100, 84)) +print('done') +""" + +SUBCLASS_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time +import vectorio + + +class RoundRect(vectorio.Rectangle): + \"\"\"A display_shapes style rounded rectangle built on vectorio.Rectangle.\"\"\" + + def __init__(self, x, y, width, height, r, *, fill=None, outline=None, stroke=1): + if width <= 0 or height <= 0: + raise ValueError("dimensions must be larger than 0") + if r > min(width, height) / 2: + raise ValueError("radius cannot exceed half of the smaller side") + self._palette = displayio.Palette(2) + self._palette.make_transparent(0) + self._palette.make_transparent(1) + super().__init__(pixel_shader=self._palette, width=width, height=height, x=x, y=y, + color_index=0, radius=r, outline_width=stroke, outline_color_index=1) + self.fill = fill + self.outline = outline + + @property + def fill(self): + return None if self._palette.is_transparent(0) else self._palette[0] + + @fill.setter + def fill(self, color): + if color is None: + self._palette.make_transparent(0) + else: + self._palette[0] = color + self._palette.make_opaque(0) + + @property + def outline(self): + return None if self._palette.is_transparent(1) else self._palette[1] + + @outline.setter + def outline(self, color): + if color is None: + self._palette.make_transparent(1) + else: + self._palette[1] = color + self._palette.make_opaque(1) + + +round_rect = RoundRect(10, 10, 80, 40, 12, fill=0xFF0000, outline=0x00FF00, stroke=4) +print('size', round_rect.x, round_rect.y, round_rect.width, round_rect.height) +print('shape', round_rect.radius, round_rect.outline_width, + round_rect.outline_color_index, round_rect.color_index) +print('colors', hex(round_rect.fill), hex(round_rect.outline)) +print('shader', round_rect.pixel_shader is round_rect._palette) + +# Everything inherited from VectorShape resolves through the native Rectangle. +print('contains', round_rect.contains(50, 30), round_rect.contains(10, 10)) +print('location', round_rect.location) +round_rect.x = 30 +round_rect.width = 100 +round_rect.radius = 20 +print('mutated', round_rect.x, round_rect.width, round_rect.radius, round_rect.location) +round_rect.hidden = True +print('hidden', round_rect.hidden) +round_rect.hidden = False +round_rect.fill = None +print('cleared', round_rect.fill, round_rect.contains(50, 30)) + +group = displayio.Group() +group.append(round_rect) +print('in group', len(group)) +other = displayio.Group() +try: + other.append(round_rect) +except ValueError: + print('second group: ValueError') + + +class SubclassedCircle(vectorio.Circle): + pass + + +class SubclassedPolygon(vectorio.Polygon): + pass + + +# Exercise the native-base conversion for every vectorio shape, not only Rectangle. +circle = SubclassedCircle(pixel_shader=round_rect._palette, radius=20, x=150, y=100, + color_index=0, outline_width=4, outline_color_index=1) +polygon = SubclassedPolygon(pixel_shader=round_rect._palette, + points=[(0, 0), (40, 0), (0, 40)], x=220, y=100, color_index=0) +print('other shapes', circle.radius, circle.outline_width, circle.outline_color_index, + polygon.points, polygon.color_index) +circle.radius = 22 +circle.outline_width = 3 +polygon.points = [(0, 0), (50, 0), (0, 40)] +polygon.color_index = 1 +print('other mutations', circle.radius, circle.outline_width, polygon.points, + polygon.color_index, circle.contains(150, 100), polygon.contains(225, 105)) + +# Restore the rectangle after the API checks and render all three Python subclasses. This +# verifies that Group's protocol lookup reaches the native wrapper on both compositors. +round_rect.x = 10 +round_rect.width = 80 +round_rect.radius = 12 +round_rect.fill = 0xFF0000 +group.append(circle) +group.append(polygon) +display.auto_refresh = False +display.root_group = group +display.refresh() +print('done') +print('rendered') +while True: + time.sleep(1) +""" +) + +ROUNDED_SCENE_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time +import vectorio + +palette = displayio.Palette(4) +palette.make_transparent(0) +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +group = displayio.Group() + +# Rounded rectangle with a 4 pixel outline: x 10..89, y 10..49, radius 12. +rectangle = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=10, y=10, + radius=12, color_index=1, outline_width=4, outline_color_index=2) +group.append(rectangle) + +# A hollow one: transparent fill, so only the outline is drawn. +hollow = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=110, y=10, + radius=12, color_index=0, outline_width=4, outline_color_index=2) +group.append(hollow) + +# No outline color means no outline, so the fill reaches the edge. +invisible = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=210, y=10, + radius=12, color_index=1, outline_width=4) +group.append(invisible) + +# A ring: center (40, 110), radius 20, 4 pixels thick. +circle = vectorio.Circle(pixel_shader=palette, radius=20, x=40, y=110, + color_index=1, outline_width=4, outline_color_index=2) +group.append(circle) + +display.auto_refresh = False +display.root_group = group +display.refresh() +print('rendered') +while True: + time.sleep(1) +""" +) + + +@pytest.mark.circuitpy_drive({"code.py": ROUNDED_CODE}) +@pytest.mark.duration(15) +def test_vectorio_radius_and_outline_api(circuitpython): + """Radius, outline width and outline color index are the same on both compositors.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "defaults 12 4 2 1" in output + # Covered: the flat sides and the diagonal inside the corner arc. Not + # covered: the corner pixel and everything a pixel beyond the shape. + assert "corners False False True True True" in output + # The corner radius and outline width are validated instead of clamped. A + # resize that would make either one too large is rejected too. + assert "constructor radius limit: ValueError" in output + assert "constructor outline limit: ValueError" in output + assert "radius limit: ValueError" in output + assert "outline limit: ValueError" in output + assert "resize limit: ValueError" in output + assert "limits 12 4 80" in output + # The 4 pixel outline band is the outline, and the fill starts inside it. An + # outline covers the same pixels as the fill it replaces. + assert "band True True True True True" in output + assert "no outline color True None" in output + assert "no outline True 0" in output + assert "transparent fill True" in output + # The ring covers radius-4..radius, the fill covers everything inside. + assert "ring 4 3 True True False False" in output + assert "no ring True" in output + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": SUBCLASS_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_vectorio_python_subclass(circuitpython): + """Python subclasses of all vectorio shapes work as rendered group members.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 10 10 80 40" in output + assert "shape 12 4 1 0" in output + assert "colors 0xff0000 0xff00" in output + assert "shader True" in output + assert "contains True False" in output + assert "location (10, 10)" in output + assert "mutated 30 100 20 (30, 10)" in output + assert "hidden True" in output + assert "cleared None True" in output + assert "in group 1" in output + assert "second group: ValueError" in output + assert "other shapes 20 4 1 [(0, 0), (40, 0), (0, 40)] 0" in output + assert "other mutations 22 3 [(0, 0), (50, 0), (0, 40)] 1 True True" in output + assert "done" in output + assert "rendered" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as img: + frame = img.convert("RGB") + + red = (255, 0, 0) + green = (0, 255, 0) + black = (0, 0, 0) + + # The subclassed rounded rectangle renders with its inherited native geometry. + assert _pixel_at(frame, 50, 30) == red + assert _pixel_at(frame, 50, 10) == green + assert _pixel_at(frame, 10, 10) == black + # Circle and Polygon subclasses also reach their native draw protocols. + assert _pixel_at(frame, 150, 100) == red + assert _pixel_at(frame, 150, 79) == green + assert _pixel_at(frame, 225, 105) == green + assert _pixel_at(frame, 260, 135) == black + + +@pytest.mark.circuitpy_drive({"code.py": ROUNDED_SCENE_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_vectorio_radius_and_outline_render(circuitpython): + """Rounded corners and outlines are drawn inside the shape's bounds.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "rendered" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as img: + frame = img.convert("RGB") + + red = (255, 0, 0) + green = (0, 255, 0) + black = (0, 0, 0) + + def pixel(x, y): + return tuple(frame.getpixel((x, y))) + + # The fill is the whole rectangle less the outline band. + assert pixel(50, 30) == red + # The outline is inside the bounds: 4 pixels in on every flat side, so it + # never makes the rectangle bigger. + assert pixel(50, 10) == green + assert pixel(50, 13) == green + assert pixel(50, 14) == red + assert pixel(10, 30) == green + assert pixel(13, 30) == green + assert pixel(14, 30) == red + # The corner is round: well outside the arc is background and the diagonal + # inside the arc is outline. + assert pixel(10, 10) == black + assert pixel(12, 12) == black + assert pixel(14, 14) == green + assert pixel(18, 18) == red + + # A transparent fill leaves only the outline. + assert pixel(150, 30) == black + assert pixel(150, 11) == green + assert pixel(111, 30) == green + assert pixel(110, 10) == black + + # A transparent outline color draws no outline, so the fill reaches the edge. + assert pixel(250, 10) == red + assert pixel(211, 30) == red + assert pixel(210, 10) == black + + # The ring is inside the circle's radius. + assert pixel(40, 110) == red + assert pixel(40, 97) == red + assert pixel(40, 92) == green + assert pixel(40, 89) == black diff --git a/shared-bindings/vectorio/Circle.c b/shared-bindings/vectorio/Circle.c index 2f3bc6bb5d2..cc6b053fd05 100644 --- a/shared-bindings/vectorio/Circle.c +++ b/shared-bindings/vectorio/Circle.c @@ -22,6 +22,8 @@ //| radius: int, //| x: int, //| y: int, +//| outline_width: int = 0, +//| outline_color_index: Optional[int] = None, //| ) -> None: //| """Circle is positioned on screen by its center point. //| @@ -30,16 +32,41 @@ //| :param int x: Initial x position of the axis. //| :param int y: Initial y position of the axis. //| :param int color_index: Initial color_index to use when selecting color from the palette. +//| :param int outline_width: The width in pixels of a ring drawn just inside the +//| circle's outer edge, so it never makes the circle bigger. 0 (the default) +//| draws no ring. +//| :param Optional[int] outline_color_index: The 0 based palette index of the ring +//| color, or ``None`` (the default) for no ring. Only used when +//| ``outline_width`` is greater than 0. Use ``None`` rather than a transparent +//| palette entry to remove a ring: the two compositors draw a band with a +//| transparent color differently. //| """ //| +// -1 means no outline color, which the shape stores as an unset bias. +static int32_t parse_outline_color_index(mp_obj_t outline_color_index) { + if (outline_color_index == mp_const_none) { + return -1; + } + return mp_arg_validate_int_min(mp_obj_get_int(outline_color_index), 0, MP_QSTR_outline_color_index); +} + +static mp_obj_t outline_color_index_to_obj(int32_t outline_color_index) { + if (outline_color_index < 0) { + return mp_const_none; + } + return mp_obj_new_int(outline_color_index); +} + static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_pixel_shader, ARG_radius, ARG_x, ARG_y, ARG_color_index }; + enum { ARG_pixel_shader, ARG_radius, ARG_x, ARG_y, ARG_color_index, ARG_outline_width, ARG_outline_color_index }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pixel_shader, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED, { .u_obj = NULL } }, { MP_QSTR_radius, MP_ARG_REQUIRED | MP_ARG_INT, { .u_obj = NULL } }, { MP_QSTR_x, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_y, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_color_index, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_width, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_color_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -47,9 +74,13 @@ static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_arg mp_int_t radius = args[ARG_radius].u_int; mp_arg_validate_int_min(radius, 1, MP_QSTR_radius); + mp_int_t outline_width = args[ARG_outline_width].u_int; + mp_arg_validate_int_min(outline_width, 0, MP_QSTR_outline_width); + vectorio_circle_t *self = mp_obj_malloc(vectorio_circle_t, &vectorio_circle_type); uint16_t color_index = args[ARG_color_index].u_int; - common_hal_vectorio_circle_construct(self, radius, color_index); + int32_t outline_color_index = parse_outline_color_index(args[ARG_outline_color_index].u_obj); + common_hal_vectorio_circle_construct(self, radius, color_index, outline_width, outline_color_index); // VectorShape parts mp_obj_t pixel_shader = args[ARG_pixel_shader].u_obj; @@ -61,9 +92,21 @@ static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_arg return MP_OBJ_FROM_PTR(self); } +// A Python subclass of Circle is an mp_obj_instance_t that holds the native Circle in +// subobj[0], so every entry point below has to see that native object instead of the instance. +// See native_rectangle() in Rectangle.c. +static vectorio_circle_t *native_circle(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&vectorio_circle_type)); + if (native == MP_OBJ_NULL) { + return MP_OBJ_TO_PTR(self_in); + } + mp_obj_assert_native_inited(native); + return MP_OBJ_TO_PTR(native); +} + #if CIRCUITPY_DISPLAYIO_LVGL static mp_obj_t circle_lvgl_protocol_self(mp_obj_t self_in) { - return common_hal_vectorio_circle_get_draw_protocol(MP_OBJ_TO_PTR(self_in)); + return common_hal_vectorio_circle_get_draw_protocol(native_circle(self_in)); } static const lvgl_protocol_t circle_lvgl_protocol = { @@ -72,9 +115,13 @@ static const lvgl_protocol_t circle_lvgl_protocol = { }; #define VECTORIO_CIRCLE_PROTOCOL &circle_lvgl_protocol #else +static mp_obj_t circle_draw_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_circle_get_draw_protocol(native_circle(self_in)); +} + static const vectorio_draw_protocol_t circle_draw_protocol = { MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) - .draw_get_protocol_self = (draw_get_protocol_self_fun)common_hal_vectorio_circle_get_draw_protocol, + .draw_get_protocol_self = circle_draw_protocol_self, .draw_protocol_impl = &vectorio_vector_shape_draw_protocol_impl }; #define VECTORIO_CIRCLE_PROTOCOL &circle_draw_protocol @@ -84,13 +131,13 @@ static const vectorio_draw_protocol_t circle_draw_protocol = { //| radius: int //| """The radius of the circle in pixels.""" static mp_obj_t vectorio_circle_obj_get_radius(mp_obj_t self_in) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); return mp_obj_new_int(common_hal_vectorio_circle_get_radius(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_radius_obj, vectorio_circle_obj_get_radius); static mp_obj_t vectorio_circle_obj_set_radius(mp_obj_t self_in, mp_obj_t radius) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); common_hal_vectorio_circle_set_radius(self, mp_obj_get_int(radius)); return mp_const_none; } @@ -103,13 +150,13 @@ MP_PROPERTY_GETSET(vectorio_circle_radius_obj, //| color_index: int //| """The color_index of the circle as 0 based index of the palette.""" static mp_obj_t vectorio_circle_obj_get_color_index(mp_obj_t self_in) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); return mp_obj_new_int(common_hal_vectorio_circle_get_color_index(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_color_index_obj, vectorio_circle_obj_get_color_index); static mp_obj_t vectorio_circle_obj_set_color_index(mp_obj_t self_in, mp_obj_t color_index) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); common_hal_vectorio_circle_set_color_index(self, mp_obj_get_int(color_index)); return mp_const_none; } @@ -119,6 +166,47 @@ MP_PROPERTY_GETSET(vectorio_circle_color_index_obj, (mp_obj_t)&vectorio_circle_get_color_index_obj, (mp_obj_t)&vectorio_circle_set_color_index_obj); +//| outline_width: int +//| """The width of the ring in pixels. The ring is drawn inside the circle, so it never +//| changes the circle's size. 0 draws no ring.""" +static mp_obj_t vectorio_circle_obj_get_outline_width(mp_obj_t self_in) { + vectorio_circle_t *self = native_circle(self_in); + return mp_obj_new_int(common_hal_vectorio_circle_get_outline_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_outline_width_obj, vectorio_circle_obj_get_outline_width); + +static mp_obj_t vectorio_circle_obj_set_outline_width(mp_obj_t self_in, mp_obj_t outline_width) { + vectorio_circle_t *self = native_circle(self_in); + common_hal_vectorio_circle_set_outline_width(self, mp_arg_validate_int_min(mp_obj_get_int(outline_width), 0, MP_QSTR_outline_width)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_outline_width_obj, vectorio_circle_obj_set_outline_width); + +MP_PROPERTY_GETSET(vectorio_circle_outline_width_obj, + (mp_obj_t)&vectorio_circle_get_outline_width_obj, + (mp_obj_t)&vectorio_circle_set_outline_width_obj); + +//| outline_color_index: Optional[int] +//| """The 0 based palette index of the ring color, or ``None`` for no ring. Only used when +//| :py:attr:`outline_width` is greater than 0.""" +static mp_obj_t vectorio_circle_obj_get_outline_color_index(mp_obj_t self_in) { + vectorio_circle_t *self = native_circle(self_in); + return outline_color_index_to_obj(common_hal_vectorio_circle_get_outline_color_index(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_outline_color_index_obj, vectorio_circle_obj_get_outline_color_index); + +static mp_obj_t vectorio_circle_obj_set_outline_color_index(mp_obj_t self_in, mp_obj_t outline_color_index) { + vectorio_circle_t *self = native_circle(self_in); + common_hal_vectorio_circle_set_outline_color_index(self, + parse_outline_color_index(outline_color_index)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_outline_color_index_obj, vectorio_circle_obj_set_outline_color_index); + +MP_PROPERTY_GETSET(vectorio_circle_outline_color_index_obj, + (mp_obj_t)&vectorio_circle_get_outline_color_index_obj, + (mp_obj_t)&vectorio_circle_set_outline_color_index_obj); + // Documentation for properties inherited from VectorShape. @@ -148,6 +236,8 @@ static const mp_rom_map_elem_t vectorio_circle_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&vectorio_vector_shape_y_obj) }, { MP_ROM_QSTR(MP_QSTR_hidden), MP_ROM_PTR(&vectorio_vector_shape_hidden_obj) }, { MP_ROM_QSTR(MP_QSTR_color_index), MP_ROM_PTR(&vectorio_circle_color_index_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_width), MP_ROM_PTR(&vectorio_circle_outline_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_color_index), MP_ROM_PTR(&vectorio_circle_outline_color_index_obj) }, { MP_ROM_QSTR(MP_QSTR_location), MP_ROM_PTR(&vectorio_vector_shape_location_obj) }, { MP_ROM_QSTR(MP_QSTR_pixel_shader), MP_ROM_PTR(&vectorio_vector_shape_pixel_shader_obj) }, }; diff --git a/shared-bindings/vectorio/Circle.h b/shared-bindings/vectorio/Circle.h index 2c72e81881c..cb1f82a3c66 100644 --- a/shared-bindings/vectorio/Circle.h +++ b/shared-bindings/vectorio/Circle.h @@ -12,7 +12,7 @@ extern const mp_obj_type_t vectorio_circle_type; -void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index); +void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index, uint16_t outline_width, int32_t outline_color_index); void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_event_t notification); @@ -27,4 +27,11 @@ void common_hal_vectorio_circle_set_radius(void *circle, int16_t radius); uint16_t common_hal_vectorio_circle_get_color_index(void *obj); void common_hal_vectorio_circle_set_color_index(void *obj, uint16_t color_index); +uint16_t common_hal_vectorio_circle_get_outline_width(void *obj); +void common_hal_vectorio_circle_set_outline_width(void *obj, uint16_t outline_width); + +// -1 means no outline color was set. +int32_t common_hal_vectorio_circle_get_outline_color_index(void *obj); +void common_hal_vectorio_circle_set_outline_color_index(void *obj, int32_t outline_color_index); + mp_obj_t common_hal_vectorio_circle_get_draw_protocol(void *circle); diff --git a/shared-bindings/vectorio/Polygon.c b/shared-bindings/vectorio/Polygon.c index c78e838cc8c..9f475a9fe41 100644 --- a/shared-bindings/vectorio/Polygon.c +++ b/shared-bindings/vectorio/Polygon.c @@ -69,9 +69,21 @@ static mp_obj_t vectorio_polygon_make_new(const mp_obj_type_t *type, size_t n_ar return MP_OBJ_FROM_PTR(self); } +// A Python subclass of Polygon is an mp_obj_instance_t that holds the native Polygon in +// subobj[0], so every entry point below has to see that native object instead of the instance. +// See native_rectangle() in Rectangle.c. +static vectorio_polygon_t *native_polygon(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&vectorio_polygon_type)); + if (native == MP_OBJ_NULL) { + return MP_OBJ_TO_PTR(self_in); + } + mp_obj_assert_native_inited(native); + return MP_OBJ_TO_PTR(native); +} + #if CIRCUITPY_DISPLAYIO_LVGL static mp_obj_t polygon_lvgl_protocol_self(mp_obj_t self_in) { - return common_hal_vectorio_polygon_get_draw_protocol(MP_OBJ_TO_PTR(self_in)); + return common_hal_vectorio_polygon_get_draw_protocol(native_polygon(self_in)); } static const lvgl_protocol_t polygon_lvgl_protocol = { @@ -80,9 +92,13 @@ static const lvgl_protocol_t polygon_lvgl_protocol = { }; #define VECTORIO_POLYGON_PROTOCOL &polygon_lvgl_protocol #else +static mp_obj_t polygon_draw_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_polygon_get_draw_protocol(native_polygon(self_in)); +} + static const vectorio_draw_protocol_t polygon_draw_protocol = { MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) - .draw_get_protocol_self = (draw_get_protocol_self_fun)common_hal_vectorio_polygon_get_draw_protocol, + .draw_get_protocol_self = polygon_draw_protocol_self, .draw_protocol_impl = &vectorio_vector_shape_draw_protocol_impl }; #define VECTORIO_POLYGON_PROTOCOL &polygon_draw_protocol @@ -92,13 +108,13 @@ static const vectorio_draw_protocol_t polygon_draw_protocol = { //| points: List[Tuple[int, int]] //| """Vertices for the polygon.""" static mp_obj_t vectorio_polygon_obj_get_points(mp_obj_t self_in) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); return common_hal_vectorio_polygon_get_points(self); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_polygon_get_points_obj, vectorio_polygon_obj_get_points); static mp_obj_t vectorio_polygon_obj_set_points(mp_obj_t self_in, mp_obj_t points) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); common_hal_vectorio_polygon_set_points(self, points); return mp_const_none; @@ -112,13 +128,13 @@ MP_PROPERTY_GETSET(vectorio_polygon_points_obj, //| color_index: int //| """The color_index of the polygon as 0 based index of the palette.""" static mp_obj_t vectorio_polygon_obj_get_color_index(mp_obj_t self_in) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); return mp_obj_new_int(common_hal_vectorio_polygon_get_color_index(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_polygon_get_color_index_obj, vectorio_polygon_obj_get_color_index); static mp_obj_t vectorio_polygon_obj_set_color_index(mp_obj_t self_in, mp_obj_t color_index) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); common_hal_vectorio_polygon_set_color_index(self, mp_obj_get_int(color_index)); return mp_const_none; } diff --git a/shared-bindings/vectorio/Rectangle.c b/shared-bindings/vectorio/Rectangle.c index 6e1a0eedfff..d7fed77a19f 100644 --- a/shared-bindings/vectorio/Rectangle.c +++ b/shared-bindings/vectorio/Rectangle.c @@ -22,6 +22,9 @@ //| height: int, //| x: int, //| y: int, +//| radius: int = 0, +//| outline_width: int = 0, +//| outline_color_index: Optional[int] = None, //| ) -> None: //| """Represents a rectangle by defining its bounds //| @@ -31,10 +34,45 @@ //| :param int x: Initial x position of the top left corner. //| :param int y: Initial y position of the top left corner. //| :param int color_index: Initial color_index to use when selecting color from the palette. +//| :param int radius: The radius of the corners in pixels. 0 (the default) is square +//| corners. The radius must not exceed half of the shortest side. +//| :param int outline_width: The width in pixels of a border drawn just inside the +//| rectangle's bounds, so it never makes the rectangle bigger. 0 (the default) +//| draws no border. The width must not exceed half of the shortest side. +//| :param Optional[int] outline_color_index: The 0 based palette index of the border +//| color, or ``None`` (the default) for no border. Only used when +//| ``outline_width`` is greater than 0. Use ``None`` rather than a transparent +//| palette entry to remove a border: the two compositors draw a band with a +//| transparent color differently. //| """ //| +// -1 means no outline color, which the shape stores as an unset bias. +static int32_t parse_outline_color_index(mp_obj_t outline_color_index) { + if (outline_color_index == mp_const_none) { + return -1; + } + return mp_arg_validate_int_min(mp_obj_get_int(outline_color_index), 0, MP_QSTR_outline_color_index); +} + +static mp_obj_t outline_color_index_to_obj(int32_t outline_color_index) { + if (outline_color_index < 0) { + return mp_const_none; + } + return mp_obj_new_int(outline_color_index); +} + +static mp_int_t half_short_side(mp_int_t width, mp_int_t height) { + return (width < height ? width : height) / 2; +} + +static void validate_radius_and_outline(mp_int_t radius, mp_int_t outline_width, mp_int_t width, mp_int_t height) { + mp_int_t maximum = half_short_side(width, height); + mp_arg_validate_int_range(radius, 0, maximum, MP_QSTR_radius); + mp_arg_validate_int_range(outline_width, 0, maximum, MP_QSTR_outline_width); +} + static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_pixel_shader, ARG_width, ARG_height, ARG_x, ARG_y, ARG_color_index }; + enum { ARG_pixel_shader, ARG_width, ARG_height, ARG_x, ARG_y, ARG_color_index, ARG_radius, ARG_outline_width, ARG_outline_color_index }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pixel_shader, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED, {.u_obj = NULL } }, { MP_QSTR_width, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0 } }, @@ -42,6 +80,9 @@ static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_ { MP_QSTR_x, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_y, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_color_index, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_radius, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_width, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_color_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -50,10 +91,14 @@ static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_ mp_arg_validate_int_min(width, 1, MP_QSTR_width); mp_int_t height = args[ARG_height].u_int; mp_arg_validate_int_min(height, 1, MP_QSTR_height); + mp_int_t radius = args[ARG_radius].u_int; + mp_int_t outline_width = args[ARG_outline_width].u_int; + validate_radius_and_outline(radius, outline_width, width, height); vectorio_rectangle_t *self = mp_obj_malloc(vectorio_rectangle_t, &vectorio_rectangle_type); uint16_t color_index = args[ARG_color_index].u_int; - common_hal_vectorio_rectangle_construct(self, width, height, color_index); + int32_t outline_color_index = parse_outline_color_index(args[ARG_outline_color_index].u_obj); + common_hal_vectorio_rectangle_construct(self, width, height, color_index, radius, outline_width, outline_color_index); // VectorShape parts mp_obj_t pixel_shader = args[ARG_pixel_shader].u_obj; @@ -65,9 +110,22 @@ static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_ return MP_OBJ_FROM_PTR(self); } +// A Python subclass of Rectangle (a display_shapes RoundRect, for example) is an +// mp_obj_instance_t that holds the native Rectangle in subobj[0], so every entry point below +// has to see that native object instead of the instance. Resolving it here keeps the protocol +// slot on the native type. See displayio.TileGrid for the same pattern. +static vectorio_rectangle_t *native_rectangle(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&vectorio_rectangle_type)); + if (native == MP_OBJ_NULL) { + return MP_OBJ_TO_PTR(self_in); + } + mp_obj_assert_native_inited(native); + return MP_OBJ_TO_PTR(native); +} + #if CIRCUITPY_DISPLAYIO_LVGL static mp_obj_t rectangle_lvgl_protocol_self(mp_obj_t self_in) { - return common_hal_vectorio_rectangle_get_draw_protocol(MP_OBJ_TO_PTR(self_in)); + return common_hal_vectorio_rectangle_get_draw_protocol(native_rectangle(self_in)); } static const lvgl_protocol_t rectangle_lvgl_protocol = { @@ -76,9 +134,13 @@ static const lvgl_protocol_t rectangle_lvgl_protocol = { }; #define VECTORIO_RECTANGLE_PROTOCOL &rectangle_lvgl_protocol #else +static mp_obj_t rectangle_draw_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_rectangle_get_draw_protocol(native_rectangle(self_in)); +} + static const vectorio_draw_protocol_t rectangle_draw_protocol = { MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) - .draw_get_protocol_self = (draw_get_protocol_self_fun)common_hal_vectorio_rectangle_get_draw_protocol, + .draw_get_protocol_self = rectangle_draw_protocol_self, .draw_protocol_impl = &vectorio_vector_shape_draw_protocol_impl }; #define VECTORIO_RECTANGLE_PROTOCOL &rectangle_draw_protocol @@ -87,14 +149,16 @@ static const vectorio_draw_protocol_t rectangle_draw_protocol = { //| width: int //| """The width of the rectangle in pixels.""" static mp_obj_t vectorio_rectangle_obj_get_width(mp_obj_t self_in) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); return mp_obj_new_int(common_hal_vectorio_rectangle_get_width(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_width_obj, vectorio_rectangle_obj_get_width); static mp_obj_t vectorio_rectangle_obj_set_width(mp_obj_t self_in, mp_obj_t width) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_vectorio_rectangle_set_width(self, mp_obj_get_int(width)); + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_width = mp_arg_validate_int_min(mp_obj_get_int(width), 1, MP_QSTR_width); + validate_radius_and_outline(self->radius, self->outline_width, new_width, self->height); + common_hal_vectorio_rectangle_set_width(self, new_width); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_width_obj, vectorio_rectangle_obj_set_width); @@ -106,14 +170,16 @@ MP_PROPERTY_GETSET(vectorio_rectangle_width_obj, //| height: int //| """The height of the rectangle in pixels.""" static mp_obj_t vectorio_rectangle_obj_get_height(mp_obj_t self_in) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); return mp_obj_new_int(common_hal_vectorio_rectangle_get_height(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_height_obj, vectorio_rectangle_obj_get_height); static mp_obj_t vectorio_rectangle_obj_set_height(mp_obj_t self_in, mp_obj_t height) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_vectorio_rectangle_set_height(self, mp_obj_get_int(height)); + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_height = mp_arg_validate_int_min(mp_obj_get_int(height), 1, MP_QSTR_height); + validate_radius_and_outline(self->radius, self->outline_width, self->width, new_height); + common_hal_vectorio_rectangle_set_height(self, new_height); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_height_obj, vectorio_rectangle_obj_set_height); @@ -122,16 +188,83 @@ MP_PROPERTY_GETSET(vectorio_rectangle_height_obj, (mp_obj_t)&vectorio_rectangle_get_height_obj, (mp_obj_t)&vectorio_rectangle_set_height_obj); +//| radius: int +//| """The radius of the rectangle's corners in pixels. 0 is square corners. +//| +//| The radius must not exceed half of the shortest side.""" +static mp_obj_t vectorio_rectangle_obj_get_radius(mp_obj_t self_in) { + vectorio_rectangle_t *self = native_rectangle(self_in); + return mp_obj_new_int(common_hal_vectorio_rectangle_get_radius(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_radius_obj, vectorio_rectangle_obj_get_radius); + +static mp_obj_t vectorio_rectangle_obj_set_radius(mp_obj_t self_in, mp_obj_t radius) { + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_radius = mp_arg_validate_int_range(mp_obj_get_int(radius), 0, + half_short_side(self->width, self->height), MP_QSTR_radius); + common_hal_vectorio_rectangle_set_radius(self, new_radius); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_radius_obj, vectorio_rectangle_obj_set_radius); + +MP_PROPERTY_GETSET(vectorio_rectangle_radius_obj, + (mp_obj_t)&vectorio_rectangle_get_radius_obj, + (mp_obj_t)&vectorio_rectangle_set_radius_obj); + +//| outline_width: int +//| """The width of the border in pixels. The border is drawn inside the rectangle, so it +//| never changes the rectangle's size. 0 draws no border. The width must not exceed half +//| of the shortest side.""" +static mp_obj_t vectorio_rectangle_obj_get_outline_width(mp_obj_t self_in) { + vectorio_rectangle_t *self = native_rectangle(self_in); + return mp_obj_new_int(common_hal_vectorio_rectangle_get_outline_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_outline_width_obj, vectorio_rectangle_obj_get_outline_width); + +static mp_obj_t vectorio_rectangle_obj_set_outline_width(mp_obj_t self_in, mp_obj_t outline_width) { + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_outline_width = mp_arg_validate_int_range(mp_obj_get_int(outline_width), 0, + half_short_side(self->width, self->height), MP_QSTR_outline_width); + common_hal_vectorio_rectangle_set_outline_width(self, new_outline_width); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_outline_width_obj, vectorio_rectangle_obj_set_outline_width); + +MP_PROPERTY_GETSET(vectorio_rectangle_outline_width_obj, + (mp_obj_t)&vectorio_rectangle_get_outline_width_obj, + (mp_obj_t)&vectorio_rectangle_set_outline_width_obj); + +//| outline_color_index: Optional[int] +//| """The 0 based palette index of the border color, or ``None`` for no border. Only used +//| when :py:attr:`outline_width` is greater than 0.""" +static mp_obj_t vectorio_rectangle_obj_get_outline_color_index(mp_obj_t self_in) { + vectorio_rectangle_t *self = native_rectangle(self_in); + return outline_color_index_to_obj(common_hal_vectorio_rectangle_get_outline_color_index(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_outline_color_index_obj, vectorio_rectangle_obj_get_outline_color_index); + +static mp_obj_t vectorio_rectangle_obj_set_outline_color_index(mp_obj_t self_in, mp_obj_t outline_color_index) { + vectorio_rectangle_t *self = native_rectangle(self_in); + common_hal_vectorio_rectangle_set_outline_color_index(self, + parse_outline_color_index(outline_color_index)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_outline_color_index_obj, vectorio_rectangle_obj_set_outline_color_index); + +MP_PROPERTY_GETSET(vectorio_rectangle_outline_color_index_obj, + (mp_obj_t)&vectorio_rectangle_get_outline_color_index_obj, + (mp_obj_t)&vectorio_rectangle_set_outline_color_index_obj); + //| color_index: int //| """The color_index of the rectangle in 1 based index of the palette.""" static mp_obj_t vectorio_rectangle_obj_get_color_index(mp_obj_t self_in) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); return mp_obj_new_int(common_hal_vectorio_rectangle_get_color_index(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_color_index_obj, vectorio_rectangle_obj_get_color_index); static mp_obj_t vectorio_rectangle_obj_set_color_index(mp_obj_t self_in, mp_obj_t color_index) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); common_hal_vectorio_rectangle_set_color_index(self, mp_obj_get_int(color_index)); return mp_const_none; } @@ -170,6 +303,9 @@ static const mp_rom_map_elem_t vectorio_rectangle_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_color_index), MP_ROM_PTR(&vectorio_rectangle_color_index_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&vectorio_rectangle_width_obj) }, { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&vectorio_rectangle_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_radius), MP_ROM_PTR(&vectorio_rectangle_radius_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_width), MP_ROM_PTR(&vectorio_rectangle_outline_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_color_index), MP_ROM_PTR(&vectorio_rectangle_outline_color_index_obj) }, { MP_ROM_QSTR(MP_QSTR_location), MP_ROM_PTR(&vectorio_vector_shape_location_obj) }, { MP_ROM_QSTR(MP_QSTR_pixel_shader), MP_ROM_PTR(&vectorio_vector_shape_pixel_shader_obj) }, }; diff --git a/shared-bindings/vectorio/Rectangle.h b/shared-bindings/vectorio/Rectangle.h index 6831fa21029..dee771c38e8 100644 --- a/shared-bindings/vectorio/Rectangle.h +++ b/shared-bindings/vectorio/Rectangle.h @@ -12,7 +12,7 @@ extern const mp_obj_type_t vectorio_rectangle_type; -void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index); +void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index, uint16_t radius, uint16_t outline_width, int32_t outline_color_index); void common_hal_vectorio_rectangle_set_on_dirty(vectorio_rectangle_t *self, vectorio_event_t on_dirty); uint32_t common_hal_vectorio_rectangle_get_pixel(void *rectangle, int16_t x, int16_t y); @@ -29,3 +29,13 @@ void common_hal_vectorio_rectangle_set_color_index(void *obj, uint16_t color_ind int16_t common_hal_vectorio_rectangle_get_height(void *obj); void common_hal_vectorio_rectangle_set_height(void *obj, int16_t height); + +uint16_t common_hal_vectorio_rectangle_get_radius(void *obj); +void common_hal_vectorio_rectangle_set_radius(void *obj, uint16_t radius); + +uint16_t common_hal_vectorio_rectangle_get_outline_width(void *obj); +void common_hal_vectorio_rectangle_set_outline_width(void *obj, uint16_t outline_width); + +// -1 means no outline color was set. +int32_t common_hal_vectorio_rectangle_get_outline_color_index(void *obj); +void common_hal_vectorio_rectangle_set_outline_color_index(void *obj, int32_t outline_color_index); diff --git a/shared-module/vectorio/Circle.c b/shared-module/vectorio/Circle.c index 6f7ee2f3406..91cbe91b2a6 100644 --- a/shared-module/vectorio/Circle.c +++ b/shared-module/vectorio/Circle.c @@ -12,10 +12,12 @@ #include "stdlib.h" -void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index) { +void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index, uint16_t outline_width, int32_t outline_color_index) { self->radius = radius; self->on_dirty.obj = NULL; self->color_index = color_index + 1; + self->outline_width = outline_width; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; } void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_event_t on_dirty) { @@ -26,22 +28,33 @@ void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_e } -uint32_t common_hal_vectorio_circle_get_pixel(void *obj, int16_t x, int16_t y) { - vectorio_circle_t *self = obj; - int16_t radius = self->radius; - x = abs(x); - y = abs(y); +// Coverage of a circle of the given radius, for a point x/y pixels right of and below its +// center. (x + y <= radius) implies x*x + y*y <= radius*radius, which keeps the pixels nearest +// the center from paying for the multiplication. +static bool circle_covers(int32_t x, int32_t y, int32_t radius) { + x = x < 0 ? -x : x; + y = y < 0 ? -y : y; if (x + y <= radius) { - return self->color_index; + return true; } - if (x > radius) { - return 0; + if (x > radius || y > radius) { + return false; } - if (y > radius) { + return x * x + y * y <= radius * radius; +} + +uint32_t common_hal_vectorio_circle_get_pixel(void *obj, int16_t x, int16_t y) { + vectorio_circle_t *self = obj; + int32_t radius = self->radius; + if (!circle_covers(x, y, radius)) { return 0; } - const bool pythagorasSmallerThanRadius = (int32_t)x * x + (int32_t)y * y <= (int32_t)radius * radius; - return pythagorasSmallerThanRadius ? self->color_index : 0; + // A zero outline_color_index means no outline was set, and then the fill reaches the edge. + if (self->outline_width > 0 && self->outline_color_index != 0 && + !circle_covers(x, y, radius - self->outline_width)) { + return self->outline_color_index; + } + return self->color_index; } @@ -66,6 +79,19 @@ void common_hal_vectorio_circle_set_radius(void *obj, int16_t radius) { } } +uint16_t common_hal_vectorio_circle_get_outline_width(void *obj) { + vectorio_circle_t *self = obj; + return self->outline_width; +} + +void common_hal_vectorio_circle_set_outline_width(void *obj, uint16_t outline_width) { + vectorio_circle_t *self = obj; + self->outline_width = outline_width; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + uint16_t common_hal_vectorio_circle_get_color_index(void *obj) { vectorio_circle_t *self = obj; return self->color_index - 1; @@ -79,6 +105,19 @@ void common_hal_vectorio_circle_set_color_index(void *obj, uint16_t color_index) } } +int32_t common_hal_vectorio_circle_get_outline_color_index(void *obj) { + vectorio_circle_t *self = obj; + return self->outline_color_index == 0 ? -1 : self->outline_color_index - 1; +} + +void common_hal_vectorio_circle_set_outline_color_index(void *obj, int32_t outline_color_index) { + vectorio_circle_t *self = obj; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + mp_obj_t common_hal_vectorio_circle_get_draw_protocol(void *circle) { vectorio_circle_t *self = circle; return self->draw_protocol_instance; diff --git a/shared-module/vectorio/Circle.h b/shared-module/vectorio/Circle.h index 48d20b28d5c..561361dd0ab 100644 --- a/shared-module/vectorio/Circle.h +++ b/shared-module/vectorio/Circle.h @@ -16,6 +16,11 @@ typedef struct { mp_obj_base_t base; uint16_t radius; uint16_t color_index; + // The outline is a ring inside the circle's outer edge, so it changes the circle's + // appearance but not its footprint. outline_color_index is biased by one like + // color_index, so that 0 can mean "no outline" as well as "not covered". + uint16_t outline_width; + uint16_t outline_color_index; vectorio_event_t on_dirty; mp_obj_t draw_protocol_instance; } vectorio_circle_t; diff --git a/shared-module/vectorio/Rectangle.c b/shared-module/vectorio/Rectangle.c index 42cdf7cca96..145af405780 100644 --- a/shared-module/vectorio/Rectangle.c +++ b/shared-module/vectorio/Rectangle.c @@ -12,10 +12,15 @@ #include "stdlib.h" -void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index) { +void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index, uint16_t radius, uint16_t outline_width, int32_t outline_color_index) { self->width = width; self->height = height; self->color_index = color_index + 1; + self->radius = radius; + self->outline_width = outline_width; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; + // set_on_dirty() uses this to detect a second parent, so it has to start empty. + self->on_dirty.obj = NULL; } void common_hal_vectorio_rectangle_set_on_dirty(vectorio_rectangle_t *self, vectorio_event_t on_dirty) { @@ -25,12 +30,60 @@ void common_hal_vectorio_rectangle_set_on_dirty(vectorio_rectangle_t *self, vect self->on_dirty = on_dirty; } +// Coverage of a rounded rectangle of the given extent whose top left pixel is (0, 0). The +// corner arcs are centered one radius in from each corner, which is the same center +// display_shapes' midpoint circle uses, so swapping implementations moves few pixels. +// +// Distances are doubled so that pixel centers land on integers instead of half pixels. +// The bindings ensure that `radius` is at most half of the shortest side. +static bool rectangle_covers(int32_t x, int32_t y, uint16_t width, uint16_t height, uint16_t radius) { + if (x < 0 || y < 0 || x >= (int32_t)width || y >= (int32_t)height) { + return false; + } + if (radius == 0) { + return true; + } + // 2x+1 is twice the pixel's center, so these are the distances from the nearest corner + // arc's center in halves of a pixel. 0 means the pixel is on one of the flat sides. + int32_t twice_radius = 2 * (int32_t)radius; + int32_t twice_x = 2 * x + 1; + int32_t twice_y = 2 * y + 1; + int32_t dx = 0; + int32_t dy = 0; + if (twice_x < twice_radius) { + dx = twice_radius - twice_x; + } else if (twice_x > 2 * (int32_t)width - twice_radius) { + dx = twice_x - (2 * (int32_t)width - twice_radius); + } + if (twice_y < twice_radius) { + dy = twice_radius - twice_y; + } else if (twice_y > 2 * (int32_t)height - twice_radius) { + dy = twice_y - (2 * (int32_t)height - twice_radius); + } + if (dx == 0 || dy == 0) { + return true; + } + return (int64_t)dx * dx + (int64_t)dy * dy <= (int64_t)twice_radius * twice_radius; +} + uint32_t common_hal_vectorio_rectangle_get_pixel(void *obj, int16_t x, int16_t y) { vectorio_rectangle_t *self = obj; - if (x >= 0 && y >= 0 && x < self->width && y < self->height) { - return self->color_index; + uint16_t radius = self->radius; + if (!rectangle_covers(x, y, self->width, self->height, radius)) { + return 0; + } + uint16_t outline_width = self->outline_width; + // A zero outline_color_index means no outline was set, and then the fill reaches the edge. + if (outline_width > 0 && self->outline_color_index != 0) { + // The outline is the band between the outer edge and a copy of the rectangle inset by + // the outline width. Inset corners stay concentric, so the inner radius shrinks too. + uint16_t inner_radius = radius > outline_width ? radius - outline_width : 0; + if (!rectangle_covers(x - outline_width, y - outline_width, + self->width - 2 * outline_width, self->height - 2 * outline_width, inner_radius)) { + return self->outline_color_index; + } } - return 0; + return self->color_index; } @@ -74,6 +127,32 @@ void common_hal_vectorio_rectangle_set_height(void *obj, int16_t height) { } } +uint16_t common_hal_vectorio_rectangle_get_radius(void *obj) { + vectorio_rectangle_t *self = obj; + return self->radius; +} + +void common_hal_vectorio_rectangle_set_radius(void *obj, uint16_t radius) { + vectorio_rectangle_t *self = obj; + self->radius = radius; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + +uint16_t common_hal_vectorio_rectangle_get_outline_width(void *obj) { + vectorio_rectangle_t *self = obj; + return self->outline_width; +} + +void common_hal_vectorio_rectangle_set_outline_width(void *obj, uint16_t outline_width) { + vectorio_rectangle_t *self = obj; + self->outline_width = outline_width; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + uint16_t common_hal_vectorio_rectangle_get_color_index(void *obj) { vectorio_rectangle_t *self = obj; return self->color_index - 1; @@ -86,3 +165,16 @@ void common_hal_vectorio_rectangle_set_color_index(void *obj, uint16_t color_ind self->on_dirty.event(self->on_dirty.obj); } } + +int32_t common_hal_vectorio_rectangle_get_outline_color_index(void *obj) { + vectorio_rectangle_t *self = obj; + return self->outline_color_index == 0 ? -1 : self->outline_color_index - 1; +} + +void common_hal_vectorio_rectangle_set_outline_color_index(void *obj, int32_t outline_color_index) { + vectorio_rectangle_t *self = obj; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} diff --git a/shared-module/vectorio/Rectangle.h b/shared-module/vectorio/Rectangle.h index 6733f74d170..e989a94fc95 100644 --- a/shared-module/vectorio/Rectangle.h +++ b/shared-module/vectorio/Rectangle.h @@ -16,6 +16,16 @@ typedef struct { uint16_t width; uint16_t height; uint16_t color_index; + // The corner radius and the outline width are in the rectangle's own pixels, and neither + // may exceed half of the shortest side. The outline is drawn inside the rectangle's + // bounds, so neither one changes the rectangle's footprint. + // + // outline_color_index is biased by one like color_index, so that 0 can mean "no outline" + // as well as "not covered" (see VectorShape.h). A radius or outline width change is a + // pure appearance change: the coverage stays inside the same bounds. + uint16_t radius; + uint16_t outline_width; + uint16_t outline_color_index; vectorio_event_t on_dirty; mp_obj_t draw_protocol_instance; } vectorio_rectangle_t; diff --git a/shared-module/vectorio/lvgl/VectorShape.c b/shared-module/vectorio/lvgl/VectorShape.c index 10fc13dbb85..7503177a216 100644 --- a/shared-module/vectorio/lvgl/VectorShape.c +++ b/shared-module/vectorio/lvgl/VectorShape.c @@ -41,6 +41,37 @@ static uint16_t _biased_color_index(vectorio_vector_shape_t *self) { return ((vectorio_polygon_t *)MP_OBJ_TO_PTR(self->ishape.shape))->color_index; } +// The shape's outline color index, still biased by one like its color_index. Polygon has no +// outline: it draws through an A8 mask image, which has no border of its own. +static uint16_t _biased_outline_color_index(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_color_index; + } + if (mp_obj_is_type(self->ishape.shape, &vectorio_circle_type)) { + return ((vectorio_circle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_color_index; + } + return 0; +} + +// Corner radius and outline width in the shape's own pixels. A circle is drawn with +// LV_RADIUS_CIRCLE instead of a stored radius, so its radius is not read here. +static uint16_t _shape_radius(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->radius; + } + return 0; +} + +static uint16_t _shape_outline_width(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_width; + } + if (mp_obj_is_type(self->ishape.shape, &vectorio_circle_type)) { + return ((vectorio_circle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_width; + } + return 0; +} + // Resolve the pixel shader to the color to paint. Returns false when nothing should be // drawn at all, which is what the "not covered" color index, a transparent palette entry // and a ColorConverter's transparent color all mean. @@ -220,26 +251,42 @@ static void _sync_mirror(vectorio_vector_shape_t *self, bool rebuild_mask) { // A new size means a new mask buffer too. rebuild_mask = true; } - if (polygon && rebuild_mask) { - _refresh_mask(self, x1, y1, w, h, scale); - } else if (!polygon) { - bool circle = mp_obj_is_type(self->ishape.shape, &vectorio_circle_type); - lv_obj_set_style_radius(self->lv_obj, circle ? LV_RADIUS_CIRCLE : 0, 0); - } lv_color_t color; bool painted = !empty && _resolve_color(self->pixel_shader, _biased_color_index(self), &color); + if (polygon) { + if (rebuild_mask) { + _refresh_mask(self, x1, y1, w, h, scale); + } if (painted) { lv_obj_set_style_image_recolor(self->lv_obj, color, 0); } lv_obj_set_style_image_recolor_opa(self->lv_obj, painted ? LV_OPA_COVER : LV_OPA_TRANSP, 0); - } else { - if (painted) { - lv_obj_set_style_bg_color(self->lv_obj, color, 0); - } - lv_obj_set_style_bg_opa(self->lv_obj, painted ? LV_OPA_COVER : LV_OPA_TRANSP, 0); + return; + } + + // The fill and the outline are style properties of the same lv_obj, so LVGL draws the + // corners once for the fill and once for the border and neither is recomputed by us. A + // scaled group scales the object's size, so the shape's own pixels have to be scaled too + // to keep the corners and the outline proportional. + bool circle = mp_obj_is_type(self->ishape.shape, &vectorio_circle_type); + int32_t radius = circle ? LV_RADIUS_CIRCLE : (int32_t)_shape_radius(self) * scale; + uint16_t outline_width = _shape_outline_width(self); + lv_color_t outline_color; + bool outlined = !empty && outline_width > 0 && + _resolve_color(self->pixel_shader, _biased_outline_color_index(self), &outline_color); + + lv_obj_set_style_radius(self->lv_obj, radius, 0); + lv_obj_set_style_border_width(self->lv_obj, outlined ? (int32_t)outline_width * scale : 0, 0); + if (painted) { + lv_obj_set_style_bg_color(self->lv_obj, color, 0); + } + lv_obj_set_style_bg_opa(self->lv_obj, painted ? LV_OPA_COVER : LV_OPA_TRANSP, 0); + if (outlined) { + lv_obj_set_style_border_color(self->lv_obj, outline_color, 0); } + lv_obj_set_style_border_opa(self->lv_obj, outlined ? LV_OPA_COVER : LV_OPA_TRANSP, 0); } // A move changes nothing but where the shape is, so the polygon mask survives it. @@ -409,6 +456,7 @@ void displayio_lvgl_vector_shape_attach(vectorio_vector_shape_t *self, lv_obj_t lv_obj_remove_style_all(self->lv_obj); lv_obj_set_style_pad_all(self->lv_obj, 0, 0); lv_obj_set_style_border_width(self->lv_obj, 0, 0); + lv_obj_set_style_border_side(self->lv_obj, LV_BORDER_SIDE_FULL, 0); lv_obj_set_style_radius(self->lv_obj, 0, 0); lv_obj_set_style_bg_opa(self->lv_obj, LV_OPA_TRANSP, 0); lv_obj_set_style_opa(self->lv_obj, LV_OPA_COVER, 0); From 26790385a92547e5e2eb9e7b59b242c8ea37784b Mon Sep 17 00:00:00 2001 From: Scott Shawcroft Date: Wed, 18 Nov 2026 10:32:52 -0800 Subject: [PATCH 2/2] Improve vectorio test and validate circle outline width --- ports/zephyr-cp/tests/test_vectorio.py | 69 ++++++++++++++++++++++++-- shared-bindings/vectorio/Circle.c | 15 ++++-- 2 files changed, 76 insertions(+), 8 deletions(-) diff --git a/ports/zephyr-cp/tests/test_vectorio.py b/ports/zephyr-cp/tests/test_vectorio.py index bbefb56a263..657bbddef45 100644 --- a/ports/zephyr-cp/tests/test_vectorio.py +++ b/ports/zephyr-cp/tests/test_vectorio.py @@ -361,9 +361,26 @@ def test_vectorio_move_and_hide(circuitpython): palette.make_transparent(1) print('transparent fill', rectangle.contains(50, 30)) -# The circle ring behaves the same way. +# The circle ring behaves the same way. Its outline cannot be wider than its +# radius, and shrinking the radius cannot invalidate an existing outline. +try: + vectorio.Circle(pixel_shader=palette, radius=20, outline_width=21) +except ValueError: + print('circle constructor outline limit: ValueError') circle = vectorio.Circle(pixel_shader=palette, radius=20, x=100, y=100, color_index=2, outline_width=4, outline_color_index=3) +try: + circle.outline_width = 21 +except ValueError: + print('circle outline limit: ValueError') +try: + circle.radius = 3 +except ValueError: + print('circle resize limit: ValueError') +print('circle limits', circle.radius, circle.outline_width) +# The maximum itself is valid. +circle.outline_width = circle.radius +circle.outline_width = 4 print('ring', circle.outline_width, circle.outline_color_index, circle.contains(100, 84), circle.contains(100, 100), circle.contains(100, 79), circle.contains(100, 121)) @@ -421,7 +438,9 @@ def outline(self, color): self._palette.make_opaque(1) -round_rect = RoundRect(10, 10, 80, 40, 12, fill=0xFF0000, outline=0x00FF00, stroke=4) +# Use display_shapes.RoundRect's default one-pixel stroke, not only the thicker +# outlines exercised by the native API and rendering tests. +round_rect = RoundRect(10, 10, 80, 40, 12, fill=0xFF0000, outline=0x00FF00) print('size', round_rect.x, round_rect.y, round_rect.width, round_rect.height) print('shape', round_rect.radius, round_rect.outline_width, round_rect.outline_color_index, round_rect.color_index) @@ -473,6 +492,39 @@ class SubclassedPolygon(vectorio.Polygon): print('other mutations', circle.radius, circle.outline_width, polygon.points, polygon.color_index, circle.contains(150, 100), polygon.contains(225, 105)) +# Until super().__init__() runs, the instance has no native Rectangle. Native properties, +# inherited VectorShape properties and Group.append() must raise instead of treating the +# Python instance as a native shape. +class EarlyAccess(vectorio.Rectangle): + def __init__(self, palette): + self.early = [] + for name, attempt in ( + ('radius', lambda: self.radius), + ('x', lambda: self.x), + ('append', lambda: displayio.Group().append(self)), + ): + try: + attempt() + self.early.append(name + ' ok') + except Exception as e: + self.early.append(name + ' ' + type(e).__name__) + super().__init__(pixel_shader=palette, width=20, height=20, radius=5) + + +early = EarlyAccess(round_rect._palette) +print('early access', ', '.join(early.early), early.radius) + + +# An __init__() that never calls super().__init__() gets its native Rectangle built +# afterwards from the constructor's arguments. +class NoSuperInit(vectorio.Rectangle): + def __init__(self, **kwargs): + pass + + +late = NoSuperInit(pixel_shader=round_rect._palette, width=20, height=20, radius=5) +print('no super init', late.width, late.radius) + # Restore the rectangle after the API checks and render all three Python subclasses. This # verifies that Group's protocol lookup reaches the native wrapper on both compositors. round_rect.x = 10 @@ -562,6 +614,10 @@ def test_vectorio_radius_and_outline_api(circuitpython): assert "no outline True 0" in output assert "transparent fill True" in output # The ring covers radius-4..radius, the fill covers everything inside. + assert "circle constructor outline limit: ValueError" in output + assert "circle outline limit: ValueError" in output + assert "circle resize limit: ValueError" in output + assert "circle limits 20 4" in output assert "ring 4 3 True True False False" in output assert "no ring True" in output assert "done" in output @@ -576,7 +632,7 @@ def test_vectorio_python_subclass(circuitpython): output = circuitpython.serial.all_output assert "size 10 10 80 40" in output - assert "shape 12 4 1 0" in output + assert "shape 12 1 1 0" in output assert "colors 0xff0000 0xff00" in output assert "shader True" in output assert "contains True False" in output @@ -588,6 +644,13 @@ def test_vectorio_python_subclass(circuitpython): assert "second group: ValueError" in output assert "other shapes 20 4 1 [(0, 0), (40, 0), (0, 40)] 0" in output assert "other mutations 22 3 [(0, 0), (50, 0), (0, 40)] 1 True True" in output + # Before super().__init__(), every entry point raises instead of reading the instance + # as a native shape. Without super().__init__(), the native base is built afterwards. + assert ( + "early access radius NotImplementedError, x NotImplementedError, " + "append NotImplementedError 5" in output + ) + assert "no super init 20 5" in output assert "done" in output assert "rendered" in output diff --git a/shared-bindings/vectorio/Circle.c b/shared-bindings/vectorio/Circle.c index cc6b053fd05..7965a4e9d54 100644 --- a/shared-bindings/vectorio/Circle.c +++ b/shared-bindings/vectorio/Circle.c @@ -34,7 +34,7 @@ //| :param int color_index: Initial color_index to use when selecting color from the palette. //| :param int outline_width: The width in pixels of a ring drawn just inside the //| circle's outer edge, so it never makes the circle bigger. 0 (the default) -//| draws no ring. +//| draws no ring. The width must not exceed the radius. //| :param Optional[int] outline_color_index: The 0 based palette index of the ring //| color, or ``None`` (the default) for no ring. Only used when //| ``outline_width`` is greater than 0. Use ``None`` rather than a transparent @@ -75,7 +75,7 @@ static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_arg mp_arg_validate_int_min(radius, 1, MP_QSTR_radius); mp_int_t outline_width = args[ARG_outline_width].u_int; - mp_arg_validate_int_min(outline_width, 0, MP_QSTR_outline_width); + mp_arg_validate_int_range(outline_width, 0, radius, MP_QSTR_outline_width); vectorio_circle_t *self = mp_obj_malloc(vectorio_circle_t, &vectorio_circle_type); uint16_t color_index = args[ARG_color_index].u_int; @@ -138,7 +138,10 @@ MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_radius_obj, vectorio_circle_obj_ge static mp_obj_t vectorio_circle_obj_set_radius(mp_obj_t self_in, mp_obj_t radius) { vectorio_circle_t *self = native_circle(self_in); - common_hal_vectorio_circle_set_radius(self, mp_obj_get_int(radius)); + mp_int_t new_radius = mp_arg_validate_int_min(mp_obj_get_int(radius), 1, MP_QSTR_radius); + // Shrinking the circle must not leave an outline wider than its new radius. + mp_arg_validate_int_range(self->outline_width, 0, new_radius, MP_QSTR_outline_width); + common_hal_vectorio_circle_set_radius(self, new_radius); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_radius_obj, vectorio_circle_obj_set_radius); @@ -168,7 +171,7 @@ MP_PROPERTY_GETSET(vectorio_circle_color_index_obj, //| outline_width: int //| """The width of the ring in pixels. The ring is drawn inside the circle, so it never -//| changes the circle's size. 0 draws no ring.""" +//| changes the circle's size. 0 draws no ring. The width must not exceed the radius.""" static mp_obj_t vectorio_circle_obj_get_outline_width(mp_obj_t self_in) { vectorio_circle_t *self = native_circle(self_in); return mp_obj_new_int(common_hal_vectorio_circle_get_outline_width(self)); @@ -177,7 +180,9 @@ MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_outline_width_obj, vectorio_circle static mp_obj_t vectorio_circle_obj_set_outline_width(mp_obj_t self_in, mp_obj_t outline_width) { vectorio_circle_t *self = native_circle(self_in); - common_hal_vectorio_circle_set_outline_width(self, mp_arg_validate_int_min(mp_obj_get_int(outline_width), 0, MP_QSTR_outline_width)); + mp_int_t new_outline_width = mp_arg_validate_int_range(mp_obj_get_int(outline_width), 0, + self->radius, MP_QSTR_outline_width); + common_hal_vectorio_circle_set_outline_width(self, new_outline_width); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_outline_width_obj, vectorio_circle_obj_set_outline_width);