From a106191026d92cf90c03ce89873a260bdc7b5ec7 Mon Sep 17 00:00:00 2001 From: strike19 <26605353+strike19@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:02:10 +0100 Subject: [PATCH] Skip the part of width 1 lines outside the image in C Restricting lines to the image in Python (#10610) moves their end points, so that Bresenham's algorithm sets different pixels inside the image than for the whole line, and the same line moved by whole pixels no longer gives the same pixels. Instead, keep the end points and skip the steps before and after the image in C. The error term for the first visible step follows from the minor axis offset k(i) = floor((2 * minor * i + major) / (2 * major)), computed with 64-bit integers, as the coordinates are 32-bit and the product of the smaller delta and the number of skipped steps can reach 2**64. The dash position is taken modulo the length of the pattern, so that long dashed lines take no time either. Python now only restricts lines that reach outside the range of C ints. Co-Authored-By: Claude Opus 5.5 --- Tests/test_imagedraw.py | 28 ++++++ src/PIL/ImageDraw.py | 24 +++-- src/libImaging/Draw.c | 211 ++++++++++++++++++++-------------------- 3 files changed, 151 insertions(+), 112 deletions(-) diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py index 01a9b36a40f..40e2d5f2efb 100644 --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -507,6 +507,34 @@ def test_line_far_outside_image(far: Coords, near: Coords) -> None: assert_image_equal(im, expected) +@timeout_unless_slower_valgrind(1) +def test_line_far_outside_image_dash() -> None: + expected = Image.new("L", (16, 16)) + ImageDraw.Draw(expected).line(((0, 0), (20, 0)), 255, dash=(4, 2)) + im = Image.new("L", (16, 16)) + ImageDraw.Draw(im).line(((0, 0), (2**30, 1)), 255, dash=(4, 2)) + assert_image_equal(im, expected) + + +@pytest.mark.parametrize("dash", (None, (4, 2), (3, 1, 2))) +def test_line_partly_outside_image(dash: tuple[int, ...] | None) -> None: + # The pixels inside the image are those of the whole line, + # drawn on an image that it does not leave + values = range(-45, 86, 19) + for a in values: + for b in values: + for c in values: + for d in values: + xy = [(a, b), (c, d), (b, a)] + im = Image.new("L", (40, 40)) + ImageDraw.Draw(im).line(xy, 255, dash=dash) + + large = Image.new("L", (400, 400)) + moved = [(x + 200, y + 200) for x, y in xy] + ImageDraw.Draw(large).line(moved, 255, dash=dash) + assert_image_equal(im, large.crop((200, 200, 240, 240))) + + def test_shape1() -> None: # Arrange im = Image.new("RGB", (100, 100), "white") diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py index d6ef7cc8a5b..aefba206acb 100644 --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -241,10 +241,18 @@ def _normalize_coords(self, xy: Coords) -> list[tuple[float, float]]: def _restrict_lines( self, xy: list[tuple[float, float]] ) -> list[list[tuple[float, float]]]: - """Restrict line coordinates to image using Liang–Barsky algorithm""" - w, h = self.im.size - if len(xy) == 1 or all(0 <= x <= w and 0 <= y <= h for x, y in xy): + """ + Restrict line coordinates to the range of C ints, using the Liang–Barsky + algorithm. The C code skips the part of a line outside the image by + itself and then draws exactly the pixels of the whole line, so lines + within that range are left unchanged. + """ + if len(xy) == 1 or all( + -(2**31) <= x < 2**31 and -(2**31) <= y < 2**31 for x, y in xy + ): return [xy] + # Clip to a smaller range, so that rounding errors stay within C ints + lo, hi = -(2**30), 2**30 lines = [] line: list[tuple[float, float]] = [] @@ -254,10 +262,10 @@ def _restrict_lines( u1, u2 = 0.0, 1.0 for p, q in ( - (-dx, x0), # left side - (dx, w - x0), # right side - (-dy, y0), # top side - (dy, h - y0), # bottom side + (-dx, x0 - lo), # left side + (dx, hi - x0), # right side + (-dy, y0 - lo), # top side + (dy, hi - y0), # bottom side ): if p == 0: # line is parallel to the side @@ -311,7 +319,7 @@ def line( if dash is not None: self._validate_dash(dash) normalized_xy = self._normalize_coords(xy) - if width == 1: + if width == 1 or dash is not None: lines = self._restrict_lines(normalized_xy) else: lines = [normalized_xy] diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c index 01e170ad485..a11573bc37d 100644 --- a/src/libImaging/Draw.c +++ b/src/libImaging/Draw.c @@ -240,30 +240,47 @@ hline32rgba(Imaging im, int x0, int y0, int x1, int ink, Imaging mask) { } } -static inline int -should_draw_dash(int i, int *dash_offset, PyObject *dash) { - i += *dash_offset; - int total = 0; - int tuple_index = -1; - int tuple_size = PyTuple_GET_SIZE(dash); - while (total <= i) { - tuple_index += 1; - if (tuple_index == tuple_size) { - tuple_index = 0; - } - PyObject *value = PyTuple_GetItem(dash, tuple_index); +/* Returns the total length of the dash pattern, or 0 if it is not usable */ +static inline int64_t +dash_length(PyObject *dash) { + int64_t total = 0; + Py_ssize_t i, size = PyTuple_GET_SIZE(dash); + for (i = 0; i < size; i++) { + PyObject *value = PyTuple_GetItem(dash, i); if (!PyLong_Check(value)) { return 0; } - int v = PyLong_AsLongLong(value); - if (v == -1 && PyErr_Occurred()) { + long long v = PyLong_AsLongLong(value); + if ((v == -1 && PyErr_Occurred()) || v < 0 || v > INT32_MAX) { + PyErr_Clear(); return 0; } total += v; } - return tuple_index % 2 == 0; + return total; +} + +/* Whether the pixel at position pos (0 <= pos < length) of the dash pattern + * is drawn. Even entries of the pattern are dashes, odd entries are gaps. */ +static inline int +should_draw_dash(int64_t pos, PyObject *dash) { + Py_ssize_t i, size = PyTuple_GET_SIZE(dash); + for (i = 0; i < size; i++) { + int64_t v = PyLong_AsLongLong(PyTuple_GetItem(dash, i)); + if (pos < v) { + return i % 2 == 0; + } + pos -= v; + } + return 0; } +/* Draws the pixels of a line from (x0, y0) to (x1, y1), excluding the end + * point, as Bresenham's algorithm visits them. Step i of the major axis sets + * the minor axis offset k(i) = floor((2 * minor * i + major) / (2 * major)), + * so the steps before the image can be skipped and the error term computed + * for the first visible step. The pixels drawn are exactly those of the whole + * line, however far it reaches outside the image. */ static inline void line( Imaging im, @@ -277,119 +294,105 @@ line( PyObject *dash, int *dash_offset ) { - int i, n, e, dx, dy, xs, ys; + int64_t dx, dy, xs, ys, n, d, i, first, last, e, k, major, minor; + int64_t major_size, minor_size, major_step, minor_step, length = 0; + int xmajor; + uint64_t p; /* normalize coordinates */ - dx = x1 - x0; + dx = (int64_t)x1 - x0; if (dx < 0) { dx = -dx, xs = -1; } else { xs = 1; } - dy = y1 - y0; + dy = (int64_t)y1 - y0; if (dy < 0) { dy = -dy, ys = -1; - } else if (dy == 0) { - /* horizontal */ - if (dash != NULL) { - for (i = 0; i < dx; i++) { - if (should_draw_dash(i, dash_offset, dash)) { - point(im, x0, y0, ink); - } - x0 += xs; - } - *dash_offset += dx; - } else if (x1 > x0) { + } else { + ys = 1; + } + + if (dy == 0 && dash == NULL) { + /* horizontal, hline clips to the image */ + if (x1 > x0) { hline(im, x0, y0, x1 - 1, ink, NULL); } else if (x0 > x1) { hline(im, x1 + 1, y0, x0, ink, NULL); } return; + } + + if (dash != NULL) { + length = dash_length(dash); + if (length == 0) { + return; + } + } + + /* the axis that advances on every step */ + xmajor = dx > dy; + if (xmajor) { + n = dx, d = dy; + major = x0, major_step = xs, major_size = im->xsize; + minor = y0, minor_step = ys, minor_size = im->ysize; } else { - ys = 1; + n = dy, d = dx; + major = y0, major_step = ys, major_size = im->ysize; + minor = x0, minor_step = xs, minor_size = im->xsize; + } + if (n == 0) { + return; } - n = (dx > dy) ? dx : dy; + /* steps whose major coordinate lies inside the image */ + if (major_step > 0) { + first = -major; + last = major_size - 1 - major; + } else { + first = major - (major_size - 1); + last = major; + } + if (first < 0) { + first = 0; + } + if (last > n - 1) { + last = n - 1; + } - if (dx == 0) { - /* vertical */ - if (dash != NULL) { - for (i = 0; i < dy; i++) { - if (should_draw_dash(i, dash_offset, dash)) { - point(im, x0, y0, ink); - } - y0 += ys; - } - *dash_offset += dy; - } else { - for (i = 0; i < dy; i++) { - point(im, x0, y0, ink); - y0 += ys; - } + if (first <= last) { + /* d * first < 2**64, since d <= n < 2**32 and first < n */ + p = (uint64_t)d * (uint64_t)first; + k = (int64_t)(p / (uint64_t)n); + e = 2 * (int64_t)(p % (uint64_t)n) + 2 * d - n; + if (e - 2 * d >= 0) { + /* the rounding of k(first) went up */ + k++; + e -= 2 * n; } - } else if (dx > dy) { - /* bresenham, horizontal slope */ - n = dx; - dy += dy; - e = dy - dx; - dx += dx; - - if (dash != NULL) { - for (i = 0; i < n; i++) { - if (should_draw_dash(i, dash_offset, dash)) { - point(im, x0, y0, ink); - } - if (e >= 0) { - y0 += ys; - e -= dx; + major += major_step * first; + minor += minor_step * k; + + for (i = first; i <= last; i++) { + if (minor >= 0 && minor < minor_size && + (dash == NULL || should_draw_dash((*dash_offset + i) % length, dash))) { + if (xmajor) { + point(im, (int)major, (int)minor, ink); + } else { + point(im, (int)minor, (int)major, ink); } - e += dy; - x0 += xs; } - *dash_offset += n; - } else { - for (i = 0; i < n; i++) { - point(im, x0, y0, ink); - if (e >= 0) { - y0 += ys; - e -= dx; - } - e += dy; - x0 += xs; + if (e >= 0) { + minor += minor_step; + e -= 2 * n; } + e += 2 * d; + major += major_step; } + } - } else { - /* bresenham, vertical slope */ - n = dy; - dx += dx; - e = dx - dy; - dy += dy; - - if (dash != NULL) { - for (i = 0; i < n; i++) { - if (should_draw_dash(i, dash_offset, dash)) { - point(im, x0, y0, ink); - } - if (e >= 0) { - x0 += xs; - e -= dy; - } - e += dx; - y0 += ys; - } - *dash_offset += n; - } else { - for (i = 0; i < n; i++) { - point(im, x0, y0, ink); - if (e >= 0) { - x0 += xs; - e -= dy; - } - e += dx; - y0 += ys; - } - } + if (dash != NULL) { + *dash_offset = (int)((*dash_offset + n) % length); } }