-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdisplayio_cartesian.py
693 lines (568 loc) · 22.8 KB
/
displayio_cartesian.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
# SPDX-FileCopyrightText: 2021 Jose David M.
#
# SPDX-License-Identifier: MIT
"""
`displayio_cartesian`
================================================================================
A cartesian plane widget for displaying graphical information.
* Author(s): Jose David M.
Implementation Notes
--------------------
**Hardware:**
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
# pylint: disable=too-many-lines, too-many-instance-attributes, too-many-arguments
# pylint: disable=too-many-locals, too-many-statements
import displayio
import terminalio
from adafruit_display_text import bitmap_label
import vectorio
from adafruit_displayio_layout.widgets.widget import Widget
from adafruit_displayio_layout.widgets import rectangle_helper
try:
import bitmaptools
except ImportError:
pass
try:
from typing import Tuple
except ImportError:
pass
class Cartesian(Widget):
"""A cartesian widget. The origin is set using ``x`` and ``y``.
:param int x: x position of the plane origin
:param int y: y position of the plane origin
:param int background_color: background color to use defaults to black (0x000000)
:param int width: requested width, in pixels.
:param int height: requested height, in pixels.
:param (int, int) xrange: X axes range. Defaults to (0, 100)
:param (int, int) yrange: Y axes range. Defaults to (0, 100)
:param int axes_color: axes lines color defaults to white (0xFFFFFF)
:param int axes_stroke: axes lines thickness in pixels defaults to 2
:param int major_tick_stroke: tick lines thickness in pixels defaults to 1
:param int major_tick_length: tick lines length in pixels defaults to 5
:param terminalio.FONT tick_label_font: tick label text font
:param int font_color: font color. Defaults to white (0xFFFFFF)
:param int pointer_radius: pointer radius in pixels defaults to 1
:param int pointer_color: pointer color. Defaults to white (0xFFFFFF)
:param bool subticks: inclusion of subticks in the plot area. Default to False
:param int nudge_x: movement in pixels in the x direction to move the origin.
Defaults to 0
:param int nudge_y: movement in pixels in the y direction to move the origin.
Defaults to 0
:param bool verbose: print debugging information in some internal functions. Default to False
**Quickstart: Importing and using Cartesian**
Here is one way of importing the `Cartesian` class so you can use it as
the name ``Plane``:
.. code-block:: python
from displayio_cartesian import Cartesian as Plane
Now you can create a plane at pixel position x=20, y=30 using:
.. code-block:: python
my_plane=Plane(x=20, y=30) # instance the plane at x=20, y=30
Once you setup your display, you can now add ``my_plane`` to your display using:
.. code-block:: python
display.show(my_plane) # add the group to the display
If you want to have multiple display elements, you can create a group and then
append the plane and the other elements to the group. Then, you can add the full
group to the display as in this example:
.. code-block:: python
my_plane= Plane(20, 30) # instance the plane at x=20, y=30
my_group = displayio.Group() # make a group
my_group.append(my_plane) # Add my_plane to the group
#
# Append other display elements to the group
#
display.show(my_group) # add the group to the display
**Summary: Cartesian Features and input variables**
The `Cartesian` widget has some options for controlling its position, visible appearance,
and scale through a collection of input variables:
- **position**: ``x``, ``y``, ``anchor_point``, ``anchored_position`` and
``nudge_x``, ``nudge_y``. Nudge parameters are used to account for the float and int
conversions required to display different ranges and values. Conversion are required
as displays work in integers and not floats
- **size**: ``width`` and ``height``
- **color**: ``axes_color``, ``font_color``, ``tick_color``, ``pointer_color``
- **background color**: ``background_color``
- **linewidths**: ``axes_stroke`` and ``major_tick_stroke``
- **range**: ``xrange`` and ``yrange`` This is the range in absolute units.
For example, when using (20-90), the X axis will start at 20 finishing at 90.
However the height of the graph is given by the height parameter. The scale
is handled internal to provide a 1:1 experience when you update the graph.
.. figure:: cartesian.gif
:scale: 100 %
:figwidth: 50%
:align: center
:alt: Diagram of the cartesian widget with the pointer in motion.
This is a diagram of a cartesian widget with the pointer moving in the
plot area.
.. figure:: cartesian_zones.png
:scale: 100 %
:figwidth: 50%
:align: center
:alt: Diagram of the cartesian widget zones.
This is a diagram of a cartesian widget showing the different zones.
.. figure:: cartesian_explanation.png
:scale: 100 %
:figwidth: 50%
:align: center
:alt: Diagram of the cartesian widget localisation.
This is a diagram of a cartesian widget showing localisation scheme.
"""
def __init__(
self,
background_color: int = 0x000000,
xrange: Tuple[int, int] = (0, 100),
yrange: Tuple[int, int] = (0, 100),
axes_color: int = 0xFFFFFF,
axes_stroke: int = 1,
tick_color: int = 0xFFFFFF,
major_tick_stroke: int = 1,
major_tick_length: int = 5,
tick_label_font=terminalio.FONT,
font_color: int = 0xFFFFFF,
pointer_radius: int = 1,
pointer_color: int = 0xFFFFFF,
subticks: bool = False,
nudge_x: int = 0,
nudge_y: int = 0,
verbose: bool = False,
fill_area: bool = False,
**kwargs,
) -> None:
super().__init__(**kwargs)
self._verbose = verbose
self._background_color = background_color
self._axes_line_color = axes_color
self._axes_line_thickness = axes_stroke
self._tick_color = tick_color
if major_tick_stroke not in range(1, 5):
print("tick thickness must be 1-4 pixels. Defaulting to 1")
self._tick_line_thickness = 1
else:
self._tick_line_thickness = major_tick_stroke
if major_tick_length not in range(1, 9):
print("tick length must be 1-10 pixels. Defaulting to 5")
self._tick_line_height = 5
else:
self._tick_line_height = major_tick_length
self._pointer_radius = pointer_radius
self._pointer_color = pointer_color
self._font = tick_label_font
self._font_color = font_color
self._font_width = self._get_font_height(self._font, 1)[0]
self._font_height = self._get_font_height(self._font, 1)[1]
self._xrange = xrange
self._normx = (self._xrange[1] - self._xrange[0]) / 100
self._valuex = self.width / 100
self._factorx = 100 / (self._xrange[1] - self._xrange[0])
self._yrange = yrange
self._normy = (self._yrange[1] - self._yrange[0]) / 100
self._valuey = self.height / 100
self._factory = 100 / (self._yrange[1] - self._yrange[0])
self._tick_bitmap = displayio.Bitmap(
self._tick_line_thickness, self._tick_line_height, 3
)
self._tick_bitmap.fill(1)
self._subticks = subticks
axesx_height = (
2
+ self._axes_line_thickness
+ self._font_height
+ self._tick_line_height // 2
)
self._axesx_bitmap = displayio.Bitmap(self.width, axesx_height, 4)
self._axesx_bitmap.fill(0)
self._axesy_width = (
2
+ self._axes_line_thickness
+ self._font_width
+ self._tick_line_height // 2
)
self._axesy_bitmap = displayio.Bitmap(self._axesy_width, self.height, 4)
self._axesy_bitmap.fill(0)
self._plot_bitmap = displayio.Bitmap(self.width, self.height, 5)
self.clear_plot_lines()
self._screen_palette = displayio.Palette(6)
self._screen_palette.make_transparent(0)
self._screen_palette[1] = self._tick_color
self._screen_palette[2] = self._axes_line_color
self._screen_palette[3] = 0x990099
self._screen_palette[4] = 0xFFFFFF
self._screen_palette[5] = self._background_color
self._corner_bitmap = displayio.Bitmap(10, 10, 5)
rectangle_helper(
0,
0,
self._axes_line_thickness,
self._axes_line_thickness,
self._corner_bitmap,
2,
self._screen_palette,
)
self._corner_tilegrid = displayio.TileGrid(
self._corner_bitmap,
pixel_shader=self._screen_palette,
x=-self._axes_line_thickness,
y=self.height,
)
self._axesx_tilegrid = displayio.TileGrid(
self._axesx_bitmap,
pixel_shader=self._screen_palette,
x=0,
y=self.height,
)
self._axesy_tilegrid = displayio.TileGrid(
self._axesy_bitmap,
pixel_shader=self._screen_palette,
x=-self._axesy_width,
y=0,
)
self._screen_tilegrid = displayio.TileGrid(
self._plot_bitmap,
pixel_shader=self._screen_palette,
x=0,
y=0,
)
self._nudge_x = nudge_x
self._nudge_y = nudge_y
self._draw_axes()
self._draw_ticks()
self.append(self._axesx_tilegrid)
self.append(self._axesy_tilegrid)
self.append(self._screen_tilegrid)
self.append(self._corner_tilegrid)
self._pointer = None
self._circle_palette = None
self.plot_line_point = None
self._fill_area = fill_area
@staticmethod
def _get_font_height(font, scale: int) -> Tuple[int, int]:
if hasattr(font, "get_bounding_box"):
font_height = int(scale * font.get_bounding_box()[1])
font_width = int(scale * font.get_bounding_box()[0])
elif hasattr(font, "ascent"):
font_height = int(scale * font.ascent + font.ascent)
font_width = 12
else:
font_height = 12
font_width = 12
return font_width, font_height
def _draw_axes(self) -> None:
# Draw x axes line
rectangle_helper(
0,
0,
self._axes_line_thickness,
self.width,
self._axesx_bitmap,
2,
self._screen_palette,
True,
)
# Draw y axes line
rectangle_helper(
self._axesy_width - self._axes_line_thickness,
0,
self.height,
self._axes_line_thickness,
self._axesy_bitmap,
2,
self._screen_palette,
True,
)
def _draw_ticks(self) -> None:
# ticks definition
ticks = [10, 30, 50, 70, 90]
subticks = [20, 40, 60, 80, 100]
# X axes ticks
for i in range(10, 100, 10):
text_tick = str(round(self._xrange[0]) + round(i * self._normx))
text_dist = int(self._valuex * i)
if i in ticks:
shift_label_x = len(text_tick) * self._font_width
tick_text = bitmap_label.Label(
self._font,
color=self._font_color,
text=text_tick,
x=text_dist - (shift_label_x // 2),
y=self.height
+ self._axes_line_thickness
+ self._tick_line_height
+ self._font_height // 2
+ 1,
)
self.append(tick_text)
rectangle_helper(
text_dist,
self._axes_line_thickness,
self._tick_line_height,
self._tick_line_thickness,
self._axesx_bitmap,
1,
self._screen_palette,
True,
)
if self._subticks:
if i in subticks:
# calc subtick_line_height; force min lineheigt to 1.
subtick_line_height = max(1, self._tick_line_height // 2)
rectangle_helper(
text_dist,
self._axes_line_thickness,
subtick_line_height,
1,
self._axesx_bitmap,
1,
self._screen_palette,
True,
)
# Y axes ticks
for i in range(10, 100, 10):
text_tick = str(round(self._yrange[0]) + round(i * self._normy))
text_dist = int(self._valuey * i)
if i in ticks:
shift_label_x = len(text_tick) * self._font_width
tick_text = bitmap_label.Label(
self._font,
color=self._font_color,
text=text_tick,
x=-shift_label_x
- self._axes_line_thickness
- self._tick_line_height
- 2,
y=0 + self.height - text_dist,
)
self.append(tick_text)
rectangle_helper(
self._axesy_width
- self._axes_line_thickness
- self._tick_line_height
- 1,
text_dist,
self._tick_line_thickness,
self._tick_line_height,
self._axesy_bitmap,
1,
self._screen_palette,
True,
)
if self._subticks:
if i in subticks:
rectangle_helper(
self._axesy_width
- self._axes_line_thickness
- self._tick_line_height // 2
- 1,
text_dist,
1,
self._tick_line_height // 2,
self._axesy_bitmap,
1,
self._screen_palette,
True,
)
def _draw_pointers(self, x: int, y: int) -> None:
self._circle_palette = displayio.Palette(1)
self._circle_palette[0] = self._pointer_color
self._pointer = vectorio.Circle(
radius=self._pointer_radius, x=x, y=y, pixel_shader=self._circle_palette
)
self.append(self._pointer)
def _calc_local_xy(self, x: int, y: int) -> Tuple[int, int]:
local_x = (
int((x - self._xrange[0]) * self._factorx * self._valuex) + self._nudge_x
)
# details on `+ (self.height - 1)` :
# the bitmap is set to self.width & self.height
# but we are only allowed to draw to pixels 0..height-1 and 0..width-1
local_y = (
int((self._yrange[0] - y) * self._factory * self._valuey)
+ (self.height - 1)
+ self._nudge_y
)
return (local_x, local_y)
def _check_local_x_in_range(self, local_x):
return 0 <= local_x < self.width
def _check_local_y_in_range(self, local_y):
return 0 <= local_y < self.height
def _check_local_xy_in_range(self, local_x, local_y):
return self._check_local_x_in_range(local_x) and self._check_local_y_in_range(
local_y
)
def _check_x_in_range(self, x):
return self._xrange[0] <= x <= self._xrange[1]
def _check_y_in_range(self, y):
return self._yrange[0] <= y <= self._yrange[1]
def _check_xy_in_range(self, x, y):
return self._check_x_in_range(x) and self._check_y_in_range(y)
def _add_point(self, x: int, y: int) -> None:
"""_add_point function
helper function to add a point to the graph in the plane
:param int x: ``x`` coordinate in the local plane
:param int y: ``y`` coordinate in the local plane
:return: None
"""
local_x, local_y = self._calc_local_xy(x, y)
if self._verbose:
print("")
print(
"xy: ({: >4}, {: >4}) "
"_xrange: ({: >4}, {: >4}) "
"_yrange: ({: >4}, {: >4}) "
"".format(
x,
y,
self._xrange[0],
self._xrange[1],
self._yrange[0],
self._yrange[1],
)
)
print(
"local_*: ({: >4}, {: >4}) "
" width: ({: >4}, {: >4}) "
" height: ({: >4}, {: >4}) "
"".format(
local_x,
local_y,
0,
self.width,
0,
self.height,
)
)
if self._check_xy_in_range(x, y):
if self._check_local_xy_in_range(local_x, local_y):
if self.plot_line_point is None:
self.plot_line_point = []
self.plot_line_point.append((local_x, local_y))
else:
# for better error messages we check in detail what failed...
# this should never happen:
# we already checked the range of the input values.
# but in case our calculation is wrong we handle this case to..
if not self._check_local_x_in_range(local_x):
raise ValueError(
"local_x out of range: "
"local_x:{: >4}; _xrange({: >4}, {: >4})"
"".format(
local_x,
0,
self.width,
)
)
if not self._check_local_y_in_range(local_y):
raise ValueError(
"local_y out of range: "
"local_y:{: >4}; _yrange({: >4}, {: >4})"
"".format(
local_y,
0,
self.height,
)
)
else:
# for better error messages we check in detail what failed...
if not self._check_x_in_range(x):
raise ValueError(
"x out of range: "
"x:{: >4}; xrange({: >4}, {: >4})"
"".format(
x,
self._xrange[0],
self._xrange[1],
)
)
if not self._check_y_in_range(y):
raise ValueError(
"y out of range: "
"y:{: >4}; yrange({: >4}, {: >4})"
"".format(
y,
self._yrange[0],
self._yrange[1],
)
)
def update_pointer(self, x: int, y: int) -> None:
"""updater_pointer function
helper function to update pointer in the plane
:param int x: ``x`` coordinate in the local plane
:param int y: ``y`` coordinate in the local plane
:return: None
"""
self._add_point(x, y)
if not self._pointer:
self._draw_pointers(
self.plot_line_point[-1][0],
self.plot_line_point[-1][1],
)
else:
self._pointer.x = self.plot_line_point[-1][0]
self._pointer.y = self.plot_line_point[-1][1]
@property
def fill_area(self) -> bool:
"""Whether the area under the graph (integral) should be shaded"""
return self._fill_area
@fill_area.setter
def fill_area(self, setting: bool) -> None:
self._fill_area = setting
def add_plot_line(self, x: int, y: int) -> None:
"""add_plot_line function.
add line to the plane.
multiple calls create a line-plot graph.
:param int x: ``x`` coordinate in the local plane
:param int y: ``y`` coordinate in the local plane
:return: None
"""
self._add_point(x, y)
if len(self.plot_line_point) > 1:
bitmaptools.draw_line(
self._plot_bitmap,
self.plot_line_point[-2][0],
self.plot_line_point[-2][1],
self.plot_line_point[-1][0],
self.plot_line_point[-1][1],
1,
)
# Plot area under graph
if self._fill_area:
delta_x = self.plot_line_point[-2][0] - self.plot_line_point[-1][0]
delta_y = self.plot_line_point[-2][1] - self.plot_line_point[-1][1]
delta_y_product = (
self.plot_line_point[-1][1] * self.plot_line_point[-2][1]
)
if delta_x == 0:
return
slope = delta_y / delta_x
if delta_y_product < 0:
intercept = self.plot_line_point[-1][1]
zero_point_x = (-1 * intercept) / slope
self._draw_area_under(self.plot_line_point[-2], (zero_point_x, 0))
self._draw_area_under((zero_point_x, 0), self.plot_line_point[-1])
else:
self._draw_area_under(
self.plot_line_point[-2], self.plot_line_point[-1]
)
def _draw_area_under(
self, xy0: Tuple[float, float], xy1: Tuple[float, float]
) -> None:
_, plot_y_zero = self._calc_local_xy(0, 0)
delta_x = self.plot_line_point[-2][0] - self.plot_line_point[-1][0]
delta_y = self.plot_line_point[-2][1] - self.plot_line_point[-1][1]
slope = delta_y / delta_x
for pixel_x in range(xy0[0], xy1[0] + 1):
if pixel_x != xy1[0]:
pixel_y = round(slope * (pixel_x - xy1[0]) + xy1[1])
bitmaptools.draw_line(
self._plot_bitmap, pixel_x, pixel_y, pixel_x, plot_y_zero, 1
)
def clear_plot_lines(self, palette_index: int = 5) -> None:
"""clear_plot_lines function.
clear all added lines
(clear line-plot graph)
:param int palette_index: color palett index. Defaults to 5
:return: None
"""
self.plot_line_point = None
self._plot_bitmap.fill(palette_index)