eaterior 1.8.0__tar.gz

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.
eaterior-1.8.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hasan Cagri Gungor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: eaterior
3
+ Version: 1.8.0
4
+ Summary: Validator, migrator and image-detection importer for Eaterior, an open JSON format for restaurant, cafe and bar floor plans
5
+ Author: Hasan Cagri Gungor
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/hasancagrigungor/eaterior
8
+ Project-URL: Documentation, https://github.com/hasancagrigungor/eaterior/blob/main/docs/specification.md
9
+ Project-URL: Repository, https://github.com/hasancagrigungor/eaterior
10
+ Project-URL: Issues, https://github.com/hasancagrigungor/eaterior/issues
11
+ Project-URL: Changelog, https://github.com/hasancagrigungor/eaterior/blob/main/CHANGELOG.md
12
+ Keywords: floor-plan,restaurant,cafe,bar,pos,json-schema,digital-twin,validator
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Topic :: Scientific/Engineering :: Visualization
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: jsonschema>=4.18
29
+ Dynamic: license-file
30
+
31
+ # eaterior
32
+
33
+ Validator, migrator and image-detection importer for **[Eaterior](https://github.com/hasancagrigungor/eaterior)**,
34
+ an open JSON format for restaurant, cafe and bar floor plans: zones, walls, doors, tables, furniture, HVAC equipment and
35
+ sensors, plus live table and device state for a digital twin of the venue.
36
+
37
+ ![Garden Bistro](https://raw.githubusercontent.com/hasancagrigungor/eaterior/main/docs/images/restaurant-illustrated.png)
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install eaterior
43
+ ```
44
+
45
+ The JSON Schemas ship inside the package. The canonical copies, the specification and examples live on
46
+ [GitHub](https://github.com/hasancagrigungor/eaterior).
47
+
48
+ ## Command line
49
+
50
+ ```bash
51
+ eaterior validate plan.json # schema + references + geometry
52
+ eaterior validate plan.json --json # machine-readable issues
53
+ eaterior check-state plan.json table-state.json
54
+ eaterior check-objects plan.json object-state.json
55
+ eaterior check-telemetry plan.json telemetry.json
56
+ eaterior import detection.json plan.json --image drawing.png --name "My cafe"
57
+ eaterior migrate old.json new.json # older Eaterior or legacy CafePlan files
58
+ ```
59
+
60
+ Exit code `0` = valid (warnings allowed), `1` = errors.
61
+
62
+ ## Library
63
+
64
+ ```python
65
+ import json
66
+ from eaterior import validate_plan, check_object_state, detection_to_plan
67
+
68
+ plan = json.load(open("plan.json"))
69
+ report = validate_plan(plan)
70
+ if not report.ok:
71
+ for issue in report.errors:
72
+ print(issue.code, issue.path, issue.message)
73
+ ```
74
+
75
+ | Function | Checks |
76
+ |---|---|
77
+ | `validate_plan(plan)` | JSON Schema, unique ids, references, floor bounds, wall openings, polygon validity, table overlaps … |
78
+ | `check_table_state(plan, state)` | live table status, by plan id or external id |
79
+ | `check_object_state(plan, state)` | active / open / power / level of any object, by plan id or external id |
80
+ | `check_telemetry(plan, reading)` | sensor readings match the sensor's metrics |
81
+ | `detection_to_plan(detection)` | pixel detection of a drawing → plan (snapping, wall attachment, scale from dimensions) |
82
+ | `migrate(doc)` | upgrade older documents |
83
+
84
+ ## Links
85
+
86
+ - [Specification](https://github.com/hasancagrigungor/eaterior/blob/main/docs/specification.md)
87
+ - [Integration with POS, reservations, kitchen, BMS and IoT systems](https://github.com/hasancagrigungor/eaterior/blob/main/docs/integration.md)
88
+ - [Converting drawings](https://github.com/hasancagrigungor/eaterior/blob/main/docs/image-import.md)
89
+ - UI library for web and React Native: [`eaterior` on npm](https://www.npmjs.com/package/eaterior)
90
+
91
+ MIT licensed.
@@ -0,0 +1,61 @@
1
+ # eaterior
2
+
3
+ Validator, migrator and image-detection importer for **[Eaterior](https://github.com/hasancagrigungor/eaterior)**,
4
+ an open JSON format for restaurant, cafe and bar floor plans: zones, walls, doors, tables, furniture, HVAC equipment and
5
+ sensors, plus live table and device state for a digital twin of the venue.
6
+
7
+ ![Garden Bistro](https://raw.githubusercontent.com/hasancagrigungor/eaterior/main/docs/images/restaurant-illustrated.png)
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install eaterior
13
+ ```
14
+
15
+ The JSON Schemas ship inside the package. The canonical copies, the specification and examples live on
16
+ [GitHub](https://github.com/hasancagrigungor/eaterior).
17
+
18
+ ## Command line
19
+
20
+ ```bash
21
+ eaterior validate plan.json # schema + references + geometry
22
+ eaterior validate plan.json --json # machine-readable issues
23
+ eaterior check-state plan.json table-state.json
24
+ eaterior check-objects plan.json object-state.json
25
+ eaterior check-telemetry plan.json telemetry.json
26
+ eaterior import detection.json plan.json --image drawing.png --name "My cafe"
27
+ eaterior migrate old.json new.json # older Eaterior or legacy CafePlan files
28
+ ```
29
+
30
+ Exit code `0` = valid (warnings allowed), `1` = errors.
31
+
32
+ ## Library
33
+
34
+ ```python
35
+ import json
36
+ from eaterior import validate_plan, check_object_state, detection_to_plan
37
+
38
+ plan = json.load(open("plan.json"))
39
+ report = validate_plan(plan)
40
+ if not report.ok:
41
+ for issue in report.errors:
42
+ print(issue.code, issue.path, issue.message)
43
+ ```
44
+
45
+ | Function | Checks |
46
+ |---|---|
47
+ | `validate_plan(plan)` | JSON Schema, unique ids, references, floor bounds, wall openings, polygon validity, table overlaps … |
48
+ | `check_table_state(plan, state)` | live table status, by plan id or external id |
49
+ | `check_object_state(plan, state)` | active / open / power / level of any object, by plan id or external id |
50
+ | `check_telemetry(plan, reading)` | sensor readings match the sensor's metrics |
51
+ | `detection_to_plan(detection)` | pixel detection of a drawing → plan (snapping, wall attachment, scale from dimensions) |
52
+ | `migrate(doc)` | upgrade older documents |
53
+
54
+ ## Links
55
+
56
+ - [Specification](https://github.com/hasancagrigungor/eaterior/blob/main/docs/specification.md)
57
+ - [Integration with POS, reservations, kitchen, BMS and IoT systems](https://github.com/hasancagrigungor/eaterior/blob/main/docs/integration.md)
58
+ - [Converting drawings](https://github.com/hasancagrigungor/eaterior/blob/main/docs/image-import.md)
59
+ - UI library for web and React Native: [`eaterior` on npm](https://www.npmjs.com/package/eaterior)
60
+
61
+ MIT licensed.
@@ -0,0 +1,9 @@
1
+ """Eaterior: an open floor-plan format for restaurants, cafes and bars."""
2
+ from .validate import (Report, Issue, SCHEMA_VERSION, validate_plan, check_table_state,
3
+ check_telemetry, check_detection, check_object_state)
4
+ from .migrate import migrate
5
+ from .importer import detection_to_plan
6
+
7
+ __all__ = ["Report", "Issue", "SCHEMA_VERSION", "validate_plan", "check_table_state", "check_telemetry",
8
+ "check_detection", "check_object_state", "migrate", "detection_to_plan"]
9
+ __version__ = "1.8.0"
@@ -0,0 +1,4 @@
1
+ import sys
2
+ from .cli import main
3
+
4
+ sys.exit(main())
@@ -0,0 +1,93 @@
1
+ """Command line interface: `eaterior <command> ...` or `python -m eaterior ...`."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import validate as v
10
+ from .importer import detection_to_plan
11
+ from .migrate import migrate
12
+
13
+
14
+ def _load(path):
15
+ return json.loads(Path(path).read_text(encoding="utf-8"))
16
+
17
+
18
+ def _write(path, doc):
19
+ Path(path).write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
20
+
21
+
22
+ def _emit(rep: v.Report, as_json: bool) -> int:
23
+ print(json.dumps(rep.as_dict(), ensure_ascii=False, indent=2) if as_json else rep.format())
24
+ return 0 if rep.ok else 1
25
+
26
+
27
+ def main(argv=None) -> int:
28
+ ap = argparse.ArgumentParser(prog="eaterior", description="Eaterior tools")
29
+ sub = ap.add_subparsers(dest="cmd", required=True)
30
+ p = sub.add_parser("validate", help="validate a plan (schema + semantics)")
31
+ p.add_argument("plan"); p.add_argument("--json", action="store_true")
32
+ p = sub.add_parser("check-state", help="validate live table state against a plan")
33
+ p.add_argument("plan"); p.add_argument("state"); p.add_argument("--json", action="store_true")
34
+ p = sub.add_parser("check-telemetry", help="validate a sensor reading against a plan")
35
+ p.add_argument("plan"); p.add_argument("telemetry"); p.add_argument("--json", action="store_true")
36
+ p = sub.add_parser("check-objects", help="validate live component state (active, open, power) against a plan")
37
+ p.add_argument("plan"); p.add_argument("objects"); p.add_argument("--json", action="store_true")
38
+ p = sub.add_parser("migrate", help="upgrade an older or legacy CafePlan 1.x file")
39
+ p.add_argument("src"); p.add_argument("dst")
40
+ p = sub.add_parser("import", help="convert an image detection (pixels) into a plan")
41
+ p.add_argument("detection"); p.add_argument("dst")
42
+ p.add_argument("--image", help="source image; stored as background asset")
43
+ p.add_argument("--plan-id", default="plan_1"); p.add_argument("--name", default="Imported plan")
44
+ p.add_argument("--width", type=float, default=1000.0, help="floor width in units (default 1000)")
45
+ p.add_argument("--source", choices=["ai", "import", "manual"], default="ai")
46
+ p.add_argument("--tool", help="name/version of the detector, recorded in provenance")
47
+ p.add_argument("--locale")
48
+ p.add_argument("--json", action="store_true")
49
+ a = ap.parse_args(argv)
50
+
51
+ if a.cmd == "migrate":
52
+ out, notes = migrate(_load(a.src))
53
+ rep = v.validate_plan(out)
54
+ if not rep.ok:
55
+ print(rep.format()); print("Upgraded plan is invalid; nothing written.")
56
+ return 1
57
+ _write(a.dst, out)
58
+ print("\n".join(notes)); print(f"written: {a.dst}")
59
+ return 0
60
+
61
+ if a.cmd == "import":
62
+ det = _load(a.detection)
63
+ rep = v.check_detection(det)
64
+ if not rep.ok:
65
+ return _emit(rep, a.json)
66
+ plan = detection_to_plan(det, plan_id=a.plan_id, name=a.name, target_width=a.width,
67
+ image_path=a.image, source=a.source, tool=a.tool, locale=a.locale)
68
+ rep = v.validate_plan(plan)
69
+ if rep.ok:
70
+ _write(a.dst, plan)
71
+ code = _emit(rep, a.json)
72
+ if not a.json:
73
+ for n in plan.get("provenance", {}).get("notes", []):
74
+ print(f"note: {n}")
75
+ print(f"written: {a.dst}" if rep.ok else "Imported plan is invalid; nothing written.")
76
+ return code
77
+
78
+ plan = _load(a.plan)
79
+ if a.cmd == "validate":
80
+ return _emit(v.validate_plan(plan), a.json)
81
+ pre = v.validate_plan(plan)
82
+ if not pre.ok:
83
+ print(pre.format()); print("The plan itself is invalid; fix it first.")
84
+ return 1
85
+ if a.cmd == "check-state":
86
+ return _emit(v.check_table_state(plan, _load(a.state)), a.json)
87
+ if a.cmd == "check-objects":
88
+ return _emit(v.check_object_state(plan, _load(a.objects)), a.json)
89
+ return _emit(v.check_telemetry(plan, _load(a.telemetry)), a.json)
90
+
91
+
92
+ if __name__ == "__main__":
93
+ sys.exit(main())
@@ -0,0 +1,285 @@
1
+ """Geometry helpers shared by the validator and the importer.
2
+
3
+ All coordinates are floor units: origin top-left, x to the right, y downwards.
4
+ Positive angles are clockwise on screen. The formulas here are the reference for
5
+ every renderer (see docs/rendering.md).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ Pt = tuple[float, float]
12
+
13
+
14
+ def rotate(pts: list[Pt], deg: float, c: Pt) -> list[Pt]:
15
+ if not deg:
16
+ return list(pts)
17
+ r = math.radians(deg)
18
+ cs, sn = math.cos(r), math.sin(r)
19
+ return [(c[0] + (x - c[0]) * cs - (y - c[1]) * sn,
20
+ c[1] + (x - c[0]) * sn + (y - c[1]) * cs) for x, y in pts]
21
+
22
+
23
+ def bbox(pts):
24
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
25
+ return min(xs), min(ys), max(xs), max(ys)
26
+
27
+
28
+ def bbox_center(pts) -> Pt:
29
+ b = bbox(pts)
30
+ return (b[0] + b[2]) / 2, (b[1] + b[3]) / 2
31
+
32
+
33
+ def path_pivot(commands) -> Pt:
34
+ """Pivot of a path: bbox centre of every coordinate written in the commands."""
35
+ pts = []
36
+ for c in commands:
37
+ for kx, ky in (("x", "y"), ("cx", "cy"), ("c1x", "c1y"), ("c2x", "c2y")):
38
+ if kx in c and ky in c:
39
+ pts.append((c[kx], c[ky]))
40
+ return bbox_center(pts)
41
+
42
+
43
+ def arc_points(p0: Pt, cmd: dict, n: int = 16) -> list[Pt]:
44
+ """SVG endpoint-parameterised elliptical arc to points (excluding p0)."""
45
+ x1, y1 = p0
46
+ x2, y2 = cmd["x"], cmd["y"]
47
+ rx, ry = abs(cmd["rx"]), abs(cmd["ry"])
48
+ if (x1, y1) == (x2, y2) or rx == 0 or ry == 0:
49
+ return [(x2, y2)]
50
+ phi = math.radians(cmd.get("xAxisRotationDeg", 0))
51
+ cp, sp = math.cos(phi), math.sin(phi)
52
+ dx, dy = (x1 - x2) / 2, (y1 - y2) / 2
53
+ x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy
54
+ lam = x1p ** 2 / rx ** 2 + y1p ** 2 / ry ** 2
55
+ if lam > 1:
56
+ rx, ry = rx * math.sqrt(lam), ry * math.sqrt(lam)
57
+ num = rx ** 2 * ry ** 2 - rx ** 2 * y1p ** 2 - ry ** 2 * x1p ** 2
58
+ den = rx ** 2 * y1p ** 2 + ry ** 2 * x1p ** 2
59
+ co = math.sqrt(max(0.0, num / den)) if den else 0.0
60
+ if cmd["largeArc"] == cmd["sweep"]:
61
+ co = -co
62
+ cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx
63
+ cx = cp * cxp - sp * cyp + (x1 + x2) / 2
64
+ cy = sp * cxp + cp * cyp + (y1 + y2) / 2
65
+
66
+ def ang(ux, uy, vx, vy):
67
+ return math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
68
+
69
+ t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
70
+ dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
71
+ if not cmd["sweep"] and dt > 0:
72
+ dt -= 2 * math.pi
73
+ elif cmd["sweep"] and dt < 0:
74
+ dt += 2 * math.pi
75
+ out = []
76
+ for i in range(1, n + 1):
77
+ t = t1 + dt * i / n
78
+ out.append((cx + rx * math.cos(t) * cp - ry * math.sin(t) * sp,
79
+ cy + rx * math.cos(t) * sp + ry * math.sin(t) * cp))
80
+ return out
81
+
82
+
83
+ def shape_points(s: dict) -> list[Pt]:
84
+ """Approximate a shape (rotation applied) as polygon points."""
85
+ k = s["kind"]
86
+ rot = s.get("rotationDeg", 0)
87
+ if k == "rect":
88
+ x, y, w, h = s["x"], s["y"], s["width"], s["height"]
89
+ return rotate([(x, y), (x + w, y), (x + w, y + h), (x, y + h)], rot, (x + w / 2, y + h / 2))
90
+ if k == "ellipse":
91
+ cx, cy, rx, ry = s["cx"], s["cy"], s["rx"], s["ry"]
92
+ pts = [(cx + rx * math.cos(2 * math.pi * i / 32), cy + ry * math.sin(2 * math.pi * i / 32)) for i in range(32)]
93
+ return rotate(pts, rot, (cx, cy))
94
+ if k == "polygon":
95
+ pts = [(p["x"], p["y"]) for p in s["points"]]
96
+ return rotate(pts, rot, bbox_center(pts))
97
+ # path
98
+ pts, cur, start = [], (0.0, 0.0), (0.0, 0.0)
99
+ for c in s["commands"]:
100
+ m = c["cmd"]
101
+ if m == "M":
102
+ cur = start = (c["x"], c["y"]); pts.append(cur)
103
+ elif m == "L":
104
+ cur = (c["x"], c["y"]); pts.append(cur)
105
+ elif m == "Q":
106
+ p0, p1, p2 = cur, (c["cx"], c["cy"]), (c["x"], c["y"])
107
+ for i in range(1, 9):
108
+ t = i / 8
109
+ pts.append(((1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * p1[0] + t * t * p2[0],
110
+ (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * p1[1] + t * t * p2[1]))
111
+ cur = p2
112
+ elif m == "C":
113
+ p0, p1, p2, p3 = cur, (c["c1x"], c["c1y"]), (c["c2x"], c["c2y"]), (c["x"], c["y"])
114
+ for i in range(1, 13):
115
+ t = i / 12
116
+ a, b, cc, d = (1 - t) ** 3, 3 * (1 - t) ** 2 * t, 3 * (1 - t) * t * t, t ** 3
117
+ pts.append((a * p0[0] + b * p1[0] + cc * p2[0] + d * p3[0],
118
+ a * p0[1] + b * p1[1] + cc * p2[1] + d * p3[1]))
119
+ cur = p3
120
+ elif m == "A":
121
+ pts.extend(arc_points(cur, c)); cur = (c["x"], c["y"])
122
+ elif m == "Z":
123
+ cur = start
124
+ if not pts:
125
+ return pts
126
+ return rotate(pts, rot, path_pivot(s["commands"]))
127
+
128
+
129
+ class WallGeom:
130
+ """Straight or curved (bulge) wall. t in [0, 1] runs from a to b."""
131
+
132
+ def __init__(self, w: dict):
133
+ self.a = (w["a"]["x"], w["a"]["y"])
134
+ self.b = (w["b"]["x"], w["b"]["y"])
135
+ self.thickness = w["thickness"]
136
+ self.chord = math.dist(self.a, self.b)
137
+ self.bulge = w.get("bulge", 0) or 0
138
+ self.curved = bool(self.bulge) and self.chord > 0
139
+ if not self.curved:
140
+ self.length = self.chord
141
+ return
142
+ theta = 4 * math.atan(self.bulge) # signed sweep angle
143
+ self.radius = self.chord / (2 * math.sin(abs(theta) / 2))
144
+ self.length = abs(theta) * self.radius
145
+ ux, uy = (self.b[0] - self.a[0]) / self.chord, (self.b[1] - self.a[1]) / self.chord
146
+ nx, ny = -uy, ux # right-hand normal of a->b (y down)
147
+ mx, my = (self.a[0] + self.b[0]) / 2, (self.a[1] + self.b[1]) / 2
148
+ sagitta = abs(self.bulge) * self.chord / 2
149
+ sign = 1 if self.bulge > 0 else -1
150
+ d = self.radius - sagitta
151
+ self.center = (mx - sign * nx * d, my - sign * ny * d)
152
+ self.a0 = math.atan2(self.a[1] - self.center[1], self.a[0] - self.center[0])
153
+ apex = (mx + sign * nx * sagitta, my + sign * ny * sagitta)
154
+ self.sweep = abs(theta)
155
+ mid = self._at_angle(self.a0 + self.sweep / 2)
156
+ if math.dist(mid, apex) > 1e-6 * max(1.0, self.chord):
157
+ self.sweep = -abs(theta)
158
+
159
+ def _at_angle(self, ang):
160
+ return (self.center[0] + self.radius * math.cos(ang), self.center[1] + self.radius * math.sin(ang))
161
+
162
+ def point_at(self, t: float) -> Pt:
163
+ if not self.curved:
164
+ return (self.a[0] + (self.b[0] - self.a[0]) * t, self.a[1] + (self.b[1] - self.a[1]) * t)
165
+ return self._at_angle(self.a0 + self.sweep * t)
166
+
167
+ def tangent_at(self, t: float) -> Pt:
168
+ if not self.curved:
169
+ if self.chord == 0:
170
+ return (1.0, 0.0)
171
+ return ((self.b[0] - self.a[0]) / self.chord, (self.b[1] - self.a[1]) / self.chord)
172
+ ang = self.a0 + self.sweep * t
173
+ s = 1 if self.sweep > 0 else -1
174
+ return (-math.sin(ang) * s, math.cos(ang) * s)
175
+
176
+ def polyline(self, n: int = 16) -> list[Pt]:
177
+ if not self.curved:
178
+ return [self.a, self.b]
179
+ return [self.point_at(i / n) for i in range(n + 1)]
180
+
181
+
182
+ def _orient(p, q, r):
183
+ v = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
184
+ return 0 if abs(v) < 1e-9 else (1 if v > 0 else -1)
185
+
186
+
187
+ def seg_intersect(p1, p2, p3, p4) -> bool:
188
+ o1, o2, o3, o4 = _orient(p1, p2, p3), _orient(p1, p2, p4), _orient(p3, p4, p1), _orient(p3, p4, p2)
189
+ if o1 != o2 and o3 != o4:
190
+ return True
191
+
192
+ def on(p, q, r):
193
+ return (min(p[0], r[0]) - 1e-9 <= q[0] <= max(p[0], r[0]) + 1e-9 and
194
+ min(p[1], r[1]) - 1e-9 <= q[1] <= max(p[1], r[1]) + 1e-9)
195
+ return ((o1 == 0 and on(p1, p3, p2)) or (o2 == 0 and on(p1, p4, p2)) or
196
+ (o3 == 0 and on(p3, p1, p4)) or (o4 == 0 and on(p3, p2, p4)))
197
+
198
+
199
+ def point_seg_dist(p, a, b) -> float:
200
+ dx, dy = b[0] - a[0], b[1] - a[1]
201
+ L2 = dx * dx + dy * dy
202
+ if L2 == 0:
203
+ return math.dist(p, a)
204
+ t = max(0.0, min(1.0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / L2))
205
+ return math.dist(p, (a[0] + t * dx, a[1] + t * dy))
206
+
207
+
208
+ def project_t(p, a, b) -> float:
209
+ dx, dy = b[0] - a[0], b[1] - a[1]
210
+ L2 = dx * dx + dy * dy
211
+ return 0.0 if L2 == 0 else ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / L2
212
+
213
+
214
+ def self_intersects(pts) -> bool:
215
+ n = len(pts)
216
+ for i in range(n):
217
+ a, b = pts[i], pts[(i + 1) % n]
218
+ for j in range(i + 1, n):
219
+ if (j + 1) % n == i or j == (i + 1) % n:
220
+ continue
221
+ if seg_intersect(a, b, pts[j], pts[(j + 1) % n]):
222
+ return True
223
+ return False
224
+
225
+
226
+ def area(pts) -> float:
227
+ n = len(pts)
228
+ return abs(sum(pts[i][0] * pts[(i + 1) % n][1] - pts[(i + 1) % n][0] * pts[i][1] for i in range(n))) / 2
229
+
230
+
231
+ def point_in_poly(p, pts) -> bool:
232
+ x, y, inside = p[0], p[1], False
233
+ for i in range(len(pts)):
234
+ (x1, y1), (x2, y2) = pts[i], pts[i - 1]
235
+ if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:
236
+ inside = not inside
237
+ return inside
238
+
239
+
240
+ def polys_overlap(a, b) -> bool:
241
+ ba, bb = bbox(a), bbox(b)
242
+ if ba[2] <= bb[0] or bb[2] <= ba[0] or ba[3] <= bb[1] or bb[3] <= ba[1]:
243
+ return False
244
+ for i in range(len(a)):
245
+ for j in range(len(b)):
246
+ if seg_intersect(a[i], a[(i + 1) % len(a)], b[j], b[(j + 1) % len(b)]):
247
+ return True
248
+ return point_in_poly(a[0], b) or point_in_poly(b[0], a)
249
+
250
+
251
+ def poly_polyline_dist(poly, line) -> float:
252
+ """Minimum distance between a closed polygon and an open polyline (0 if they touch or overlap)."""
253
+ for i in range(len(line) - 1):
254
+ for j in range(len(poly)):
255
+ if seg_intersect(line[i], line[i + 1], poly[j], poly[(j + 1) % len(poly)]):
256
+ return 0.0
257
+ if any(point_in_poly(p, poly) for p in line):
258
+ return 0.0
259
+ d = math.inf
260
+ for i in range(len(line) - 1):
261
+ for p in poly:
262
+ d = min(d, point_seg_dist(p, line[i], line[i + 1]))
263
+ for p in line:
264
+ for j in range(len(poly)):
265
+ d = min(d, point_seg_dist(p, poly[j], poly[(j + 1) % len(poly)]))
266
+ return d
267
+
268
+
269
+ def convex_hull(pts):
270
+ pts = sorted(set(pts))
271
+ if len(pts) <= 2:
272
+ return pts
273
+
274
+ def cross(o, a, b):
275
+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
276
+ lower, upper = [], []
277
+ for p in pts:
278
+ while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
279
+ lower.pop()
280
+ lower.append(p)
281
+ for p in reversed(pts):
282
+ while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
283
+ upper.pop()
284
+ upper.append(p)
285
+ return lower[:-1] + upper[:-1]