pyvisionect 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyvisionect/__init__.py +120 -0
- pyvisionect/devices/__init__.py +92 -0
- pyvisionect/devices/enums.py +403 -0
- pyvisionect/devices/panels.py +242 -0
- pyvisionect/devices/tclv.py +460 -0
- pyvisionect/imaging/README.md +175 -0
- pyvisionect/imaging/__init__.py +181 -0
- pyvisionect/imaging/checksum.py +114 -0
- pyvisionect/imaging/constants.py +131 -0
- pyvisionect/imaging/data/blue_noise_64.npy +0 -0
- pyvisionect/imaging/decode.py +172 -0
- pyvisionect/imaging/dither.py +357 -0
- pyvisionect/imaging/encoder.py +594 -0
- pyvisionect/imaging/geometry.py +129 -0
- pyvisionect/imaging/grey.py +104 -0
- pyvisionect/imaging/interlace.py +244 -0
- pyvisionect/imaging/pack.py +142 -0
- pyvisionect/imaging/panel.py +339 -0
- pyvisionect/imaging/partial.py +931 -0
- pyvisionect/imaging/rects.py +466 -0
- pyvisionect/io/__init__.py +33 -0
- pyvisionect/io/tcp.py +795 -0
- pyvisionect/io/usb/__init__.py +237 -0
- pyvisionect/io/usb/cli.py +278 -0
- pyvisionect/io/usb/commands.py +781 -0
- pyvisionect/io/usb/console.py +730 -0
- pyvisionect/io/usb/device.py +914 -0
- pyvisionect/io/usb/discovery.py +260 -0
- pyvisionect/io/usb/encryption.py +262 -0
- pyvisionect/io/usb/errors.py +175 -0
- pyvisionect/io/usb/fake.py +292 -0
- pyvisionect/io/usb/parsers.py +1464 -0
- pyvisionect/io/usb/provisioning.py +502 -0
- pyvisionect/packets/__init__.py +135 -0
- pyvisionect/packets/control.py +95 -0
- pyvisionect/packets/file.py +325 -0
- pyvisionect/packets/image.py +234 -0
- pyvisionect/packets/misc.py +202 -0
- pyvisionect/packets/param.py +284 -0
- pyvisionect/packets/status.py +518 -0
- pyvisionect/packets/stored.py +217 -0
- pyvisionect/py.typed +0 -0
- pyvisionect/session/__init__.py +100 -0
- pyvisionect/session/connection.py +1043 -0
- pyvisionect/session/device.py +587 -0
- pyvisionect/session/events.py +196 -0
- pyvisionect/session/filetransfer.py +251 -0
- pyvisionect/session/pending.py +425 -0
- pyvisionect/wire/__init__.py +91 -0
- pyvisionect/wire/blocks.py +350 -0
- pyvisionect/wire/checksum.py +115 -0
- pyvisionect/wire/errors.py +176 -0
- pyvisionect/wire/framing.py +334 -0
- pyvisionect-0.1.0.dist-info/METADATA +1030 -0
- pyvisionect-0.1.0.dist-info/RECORD +58 -0
- pyvisionect-0.1.0.dist-info/WHEEL +4 -0
- pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
- pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
"""Rectangle bookkeeping: change detection, region merging, alignment.
|
|
2
|
+
|
|
3
|
+
Spec §2.4 (the 16-bit quantum), §4.1 (``MergeRegions``) and §4.2
|
|
4
|
+
(``ChangesAutodetect``). All functions are pure.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from dataclasses import dataclass, replace
|
|
11
|
+
from typing import Iterable, Sequence
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from .constants import (ALIGN_QUANTUM, MAX_REGIONS_PER_DISPLAY,
|
|
16
|
+
MERGE_THRESHOLD_PERCENT, MERGE_THRESHOLD_STEP_PERCENT)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Rect",
|
|
20
|
+
"detect_changes",
|
|
21
|
+
"unite_overlapping_regions",
|
|
22
|
+
"join_contours",
|
|
23
|
+
"apply_region_count_limit",
|
|
24
|
+
"limit_regions",
|
|
25
|
+
"align_to_quantum",
|
|
26
|
+
"is_aligned",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Rect:
|
|
32
|
+
"""An axis-aligned rectangle, ``(x, y, width, height)``, integer pixels."""
|
|
33
|
+
|
|
34
|
+
x: int
|
|
35
|
+
y: int
|
|
36
|
+
width: int
|
|
37
|
+
height: int
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
if self.width < 0 or self.height < 0:
|
|
41
|
+
raise ValueError(f"negative rectangle extent: {self!r}")
|
|
42
|
+
|
|
43
|
+
# -- geometry ----------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def far_x(self) -> int:
|
|
47
|
+
return self.x + self.width
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def far_y(self) -> int:
|
|
51
|
+
return self.y + self.height
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def area(self) -> int:
|
|
55
|
+
return self.width * self.height
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def center(self) -> tuple[float, float]:
|
|
59
|
+
"""``join.go:221-228`` uses the centre for pairwise distances."""
|
|
60
|
+
return (self.x + 0.5 * self.width, self.y + 0.5 * self.height)
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def is_empty(self) -> bool:
|
|
64
|
+
return self.width == 0 or self.height == 0
|
|
65
|
+
|
|
66
|
+
def overlaps(self, other: "Rect") -> bool:
|
|
67
|
+
"""Strict AABB intersection -- ``RenderRect.rectsOverlap``, ``join.go:31-48``.
|
|
68
|
+
|
|
69
|
+
Touching edges do **not** count, and an empty rectangle never overlaps.
|
|
70
|
+
"""
|
|
71
|
+
if self.is_empty or other.is_empty:
|
|
72
|
+
return False
|
|
73
|
+
return (self.x < other.far_x and other.x < self.far_x
|
|
74
|
+
and self.y < other.far_y and other.y < self.far_y)
|
|
75
|
+
|
|
76
|
+
def bounding_box(self, other: "Rect") -> "Rect":
|
|
77
|
+
"""``commonRect`` -- ``join.go:185-192``. No overlap test."""
|
|
78
|
+
x = min(self.x, other.x)
|
|
79
|
+
y = min(self.y, other.y)
|
|
80
|
+
return Rect(x, y, max(self.far_x, other.far_x) - x,
|
|
81
|
+
max(self.far_y, other.far_y) - y)
|
|
82
|
+
|
|
83
|
+
def union(self, other: "Rect") -> "Rect | None":
|
|
84
|
+
"""``RenderRect.Union`` -- ``join.go:77-99``. **Requires** overlap."""
|
|
85
|
+
if not self.overlaps(other):
|
|
86
|
+
return None
|
|
87
|
+
return self.bounding_box(other)
|
|
88
|
+
|
|
89
|
+
def intersection(self, other: "Rect") -> "Rect | None":
|
|
90
|
+
x = max(self.x, other.x)
|
|
91
|
+
y = max(self.y, other.y)
|
|
92
|
+
fx = min(self.far_x, other.far_x)
|
|
93
|
+
fy = min(self.far_y, other.far_y)
|
|
94
|
+
if fx <= x or fy <= y:
|
|
95
|
+
return None
|
|
96
|
+
return Rect(x, y, fx - x, fy - y)
|
|
97
|
+
|
|
98
|
+
def translated(self, dx: int, dy: int) -> "Rect":
|
|
99
|
+
return replace(self, x=self.x + dx, y=self.y + dy)
|
|
100
|
+
|
|
101
|
+
def as_slice(self) -> tuple[slice, slice]:
|
|
102
|
+
"""``(rows, cols)`` numpy slices for a canvas-space crop."""
|
|
103
|
+
return (slice(self.y, self.far_y), slice(self.x, self.far_x))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# --------------------------------------------------------------------------
|
|
107
|
+
# change detection -- spec §4.2
|
|
108
|
+
# --------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
def _connected_components(mask: np.ndarray) -> list[Rect]:
|
|
111
|
+
"""Bounding boxes of 8-connected ``True`` components, largest area first.
|
|
112
|
+
|
|
113
|
+
The vendor runs ``cvAbsDiff`` -> ``cvThreshold`` -> ``cvFindContours``
|
|
114
|
+
(``CV_RETR_EXTERNAL``) -> ``cvBoundingRect``, sorted by contour area
|
|
115
|
+
descending (``changes.cpp``, spec §4.2). The bounding boxes of 8-connected
|
|
116
|
+
components are the same set of rectangles as the bounding boxes of external
|
|
117
|
+
contours.
|
|
118
|
+
|
|
119
|
+
.. note::
|
|
120
|
+
We sort by **bounding-box** area, not by contour area as OpenCV does.
|
|
121
|
+
The ordering only affects which pair ``joinContours`` happens to merge
|
|
122
|
+
first when the region count is already over the limit, never
|
|
123
|
+
correctness. Implemented with run-length rows + union-find so that
|
|
124
|
+
``imaging/`` needs no scipy or OpenCV.
|
|
125
|
+
"""
|
|
126
|
+
h, w = mask.shape
|
|
127
|
+
# One vectorised pass to find which rows have anything at all. Change
|
|
128
|
+
# detection runs over the whole canvas on every frame, and on a typical
|
|
129
|
+
# partial update almost every row is empty, so asking numpy once beats
|
|
130
|
+
# 2560 per-row ``.any()`` calls.
|
|
131
|
+
nonempty = mask.any(axis=1)
|
|
132
|
+
parent: list[int] = []
|
|
133
|
+
|
|
134
|
+
def find(a: int) -> int:
|
|
135
|
+
while parent[a] != a:
|
|
136
|
+
parent[a] = parent[parent[a]]
|
|
137
|
+
a = parent[a]
|
|
138
|
+
return a
|
|
139
|
+
|
|
140
|
+
def union(a: int, b: int) -> None:
|
|
141
|
+
ra, rb = find(a), find(b)
|
|
142
|
+
if ra != rb:
|
|
143
|
+
parent[max(ra, rb)] = min(ra, rb)
|
|
144
|
+
|
|
145
|
+
runs_by_row: list[list[tuple[int, int, int]]] = [] # (x0, x1_exclusive, label)
|
|
146
|
+
for y in range(h):
|
|
147
|
+
if not nonempty[y]:
|
|
148
|
+
runs_by_row.append([])
|
|
149
|
+
continue
|
|
150
|
+
row = mask[y]
|
|
151
|
+
# run starts/ends via edge differences
|
|
152
|
+
d = np.flatnonzero(np.diff(np.concatenate(([0], row.view(np.uint8), [0]))))
|
|
153
|
+
starts, ends = d[0::2], d[1::2]
|
|
154
|
+
runs: list[tuple[int, int, int]] = []
|
|
155
|
+
prev = runs_by_row[y - 1] if y else []
|
|
156
|
+
for x0, x1 in zip(starts.tolist(), ends.tolist()):
|
|
157
|
+
label = len(parent)
|
|
158
|
+
parent.append(label)
|
|
159
|
+
# 8-connectivity: the previous row's runs touching [x0-1, x1]
|
|
160
|
+
for px0, px1, plabel in prev:
|
|
161
|
+
if px0 <= x1 and x0 <= px1:
|
|
162
|
+
union(label, plabel)
|
|
163
|
+
runs.append((x0, x1, label))
|
|
164
|
+
runs_by_row.append(runs)
|
|
165
|
+
|
|
166
|
+
boxes: dict[int, list[int]] = {}
|
|
167
|
+
for y, runs in enumerate(runs_by_row):
|
|
168
|
+
for x0, x1, label in runs:
|
|
169
|
+
root = find(label)
|
|
170
|
+
b = boxes.get(root)
|
|
171
|
+
if b is None:
|
|
172
|
+
boxes[root] = [x0, y, x1, y + 1]
|
|
173
|
+
else:
|
|
174
|
+
b[0] = min(b[0], x0)
|
|
175
|
+
b[2] = max(b[2], x1)
|
|
176
|
+
b[3] = y + 1
|
|
177
|
+
rects = [Rect(x0, y0, x1 - x0, y1 - y0) for x0, y0, x1, y1 in boxes.values()]
|
|
178
|
+
rects.sort(key=lambda r: (-r.area, r.y, r.x))
|
|
179
|
+
return rects
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def detect_changes(new_grey: np.ndarray, old_grey: np.ndarray,
|
|
183
|
+
threshold: float = 0.0) -> list[Rect]:
|
|
184
|
+
"""``changes.DetectorCV.DetectChanges`` -- spec §4.2.
|
|
185
|
+
|
|
186
|
+
``threshold`` is a **per-pixel absolute grey difference**. The vendor's
|
|
187
|
+
default is ``0``, and ``cvThreshold(diff, 0, 255, CV_THRESH_BINARY)`` marks
|
|
188
|
+
a pixel changed when ``diff > 0`` -- i.e. *any* non-zero difference. So
|
|
189
|
+
the comparison is strictly greater-than, not greater-or-equal.
|
|
190
|
+
|
|
191
|
+
The two-pass structure of ``get_changes`` is reproduced:
|
|
192
|
+
components -> ``uniteOverlappingRegions(areaCriteria=false)`` -> (if more
|
|
193
|
+
than 100 regions) ``joinContours`` at 5 %/10 % of the canvas diagonal ->
|
|
194
|
+
``uniteOverlappingRegions(areaCriteria=true)``.
|
|
195
|
+
|
|
196
|
+
.. note::
|
|
197
|
+
The vendor chunks the >100 case into 100-rect groups before the final
|
|
198
|
+
join (``changes.cpp``, marked **[INFERRED]** in the spec). We run the
|
|
199
|
+
single global ``joinContours`` pass only; the chunking is a performance
|
|
200
|
+
detail whose bookkeeping the report could not pin down.
|
|
201
|
+
"""
|
|
202
|
+
a = np.asarray(new_grey, dtype=np.uint8)
|
|
203
|
+
b = np.asarray(old_grey, dtype=np.uint8)
|
|
204
|
+
if a.shape != b.shape:
|
|
205
|
+
raise ValueError(f"change detection needs equal shapes, got {a.shape} vs {b.shape}")
|
|
206
|
+
if threshold <= 0:
|
|
207
|
+
# ``diff > 0`` is just inequality, and skipping the two int16
|
|
208
|
+
# promotions saves two 3.7 MB temporaries on a full canvas. This is
|
|
209
|
+
# the vendor's default and by far the common case.
|
|
210
|
+
mask = a != b
|
|
211
|
+
else:
|
|
212
|
+
diff = np.abs(a.astype(np.int16) - b.astype(np.int16))
|
|
213
|
+
mask = diff > threshold
|
|
214
|
+
if not mask.any():
|
|
215
|
+
return []
|
|
216
|
+
rects = _connected_components(mask)
|
|
217
|
+
rects = unite_overlapping_regions(rects, area_criteria=False)
|
|
218
|
+
if len(rects) > 100:
|
|
219
|
+
h, w = a.shape
|
|
220
|
+
diag = math.hypot(w, h)
|
|
221
|
+
rects = join_contours(100,
|
|
222
|
+
diag * MERGE_THRESHOLD_PERCENT / 100.0,
|
|
223
|
+
diag * MERGE_THRESHOLD_STEP_PERCENT / 100.0,
|
|
224
|
+
rects)
|
|
225
|
+
return unite_overlapping_regions(rects, area_criteria=True)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# --------------------------------------------------------------------------
|
|
229
|
+
# region merging -- spec §4.1
|
|
230
|
+
# --------------------------------------------------------------------------
|
|
231
|
+
|
|
232
|
+
def unite_overlapping_regions(rects: Sequence[Rect],
|
|
233
|
+
area_criteria: bool = True) -> list[Rect]:
|
|
234
|
+
"""``uniteOverlappingRegions`` -- ``join.go:127-182``. Iterates to a fixpoint.
|
|
235
|
+
|
|
236
|
+
:param area_criteria: when true, a union is rejected if its area exceeds
|
|
237
|
+
the sum of the two input areas (``join.go:150-155``), i.e. merging must
|
|
238
|
+
not make the repaint bigger.
|
|
239
|
+
"""
|
|
240
|
+
items: list[Rect] = list(rects)
|
|
241
|
+
changed = True
|
|
242
|
+
while changed:
|
|
243
|
+
changed = False
|
|
244
|
+
i = 0
|
|
245
|
+
while i < len(items):
|
|
246
|
+
j = i + 1
|
|
247
|
+
while j < len(items):
|
|
248
|
+
r1, r2 = items[i], items[j]
|
|
249
|
+
if not r1.overlaps(r2):
|
|
250
|
+
j += 1
|
|
251
|
+
continue
|
|
252
|
+
u = r1.union(r2)
|
|
253
|
+
if u is None or u.is_empty:
|
|
254
|
+
j += 1
|
|
255
|
+
continue
|
|
256
|
+
if area_criteria and u.area > r1.area + r2.area:
|
|
257
|
+
j += 1
|
|
258
|
+
continue
|
|
259
|
+
items[i] = u
|
|
260
|
+
del items[j]
|
|
261
|
+
changed = True
|
|
262
|
+
i += 1
|
|
263
|
+
return items
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def join_contours(max_regions: int, dist_threshold: float, dist_threshold_step: float,
|
|
267
|
+
rects: Sequence[Rect]) -> list[Rect]:
|
|
268
|
+
"""``joinContures`` -- ``join.go:195-350``.
|
|
269
|
+
|
|
270
|
+
Sorts all pairwise centre distances ascending, then repeatedly groups
|
|
271
|
+
rectangles whose centres are closer than ``threshold`` into bounding boxes,
|
|
272
|
+
raising ``threshold`` by ``dist_threshold_step`` until the region count
|
|
273
|
+
drops to ``max_regions`` (or the step is zero, which makes it a single
|
|
274
|
+
pass).
|
|
275
|
+
"""
|
|
276
|
+
inp = list(rects)
|
|
277
|
+
if max_regions == 0:
|
|
278
|
+
raise ValueError("region count upper limit 'maxRegions' should greater than 0")
|
|
279
|
+
if dist_threshold_step < 0:
|
|
280
|
+
raise ValueError("join threshold step 'distThresholdStep' should not be a negative number")
|
|
281
|
+
if dist_threshold <= 0:
|
|
282
|
+
raise ValueError("join threshold 'distThreshold' should be greater than 0")
|
|
283
|
+
if len(inp) <= max_regions:
|
|
284
|
+
return inp
|
|
285
|
+
|
|
286
|
+
distances: list[tuple[float, int, int]] = []
|
|
287
|
+
for i in range(len(inp) - 1):
|
|
288
|
+
c1 = inp[i].center
|
|
289
|
+
for j in range(i + 1, len(inp)):
|
|
290
|
+
c2 = inp[j].center
|
|
291
|
+
distances.append((math.hypot(c1[0] - c2[0], c1[1] - c2[1]), i, j))
|
|
292
|
+
distances.sort(key=lambda t: (t[0], t[1], t[2]))
|
|
293
|
+
|
|
294
|
+
threshold = dist_threshold
|
|
295
|
+
out: list[Rect] = inp
|
|
296
|
+
while True:
|
|
297
|
+
used: list[int] = [-1] * len(inp)
|
|
298
|
+
regions: list[Rect] = []
|
|
299
|
+
for d, i, j in distances:
|
|
300
|
+
if threshold <= d:
|
|
301
|
+
continue
|
|
302
|
+
a, b = used[i], used[j]
|
|
303
|
+
if a == -1 and b == -1:
|
|
304
|
+
regions.append(inp[i].bounding_box(inp[j]))
|
|
305
|
+
used[i] = used[j] = len(regions) - 1
|
|
306
|
+
elif a == -1:
|
|
307
|
+
regions[b] = regions[b].bounding_box(inp[i])
|
|
308
|
+
used[i] = b
|
|
309
|
+
elif b == -1:
|
|
310
|
+
regions[a] = regions[a].bounding_box(inp[j])
|
|
311
|
+
used[j] = a
|
|
312
|
+
elif a != b:
|
|
313
|
+
regions[a] = regions[a].bounding_box(regions[b])
|
|
314
|
+
for k, v in enumerate(used):
|
|
315
|
+
if v == b:
|
|
316
|
+
used[k] = a
|
|
317
|
+
regions.extend(inp[k] for k, v in enumerate(used) if v == -1)
|
|
318
|
+
out = unite_overlapping_regions(regions, area_criteria=True)
|
|
319
|
+
if dist_threshold_step <= 0:
|
|
320
|
+
break
|
|
321
|
+
threshold += dist_threshold_step
|
|
322
|
+
if len(out) <= max_regions:
|
|
323
|
+
break
|
|
324
|
+
return out
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def apply_region_count_limit(max_regions: int, dist_threshold: float,
|
|
328
|
+
dist_threshold_step: float,
|
|
329
|
+
rects: Sequence[Rect]) -> list[Rect]:
|
|
330
|
+
"""``applyRegionCountLimit`` -- ``join.go:351-356``."""
|
|
331
|
+
if len(rects) <= max_regions:
|
|
332
|
+
return list(rects)
|
|
333
|
+
return join_contours(max_regions, dist_threshold, dist_threshold_step, rects)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def limit_regions(rects: Sequence[Rect], display_width: int, display_height: int,
|
|
337
|
+
merge: bool = True,
|
|
338
|
+
threshold_percent: float = MERGE_THRESHOLD_PERCENT,
|
|
339
|
+
threshold_step_percent: float = MERGE_THRESHOLD_STEP_PERCENT,
|
|
340
|
+
max_regions: int = MAX_REGIONS_PER_DISPLAY) -> list[Rect] | None:
|
|
341
|
+
"""``displayRects.update``'s region-count branch -- ``image-state.go:221-247``.
|
|
342
|
+
|
|
343
|
+
Returns the merged rectangle list, or ``None`` to mean "the caller must
|
|
344
|
+
force a full-screen update" (which is what ``forceFullScreenUnlocked``
|
|
345
|
+
does at ``image-state.go:241`` when merging is disabled and the count is
|
|
346
|
+
over the limit).
|
|
347
|
+
|
|
348
|
+
``threshold_percent`` / ``threshold_step_percent`` are **percentages of the
|
|
349
|
+
display diagonal** (``image-state.go:234-235``); for a 1440x640 display the
|
|
350
|
+
diagonal is 1575.81 px, so the vendor defaults of 5 % / 10 % become
|
|
351
|
+
78.8 px / 157.6 px. ``NewMergeParameters`` clamps both to ``[0, 100]`` and
|
|
352
|
+
substitutes 5/10 when the step is non-positive (``image-state.go:116-126``).
|
|
353
|
+
"""
|
|
354
|
+
out = list(rects)
|
|
355
|
+
if len(out) > max_regions:
|
|
356
|
+
if not merge:
|
|
357
|
+
return None
|
|
358
|
+
step = threshold_step_percent
|
|
359
|
+
start = threshold_percent
|
|
360
|
+
if step <= 0:
|
|
361
|
+
if start <= 0:
|
|
362
|
+
start = MERGE_THRESHOLD_PERCENT
|
|
363
|
+
step = MERGE_THRESHOLD_STEP_PERCENT
|
|
364
|
+
start = min(100.0, max(0.0, start))
|
|
365
|
+
step = min(100.0, max(0.0, step))
|
|
366
|
+
diag = math.hypot(display_width, display_height)
|
|
367
|
+
out = apply_region_count_limit(max_regions, start * diag / 100.0,
|
|
368
|
+
step * diag / 100.0, out)
|
|
369
|
+
return unite_overlapping_regions(out, area_criteria=True)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
# --------------------------------------------------------------------------
|
|
373
|
+
# 16-bit quantum alignment -- spec §2.4
|
|
374
|
+
# --------------------------------------------------------------------------
|
|
375
|
+
|
|
376
|
+
def is_aligned(rect: Rect, encoding: int) -> bool:
|
|
377
|
+
"""``isDividableTo16BitQuants`` -- ``sixteen-bit-limitation.go:30-44``.
|
|
378
|
+
|
|
379
|
+
The constraint is on ``width * height`` (total sub-pixels), because the
|
|
380
|
+
packer runs linearly over the whole rectangle with no row padding. A total
|
|
381
|
+
smaller than the quantum is never acceptable (``:38-39``).
|
|
382
|
+
"""
|
|
383
|
+
try:
|
|
384
|
+
q = ALIGN_QUANTUM[int(encoding)]
|
|
385
|
+
except KeyError:
|
|
386
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)") from None
|
|
387
|
+
total = rect.width * rect.height
|
|
388
|
+
if total < q:
|
|
389
|
+
return False
|
|
390
|
+
return total % q == 0
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def align_to_quantum(rect: Rect, encoding: int, border: Rect) -> Rect:
|
|
394
|
+
"""Grow ``rect`` outward until ``width * height`` divides the 16-bit quantum.
|
|
395
|
+
|
|
396
|
+
Vendor equivalent: ``sizeRectFor16BitQuantEncoding`` /
|
|
397
|
+
``driverSizeRectFor16BitQuantEncodingBothDirections``
|
|
398
|
+
(``sixteen-bit-limitation.go:74/81``), reached through the driver op
|
|
399
|
+
``"rectangle-encode"`` from ``render.SizeRectsForEncoding``
|
|
400
|
+
(``image-state.go:1760``).
|
|
401
|
+
|
|
402
|
+
.. note:: **[INFERRED]** growth order.
|
|
403
|
+
The report records *that* the vendor grows the rectangle outward using
|
|
404
|
+
``nextCommonMultiple``, clamped to the display/canvas border, but not the
|
|
405
|
+
exact order in which it tries width/height or right/left. We grow the
|
|
406
|
+
**width** to the next multiple of the quantum -- which makes
|
|
407
|
+
``width * height`` divisible for any height, so it is always sufficient
|
|
408
|
+
-- preferring to grow right (towards ``border.far_x``) and falling back
|
|
409
|
+
to growing left. If the width cannot reach a multiple of the quantum
|
|
410
|
+
inside the border we grow the height the same way, and if that also
|
|
411
|
+
fails we raise, as the vendor does with ``"rectangle is outside
|
|
412
|
+
boundaries"``.
|
|
413
|
+
|
|
414
|
+
A rectangle that is already aligned is returned unchanged, matching the
|
|
415
|
+
vendor's ``isDividableTo16BitQuants`` early exit.
|
|
416
|
+
"""
|
|
417
|
+
try:
|
|
418
|
+
q = ALIGN_QUANTUM[int(encoding)]
|
|
419
|
+
except KeyError:
|
|
420
|
+
raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)") from None
|
|
421
|
+
if border.width <= 0 or border.height <= 0:
|
|
422
|
+
raise ValueError("bad display/image borders")
|
|
423
|
+
r = rect.intersection(border)
|
|
424
|
+
if r is None:
|
|
425
|
+
raise ValueError(f"rectangle {rect!r} is outside boundaries {border!r}")
|
|
426
|
+
if is_aligned(r, encoding):
|
|
427
|
+
return r
|
|
428
|
+
|
|
429
|
+
def grow(lo: int, extent: int, b_lo: int, b_hi: int, target: int) -> tuple[int, int] | None:
|
|
430
|
+
"""Grow ``[lo, lo+extent)`` to ``target`` inside ``[b_lo, b_hi)``."""
|
|
431
|
+
need = target - extent
|
|
432
|
+
if need <= 0 or target > b_hi - b_lo:
|
|
433
|
+
return None
|
|
434
|
+
right = min(need, b_hi - (lo + extent))
|
|
435
|
+
lo -= need - right
|
|
436
|
+
if lo < b_lo:
|
|
437
|
+
return None
|
|
438
|
+
return lo, target
|
|
439
|
+
|
|
440
|
+
want_w = ((r.width + q - 1) // q) * q
|
|
441
|
+
if want_w == r.width:
|
|
442
|
+
want_w = r.width + q
|
|
443
|
+
grown = grow(r.x, r.width, border.x, border.far_x, want_w)
|
|
444
|
+
if grown is not None:
|
|
445
|
+
return Rect(grown[0], r.y, grown[1], r.height)
|
|
446
|
+
|
|
447
|
+
want_h = ((r.height + q - 1) // q) * q
|
|
448
|
+
if want_h == r.height:
|
|
449
|
+
want_h = r.height + q
|
|
450
|
+
grown = grow(r.y, r.height, border.y, border.far_y, want_h)
|
|
451
|
+
if grown is not None:
|
|
452
|
+
return Rect(r.x, grown[0], r.width, grown[1])
|
|
453
|
+
|
|
454
|
+
raise ValueError(
|
|
455
|
+
f"rectangle {rect!r} cannot be aligned to the {q}-sub-pixel quantum "
|
|
456
|
+
f"inside borders {border!r}"
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def align_all(rects: Iterable[Rect], encoding: int, border: Rect) -> list[Rect]:
|
|
461
|
+
"""``SizeRectsForEncoding`` -- ``image-state.go:1760``.
|
|
462
|
+
|
|
463
|
+
Aligns every rectangle, then re-unites overlaps that the growth created.
|
|
464
|
+
"""
|
|
465
|
+
out = [align_to_quantum(r, encoding, border) for r in rects]
|
|
466
|
+
return unite_overlapping_regions(out, area_criteria=False)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""The **only** layer that touches I/O.
|
|
2
|
+
|
|
3
|
+
* :mod:`pyvisionect.io.tcp` -- an asyncio listener on port 11113.
|
|
4
|
+
* :mod:`pyvisionect.io.usb` -- a package covering the device's ASCII serial
|
|
5
|
+
console: transport, typed command surface, provisioning flows, discovery.
|
|
6
|
+
|
|
7
|
+
Both are thin. Everything interesting is in the sans-io layers below them.
|
|
8
|
+
|
|
9
|
+
``pyserial`` is an optional dependency (``pip install 'pyvisionect[usb]'``), so
|
|
10
|
+
:mod:`~pyvisionect.io.usb` is imported lazily and this package's ``__init__``
|
|
11
|
+
exposes only the TCP side eagerly.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
from .tcp import DEFAULT_PORT, VisionectServer
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
21
|
+
from .usb import SerialConsole, Sign
|
|
22
|
+
|
|
23
|
+
__all__ = ["DEFAULT_PORT", "VisionectServer", "SerialConsole", "Sign"]
|
|
24
|
+
|
|
25
|
+
_LAZY = {"SerialConsole", "Sign"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def __getattr__(name: str) -> Any:
|
|
29
|
+
if name in _LAZY:
|
|
30
|
+
from . import usb
|
|
31
|
+
|
|
32
|
+
return getattr(usb, name)
|
|
33
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|