]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - vectorio/_vectorshape.py
Merge pull request #149 from FoamyGuy/tuple_int_fix_pr
[hackapet/Adafruit_Blinka_Displayio.git] / vectorio / _vectorshape.py
1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4
5 """
6 `vectorio._vectorshape`
7 ================================================================================
8
9 vectorio for Blinka
10
11 **Software and Dependencies:**
12
13 * Adafruit Blinka:
14   https://github.com/adafruit/Adafruit_Blinka/releases
15
16 * Author(s): Melissa LeBlanc-Williams
17
18 """
19
20 import struct
21 from typing import Union, Tuple
22 from circuitpython_typing import WriteableBuffer
23 from displayio._colorconverter import ColorConverter
24 from displayio._colorspace import Colorspace
25 from displayio._palette import Palette
26 from displayio._area import Area
27 from displayio._structs import null_transform, InputPixelStruct, OutputPixelStruct
28
29 __version__ = "0.0.0+auto.0"
30 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
31
32
33 class _VectorShape:
34     def __init__(
35         self,
36         pixel_shader: Union[ColorConverter, Palette],
37         x: int,
38         y: int,
39     ):
40         self._x = x
41         self._y = y
42         self._pixel_shader = pixel_shader
43         self._hidden = False
44         self._current_area_dirty = True
45         self._current_area = Area(0, 0, 0, 0)
46         self._ephemeral_dirty_area = Area(0, 0, 0, 0)
47         self._absolute_transform = null_transform
48         self._get_screen_area(self._current_area)
49
50     @property
51     def x(self) -> int:
52         """X position of the center point of the circle in the parent."""
53         return self._x
54
55     @x.setter
56     def x(self, value: int) -> None:
57         if self._x == value:
58             return
59         self._x = value
60         self._shape_set_dirty()
61
62     @property
63     def y(self) -> int:
64         """Y position of the center point of the circle in the parent."""
65         return self._y
66
67     @y.setter
68     def y(self, value: int) -> None:
69         if self._y == value:
70             return
71         self._y = value
72         self._shape_set_dirty()
73
74     @property
75     def hidden(self) -> bool:
76         """Hide the circle or not."""
77         return self._hidden
78
79     @hidden.setter
80     def hidden(self, value: bool) -> None:
81         self._hidden = value
82         self._shape_set_dirty()
83
84     @property
85     def location(self) -> Tuple[int, int]:
86         """(X,Y) position of the center point of the circle in the parent."""
87         return (self._x, self._y)
88
89     @location.setter
90     def location(self, value: Tuple[int, int]) -> None:
91         if len(value) != 2:
92             raise ValueError("location must be a list or tuple with exactly 2 integers")
93         x = value[0]
94         y = value[1]
95         dirty = False
96         if self._x != x:
97             self._x = x
98             dirty = True
99         if self._y != y:
100             self._y = y
101             dirty = True
102         if dirty:
103             self._shape_set_dirty()
104
105     @property
106     def pixel_shader(self) -> Union[ColorConverter, Palette]:
107         """The pixel shader of the circle."""
108         return self._pixel_shader
109
110     @pixel_shader.setter
111     def pixel_shader(self, value: Union[ColorConverter, Palette]) -> None:
112         self._pixel_shader = value
113
114     def _get_area(self, _out_area: Area) -> Area:
115         raise NotImplementedError("Subclass must implement _get_area")
116
117     def _get_pixel(self, _x: int, _y: int) -> int:
118         raise NotImplementedError("Subclass must implement _get_pixel")
119
120     def _shape_set_dirty(self) -> None:
121         current_area = Area()
122         self._get_screen_area(current_area)
123         moved = current_area != self._current_area
124         if moved:
125             self._current_area.union(
126                 self._ephemeral_dirty_area, self._ephemeral_dirty_area
127             )
128             # Dirty area tracks the shape's footprint between draws.  It's reset on refresh finish.
129             current_area.copy_into(self._current_area)
130         self._current_area_dirty = True
131
132     def _get_dirty_area(self, out_area: Area) -> Area:
133         out_area.x1 = out_area.x2
134         self._ephemeral_dirty_area.union(self._current_area, out_area)
135         return True  # For now just always redraw.
136
137     def _get_screen_area(self, out_area) -> Area:
138         self._get_area(out_area)
139         if self._absolute_transform.transpose_xy:
140             x = self._absolute_transform.x + self._absolute_transform.dx * self._y
141             y = self._absolute_transform.y + self._absolute_transform.dy * self._x
142             if self._absolute_transform.dx < 1:
143                 out_area.y1 = out_area.y1 * -1 + 1
144                 out_area.y2 = out_area.y2 * -1 + 1
145             if self._absolute_transform.dy < 1:
146                 out_area.x1 = out_area.x1 * -1 + 1
147                 out_area.x2 = out_area.x2 * -1 + 1
148             self._area_transpose(out_area)
149         else:
150             x = self._absolute_transform.x + self._absolute_transform.dx * self._x
151             y = self._absolute_transform.y + self._absolute_transform.dy * self._y
152             if self._absolute_transform.dx < 1:
153                 out_area.x1 = out_area.x1 * -1 + 1
154                 out_area.x2 = out_area.x2 * -1 + 1
155             if self._absolute_transform.dy < 1:
156                 out_area.y1 = out_area.y1 * -1 + 1
157                 out_area.y2 = out_area.y2 * -1 + 1
158         out_area.canon()
159         out_area.shift(x, y)
160
161     @staticmethod
162     def _area_transpose(to_transpose: Area) -> Area:
163         to_transpose.x1, to_transpose.y1 = to_transpose.y1, to_transpose.x1
164         to_transpose.x2, to_transpose.y2 = to_transpose.y2, to_transpose.x2
165
166     def _screen_to_shape_coordinates(self, x: int, y: int) -> Tuple[int, int]:
167         """Get the target pixel based on the shape's coordinate space"""
168         if self._absolute_transform.transpose_xy:
169             out_shape_x = (
170                 y - self._absolute_transform.y - self._absolute_transform.dy * self._x
171             )
172             out_shape_y = (
173                 x - self._absolute_transform.x - self._absolute_transform.dx * self._y
174             )
175
176             if self._absolute_transform.dx < 1:
177                 out_shape_x *= -1
178             if self._absolute_transform.dy < 1:
179                 out_shape_y *= -1
180         else:
181             out_shape_x = (
182                 x - self._absolute_transform.x - self._absolute_transform.dx * self._x
183             )
184             out_shape_y = (
185                 y - self._absolute_transform.y - self._absolute_transform.dy * self._y
186             )
187
188             if self._absolute_transform.dx < 1:
189                 out_shape_x *= -1
190             if self._absolute_transform.dy < 1:
191                 out_shape_y *= -1
192
193             # It's mirrored via dx. Maybe we need to add support for also separately mirroring?
194             # if self.absolute_transform.mirror_x:
195             #    pixel_to_get_x = (
196             #        (shape_area.x2 - shape_area.x1)
197             #        - (pixel_to_get_x - shape_area.x1)
198             #        + shape_area.x1
199             #        - 1
200             #    )
201             # if self.absolute_transform.mirror_y:
202             #    pixel_to_get_y = (
203             #        (shape_area.y2 - shape_area.y1)
204             #        - (pixel_to_get_y - shape_area.y1)
205             #        + +shape_area.y1
206             #        - 1
207             #    )
208
209         return out_shape_x, out_shape_y
210
211     def _shape_contains(self, x: int, y: int) -> bool:
212         shape_x, shape_y = self._screen_to_shape_coordinates(x, y)
213         return self._get_pixel(shape_x, shape_y) != 0
214
215     def _fill_area(
216         self,
217         colorspace: Colorspace,
218         area: Area,
219         mask: WriteableBuffer,
220         buffer: WriteableBuffer,
221     ) -> bool:
222         # pylint: disable=too-many-locals,too-many-branches,too-many-statements
223         if self._hidden:
224             return False
225
226         overlap = Area()
227         if not area.compute_overlap(self._current_area, overlap):
228             return False
229
230         full_coverage = area == overlap
231         pixels_per_byte = 8 // colorspace.depth
232         linestride_px = area.width()
233         line_dirty_offset_px = (overlap.y1 - area.y1) * linestride_px
234         column_dirty_offset_px = overlap.x1 - area.x1
235
236         input_pixel = InputPixelStruct()
237         output_pixel = OutputPixelStruct()
238
239         shape_area = Area()
240         self._get_area(shape_area)
241
242         mask_start_px = line_dirty_offset_px
243
244         for input_pixel.y in range(overlap.y1, overlap.y2):
245             mask_start_px += column_dirty_offset_px
246             for input_pixel.x in range(overlap.x1, overlap.x2):
247                 # Check the mask first to see if the pixel has already been set.
248                 pixel_index = mask_start_px + (input_pixel.x - overlap.x1)
249                 mask_doubleword = mask[pixel_index // 32]
250                 mask_bit = pixel_index % 32
251                 if (mask_doubleword & (1 << mask_bit)) != 0:
252                     continue
253                 output_pixel.pixel = 0
254
255                 # Cast input screen coordinates to shape coordinates to pick the pixel to draw
256                 pixel_to_get_x, pixel_to_get_y = self._screen_to_shape_coordinates(
257                     input_pixel.x, input_pixel.y
258                 )
259                 input_pixel.pixel = self._get_pixel(pixel_to_get_x, pixel_to_get_y)
260
261                 # vectorio shapes use 0 to mean "area is not covered."
262                 # We can skip all the rest of the work for this pixel
263                 # if it's not currently covered by the shape.
264                 if input_pixel.pixel == 0:
265                     full_coverage = False
266                 else:
267                     # Pixel is not transparent. Let's pull the pixel value index down
268                     # to 0-base for more error-resistant palettes.
269                     input_pixel.pixel -= 1
270                     output_pixel.opaque = True
271                     if self._pixel_shader is None:
272                         output_pixel.pixel = input_pixel.pixel
273                     elif isinstance(self._pixel_shader, Palette):
274                         self._pixel_shader._get_color(  # pylint: disable=protected-access
275                             colorspace, input_pixel, output_pixel
276                         )
277                     elif isinstance(self._pixel_shader, ColorConverter):
278                         self._pixel_shader._convert(  # pylint: disable=protected-access
279                             colorspace, input_pixel, output_pixel
280                         )
281
282                     if not output_pixel.opaque:
283                         full_coverage = False
284
285                     mask[pixel_index // 32] |= 1 << (pixel_index % 32)
286                     if colorspace.depth == 16:
287                         struct.pack_into(
288                             "H",
289                             buffer.cast("B"),
290                             pixel_index * 2,
291                             output_pixel.pixel,
292                         )
293                     elif colorspace.depth == 32:
294                         struct.pack_into(
295                             "I",
296                             buffer.cast("B"),
297                             pixel_index * 4,
298                             output_pixel.pixel,
299                         )
300                     elif colorspace.depth == 8:
301                         buffer.cast("B")[pixel_index] = output_pixel.pixel & 0xFF
302                     elif colorspace.depth < 8:
303                         # Reorder the offsets to pack multiple rows into
304                         # a byte (meaning they share a column).
305                         if not colorspace.pixels_in_byte_share_row:
306                             row = pixel_index // linestride_px
307                             col = pixel_index % linestride_px
308                             # Dividing by pixels_per_byte does truncated division
309                             # even if we multiply it back out
310                             pixel_index = (
311                                 col * pixels_per_byte
312                                 + (row // pixels_per_byte)
313                                 * pixels_per_byte
314                                 * linestride_px
315                                 + (row % pixels_per_byte)
316                             )
317                         shift = (pixel_index % pixels_per_byte) * colorspace.depth
318                         if colorspace.reverse_pixels_in_byte:
319                             # Reverse the shift by subtracting it from the leftmost shift
320                             shift = (pixels_per_byte - 1) * colorspace.depth - shift
321                         buffer.cast("B")[pixel_index // pixels_per_byte] |= (
322                             output_pixel.pixel << shift
323                         )
324             mask_start_px += linestride_px - column_dirty_offset_px
325
326         return full_coverage
327
328     def _finish_refresh(self) -> None:
329         if self._ephemeral_dirty_area.empty() and not self._current_area_dirty:
330             return
331         # Reset dirty area to nothing
332         self._ephemeral_dirty_area.x1 = self._ephemeral_dirty_area.x2
333         self._current_area_dirty = False
334
335         if isinstance(self._pixel_shader, (Palette, ColorConverter)):
336             self._pixel_shader._finish_refresh()  # pylint: disable=protected-access
337
338     def _get_refresh_areas(self, areas: list[Area]) -> None:
339         if self._current_area_dirty or (
340             isinstance(self._pixel_shader, (Palette, ColorConverter))
341             and self._pixel_shader._needs_refresh  # pylint: disable=protected-access
342         ):
343             if not self._ephemeral_dirty_area.empty():
344                 # Both are dirty, check if we should combine the areas or draw separately
345                 # Draws as few pixels as possible both when animations move short distances
346                 # and large distances. The display core implementation currently doesn't
347                 # combine areas to reduce redrawing of masked areas. If it does, this could
348                 # be simplified to just return the 2 possibly overlapping areas.
349                 area_swap = Area()
350                 self._ephemeral_dirty_area.compute_overlap(
351                     self._current_area, area_swap
352                 )
353                 overlap_size = area_swap.size()
354                 self._ephemeral_dirty_area.union(self._current_area, area_swap)
355                 union_size = area_swap.size()
356                 current_size = self._current_area.size()
357                 dirty_size = self._ephemeral_dirty_area.size()
358
359                 if union_size - dirty_size - current_size + overlap_size <= min(
360                     dirty_size, current_size
361                 ):
362                     # The excluded / non-overlapping area from the disjoint dirty and current
363                     # areas is smaller than the smallest area we need to draw. Redrawing the
364                     # overlapping area would cost more than just drawing the union disjoint
365                     # area once.
366                     area_swap.copy_into(self._ephemeral_dirty_area)
367                 else:
368                     # The excluded area between the 2 dirty areas is larger than the smallest
369                     # dirty area. It would be more costly to combine these areas than possibly
370                     # redraw some overlap.
371                     areas.append(self._current_area)
372                 areas.append(self._ephemeral_dirty_area)
373             else:
374                 areas.append(self._current_area)
375         elif not self._ephemeral_dirty_area.empty():
376             areas.append(self._ephemeral_dirty_area)
377
378     def _update_transform(self, group_transform) -> None:
379         self._absolute_transform = (
380             null_transform if group_transform is None else group_transform
381         )
382         self._shape_set_dirty()