From c553f22f1ec6d4694d39b70663ed1e23f97f4758 Mon Sep 17 00:00:00 2001 From: Mika Tuupola Date: Fri, 3 Apr 2026 09:09:27 +0300 Subject: [PATCH 1/2] Change to insertion sort In theory faster, but the effect is minimal until there is lot of vertices. --- src/hagl_polygon.c | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/hagl_polygon.c b/src/hagl_polygon.c index 666c92a..d49040a 100644 --- a/src/hagl_polygon.c +++ b/src/hagl_polygon.c @@ -115,19 +115,15 @@ void hagl_fill_polygon( j = i; } - /* Sort the nodes, via a simple “Bubble” sort. */ - int16_t i = 0; - while (i < count - 1) { - if (nodes[i] > nodes[i + 1]) { - int16_t swap = nodes[i]; - nodes[i] = nodes[i + 1]; - nodes[i + 1] = swap; - if (i) { - i--; - } - } else { - i++; + /* Sort the nodes, via insertion sort. */ + for (int16_t i = 1; i < count; i++) { + int16_t key = nodes[i]; + int16_t j = i - 1; + while (j >= 0 && nodes[j] > key) { + nodes[j + 1] = nodes[j]; + j--; } + nodes[j + 1] = key; } /* Draw lines between nodes. */ From bb071c2c404ce312a50bab4e11e0f18c2bb18d09 Mon Sep 17 00:00:00 2001 From: Mika Tuupola Date: Wed, 16 Sep 2026 17:08:33 +0300 Subject: [PATCH 2/2] Clamp miny and maxy with clip window --- src/hagl_polygon.c | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/hagl_polygon.c b/src/hagl_polygon.c index d49040a..e8f07b0 100644 --- a/src/hagl_polygon.c +++ b/src/hagl_polygon.c @@ -79,18 +79,30 @@ void hagl_fill_polygon( return; } - miny = surface->height; - maxy = 0; + miny = vertices[1]; + maxy = vertices[1]; - for (uint8_t i = 0; i < amount; i++) { - if (miny > vertices[(i << 1) + 1]) { - miny = vertices[(i << 1) + 1]; + for (int16_t i = 1; i < amount; i++) { + int16_t vy = vertices[(i << 1) + 1]; + if (miny > vy) { + miny = vy; } - if (maxy < vertices[(i << 1) + 1]) { - maxy = vertices[(i << 1) + 1]; + if (maxy < vy) { + maxy = vy; } } + if ((maxy < surface->clip.y0) || (miny > surface->clip.y1)) { + return; + } + + if (miny < surface->clip.y0) { + miny = surface->clip.y0; + } + if (maxy > surface->clip.y1) { + maxy = surface->clip.y1; + } + /* Loop through the rows of the image. */ for (y = miny; y <= maxy; y++) {