@7365admin1/layer-common 4.21.4-staging.347 → 4.21.4-staging.349

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.
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Floor plan to 3D layout, in the browser.
3
+ *
4
+ * This is a deliberate copy of the same logic in `@7365admin1/core`, for the
5
+ * same reason `robot-display.ts` is: core is a backend package and a browser
6
+ * cannot import it. The wall extraction has to run where the floor plan image
7
+ * is — the vendor signs its map URLs for about an hour, so the picture is
8
+ * fetched into a canvas at the moment of display and never stored, and the
9
+ * pixels only exist client-side.
10
+ *
11
+ * The two copies must agree, and the agreement is held by the same tests on
12
+ * both sides.
13
+ *
14
+ * ## Why there is no 3D library here
15
+ *
16
+ * The scene is extruded boxes standing on flat floors. A projection and a
17
+ * back-to-front draw order render that correctly in a few hundred lines, and
18
+ * `layer-common` is consumed by eleven web apps — a 3D engine is a large thing
19
+ * to put in all of them for a shape this simple.
20
+ *
21
+ * ponytail: painter's algorithm with a fixed camera. No lighting model, no
22
+ * textures, no orbit. If any of those matter later, swap Three.js in behind
23
+ * `levelSolids` / `projectPoint` — the geometry above them does not change.
24
+ */
25
+
26
+ /** `traffic_editor`'s defaults, matched so our layout and RMF's agree. */
27
+ export const WALL_HEIGHT_M = 2.5;
28
+ export const WALL_THICKNESS_M = 0.1;
29
+ export const DEFAULT_SCALE_M_PER_PX = 0.05;
30
+
31
+ export type TMapVertex = { x: number; y: number; name?: string };
32
+ export type TMapWall = { start: number; end: number; heightM?: number; thicknessM?: number };
33
+
34
+ export type TPlanLevel = {
35
+ name: string;
36
+ elevationM: number;
37
+ scaleMPerPx: number;
38
+ originXM: number;
39
+ originYM: number;
40
+ vertices: TMapVertex[];
41
+ walls: TMapWall[];
42
+ };
43
+
44
+ export type TWallSolid = {
45
+ centre: { x: number; y: number; z: number };
46
+ lengthM: number;
47
+ thicknessM: number;
48
+ heightM: number;
49
+ yaw: number;
50
+ };
51
+
52
+ /* ------------------------------------------------- image to occupancy grid */
53
+
54
+ export type TOccupancyGrid = { data: Uint8Array; width: number; height: number };
55
+
56
+ /**
57
+ * Turn canvas RGBA into one luminance value per pixel.
58
+ *
59
+ * A fully transparent pixel is treated as FREE space, not dark. Map PNGs are
60
+ * commonly transparent outside the surveyed area, and reading alpha 0 as black
61
+ * would wrap the whole plan in a wall.
62
+ */
63
+ export function gridFromImageData(
64
+ rgba: ArrayLike<number>,
65
+ width: number,
66
+ height: number,
67
+ ): TOccupancyGrid {
68
+ const data = new Uint8Array(width * height);
69
+ for (let i = 0, p = 0; p < width * height; i += 4, p++) {
70
+ const alpha = Number(rgba[i + 3]);
71
+ if (alpha === 0) {
72
+ data[p] = 255;
73
+ continue;
74
+ }
75
+ // Rec. 601 luma — close enough for "is this pixel dark", and cheap.
76
+ data[p] =
77
+ (0.299 * Number(rgba[i]) + 0.587 * Number(rgba[i + 1]) + 0.114 * Number(rgba[i + 2])) | 0;
78
+ }
79
+ return { data, width, height };
80
+ }
81
+
82
+ /**
83
+ * Trace walls out of a floor plan, so nobody has to draw them.
84
+ *
85
+ * Horizontal runs first, then vertical runs from what those did not cover, so a
86
+ * long wall is one segment rather than one per pixel. Corners are de-duplicated
87
+ * so the result stays editable afterwards.
88
+ */
89
+ export function wallsFromOccupancyGrid(
90
+ grid: TOccupancyGrid,
91
+ options?: { threshold?: number; minRunPx?: number },
92
+ ): { vertices: TMapVertex[]; walls: TMapWall[] } {
93
+ const threshold = options?.threshold ?? 100;
94
+ const minRun = Math.max(2, options?.minRunPx ?? 6);
95
+ const { data, width, height } = grid;
96
+
97
+ if (!width || !height || !data || data.length < width * height) {
98
+ return { vertices: [], walls: [] };
99
+ }
100
+
101
+ const occupied = (x: number, y: number) => Number(data[y * width + x]) <= threshold;
102
+ const consumed = new Uint8Array(width * height);
103
+ const vertices: TMapVertex[] = [];
104
+ const walls: TMapWall[] = [];
105
+ const index = new Map<string, number>();
106
+
107
+ const vertexAt = (x: number, y: number) => {
108
+ const key = `${x}:${y}`;
109
+ const found = index.get(key);
110
+ if (found !== undefined) return found;
111
+ vertices.push({ x, y });
112
+ index.set(key, vertices.length - 1);
113
+ return vertices.length - 1;
114
+ };
115
+
116
+ for (let y = 0; y < height; y++) {
117
+ let run = 0;
118
+ for (let x = 0; x <= width; x++) {
119
+ if (x < width && occupied(x, y)) {
120
+ run++;
121
+ continue;
122
+ }
123
+ if (run >= minRun) {
124
+ const startX = x - run;
125
+ walls.push({ start: vertexAt(startX, y), end: vertexAt(x - 1, y) });
126
+ for (let i = startX; i < x; i++) consumed[y * width + i] = 1;
127
+ }
128
+ run = 0;
129
+ }
130
+ }
131
+
132
+ for (let x = 0; x < width; x++) {
133
+ let run = 0;
134
+ for (let y = 0; y <= height; y++) {
135
+ if (y < height && occupied(x, y) && !consumed[y * width + x]) {
136
+ run++;
137
+ continue;
138
+ }
139
+ if (run >= minRun) {
140
+ walls.push({ start: vertexAt(x, y - run), end: vertexAt(x, y - 1) });
141
+ }
142
+ run = 0;
143
+ }
144
+ }
145
+
146
+ return { vertices, walls };
147
+ }
148
+
149
+ /* ------------------------------------------------------------- geometry */
150
+
151
+ export function levelScale(level: TPlanLevel): number {
152
+ return level.scaleMPerPx > 0 ? level.scaleMPerPx : DEFAULT_SCALE_M_PER_PX;
153
+ }
154
+
155
+ /**
156
+ * A drawing pixel in site metres.
157
+ *
158
+ * The vertical flip is the occupancy-grid convention: image origin top-left,
159
+ * map origin bottom-left. Without it the building renders mirrored, which reads
160
+ * as "the robot is in the wrong room" rather than as a transform bug.
161
+ */
162
+ export function levelPixelToMetres(
163
+ level: TPlanLevel,
164
+ px: number,
165
+ py: number,
166
+ imageHeightPx: number,
167
+ ): { x: number; y: number } {
168
+ const scale = levelScale(level);
169
+ return {
170
+ x: level.originXM + px * scale,
171
+ y: level.originYM + (imageHeightPx - py) * scale,
172
+ };
173
+ }
174
+
175
+ /** Extrude a level's walls into boxes a renderer can place. */
176
+ export function levelSolids(level: TPlanLevel, imageHeightPx: number): TWallSolid[] {
177
+ const solids: TWallSolid[] = [];
178
+ for (const wall of level.walls ?? []) {
179
+ const a = level.vertices[wall.start];
180
+ const b = level.vertices[wall.end];
181
+ if (!a || !b) continue;
182
+
183
+ const pa = levelPixelToMetres(level, a.x, a.y, imageHeightPx);
184
+ const pb = levelPixelToMetres(level, b.x, b.y, imageHeightPx);
185
+ const lengthM = Math.hypot(pb.x - pa.x, pb.y - pa.y);
186
+ // A zero-length wall renders as a flickering sliver that looks like a
187
+ // graphics fault rather than a map mistake.
188
+ if (lengthM <= 0) continue;
189
+
190
+ const heightM = wall.heightM ?? WALL_HEIGHT_M;
191
+ solids.push({
192
+ centre: {
193
+ x: (pa.x + pb.x) / 2,
194
+ y: (pa.y + pb.y) / 2,
195
+ // Boxes are centred, so a wall standing ON the floor sits at half its
196
+ // own height above the level's elevation.
197
+ z: level.elevationM + heightM / 2,
198
+ },
199
+ lengthM,
200
+ thicknessM: wall.thicknessM ?? WALL_THICKNESS_M,
201
+ heightM,
202
+ yaw: Math.atan2(pb.y - pa.y, pb.x - pa.x),
203
+ });
204
+ }
205
+ return solids;
206
+ }
207
+
208
+ /* ----------------------------------------------------------- projection */
209
+
210
+ export type TView = {
211
+ /** Radians. How far the scene is turned about the vertical axis. */
212
+ rotation: number;
213
+ /** Radians. 0 is a plan view looking straight down; ~0.9 reads as 3D. */
214
+ tilt: number;
215
+ /** Screen pixels per metre. */
216
+ zoom: number;
217
+ /** Where the site origin lands on the canvas. */
218
+ originPx: { x: number; y: number };
219
+ };
220
+
221
+ /**
222
+ * A point in site metres, on the canvas.
223
+ *
224
+ * An axonometric projection: rotate about the vertical axis, then foreshorten
225
+ * the depth axis by the tilt. Parallel, so there is no perspective distortion
226
+ * and a wall is the same size wherever it sits — which is what you want for a
227
+ * floor plan, and is why a full camera is not needed.
228
+ *
229
+ * Screen y grows downward, so height is SUBTRACTED: a taller wall draws further
230
+ * up the canvas.
231
+ */
232
+ export function projectPoint(
233
+ x: number,
234
+ y: number,
235
+ z: number,
236
+ view: TView,
237
+ ): { x: number; y: number } {
238
+ const cos = Math.cos(view.rotation);
239
+ const sin = Math.sin(view.rotation);
240
+
241
+ const rx = x * cos - y * sin;
242
+ const ry = x * sin + y * cos;
243
+
244
+ return {
245
+ x: view.originPx.x + rx * view.zoom,
246
+ y: view.originPx.y + ry * view.zoom * Math.cos(view.tilt) - z * view.zoom * Math.sin(view.tilt),
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Back-to-front order, so nearer walls are drawn over farther ones.
252
+ *
253
+ * Painter's algorithm: with no depth buffer, draw order IS the depth test. Sort
254
+ * by the rotated depth axis, lowest first — get this backwards and the building
255
+ * renders inside out, which looks like a rendering bug and is really a sort.
256
+ */
257
+ export function depthOf(point: { x: number; y: number }, view: TView): number {
258
+ return point.x * Math.sin(view.rotation) + point.y * Math.cos(view.rotation);
259
+ }
260
+
261
+ /** The eight corners of a wall box, in site metres. */
262
+ export function wallCorners(solid: TWallSolid): Array<{ x: number; y: number; z: number }> {
263
+ const hl = solid.lengthM / 2;
264
+ const ht = solid.thicknessM / 2;
265
+ const hh = solid.heightM / 2;
266
+ const cos = Math.cos(solid.yaw);
267
+ const sin = Math.sin(solid.yaw);
268
+
269
+ const corners: Array<{ x: number; y: number; z: number }> = [];
270
+ for (const dz of [-hh, hh]) {
271
+ for (const [dl, dt] of [
272
+ [-hl, -ht],
273
+ [hl, -ht],
274
+ [hl, ht],
275
+ [-hl, ht],
276
+ ] as const) {
277
+ corners.push({
278
+ x: solid.centre.x + dl * cos - dt * sin,
279
+ y: solid.centre.y + dl * sin + dt * cos,
280
+ z: solid.centre.z + dz,
281
+ });
282
+ }
283
+ }
284
+ return corners;
285
+ }
286
+
287
+ /**
288
+ * How big the site is, so a view can be framed without anyone choosing numbers.
289
+ *
290
+ * Returns null for an empty scene rather than a zero-size box: a caller must be
291
+ * able to tell "nothing to show" from "everything is at the origin".
292
+ */
293
+ export function solidsBounds(solids: TWallSolid[]): {
294
+ minX: number; maxX: number; minY: number; maxY: number;
295
+ } | null {
296
+ if (!solids.length) return null;
297
+
298
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
299
+ for (const s of solids) {
300
+ for (const c of wallCorners(s)) {
301
+ if (c.x < minX) minX = c.x;
302
+ if (c.x > maxX) maxX = c.x;
303
+ if (c.y < minY) minY = c.y;
304
+ if (c.y > maxY) maxY = c.y;
305
+ }
306
+ }
307
+ return { minX, maxX, minY, maxY };
308
+ }
309
+
310
+ /**
311
+ * A view that fits the whole site on the canvas.
312
+ *
313
+ * Falls back to a sane zoom for a degenerate scene — a single wall has zero
314
+ * extent on one axis, and dividing by it would give an infinite zoom and a
315
+ * blank canvas.
316
+ */
317
+ export function fitView(
318
+ solids: TWallSolid[],
319
+ canvas: { width: number; height: number },
320
+ options?: { rotation?: number; tilt?: number; paddingPx?: number },
321
+ ): TView {
322
+ const rotation = options?.rotation ?? Math.PI / 5;
323
+ const tilt = options?.tilt ?? 0.95;
324
+ const padding = options?.paddingPx ?? 32;
325
+
326
+ const base: TView = {
327
+ rotation,
328
+ tilt,
329
+ zoom: 20,
330
+ originPx: { x: canvas.width / 2, y: canvas.height / 2 },
331
+ };
332
+
333
+ const bounds = solidsBounds(solids);
334
+ if (!bounds) return base;
335
+
336
+ const projected = [
337
+ { x: bounds.minX, y: bounds.minY },
338
+ { x: bounds.maxX, y: bounds.minY },
339
+ { x: bounds.maxX, y: bounds.maxY },
340
+ { x: bounds.minX, y: bounds.maxY },
341
+ ].map((p) => projectPoint(p.x, p.y, 0, { ...base, zoom: 1, originPx: { x: 0, y: 0 } }));
342
+
343
+ const spanX = Math.max(...projected.map((p) => p.x)) - Math.min(...projected.map((p) => p.x));
344
+ const spanY = Math.max(...projected.map((p) => p.y)) - Math.min(...projected.map((p) => p.y));
345
+
346
+ const usableW = Math.max(1, canvas.width - padding * 2);
347
+ const usableH = Math.max(1, canvas.height - padding * 2);
348
+ const zoom =
349
+ spanX > 0 && spanY > 0
350
+ ? Math.min(usableW / spanX, usableH / spanY)
351
+ : base.zoom;
352
+
353
+ const centre = projectPoint(
354
+ (bounds.minX + bounds.maxX) / 2,
355
+ (bounds.minY + bounds.maxY) / 2,
356
+ 0,
357
+ { ...base, zoom, originPx: { x: 0, y: 0 } },
358
+ );
359
+
360
+ return {
361
+ rotation,
362
+ tilt,
363
+ zoom,
364
+ originPx: { x: canvas.width / 2 - centre.x, y: canvas.height / 2 - centre.y },
365
+ };
366
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * How a robot's state is shown to a person.
3
+ *
4
+ * The API answers with a mode from a fixed vocabulary; every screen turns that
5
+ * into the same words and the same colour, so a cleaner on a phone and a manager
6
+ * on a desktop are never looking at two different descriptions of one robot.
7
+ *
8
+ * Pure on purpose: the interesting part is the failure wording, and none of it
9
+ * needs Nuxt, a network or a robot to test.
10
+ */
11
+
12
+ export type TRobotMode =
13
+ | "IDLE"
14
+ | "CHARGED"
15
+ | "WORKING"
16
+ | "PAUSED"
17
+ | "CHARGING_CYCLE"
18
+ | "MAINTENANCE"
19
+ | "IN_TRANSIT"
20
+ | "MANUAL"
21
+ | "UNAVAILABLE";
22
+
23
+ export type TRobotDisplay = {
24
+ /** What the person reads. */
25
+ label: string;
26
+ /** A Vuetify colour token, not a hex — the theme decides the shade. */
27
+ color: string;
28
+ icon: string;
29
+ /** True only when the robot could be given a job this moment. */
30
+ ready: boolean;
31
+ };
32
+
33
+ const DISPLAY: Readonly<Record<TRobotMode, TRobotDisplay>> = {
34
+ IDLE: { label: "Ready", color: "success", icon: "mdi-check-circle-outline", ready: true },
35
+ CHARGED: { label: "Charged", color: "success", icon: "mdi-battery-charging-100", ready: true },
36
+ WORKING: { label: "Cleaning", color: "primary", icon: "mdi-broom", ready: false },
37
+ PAUSED: { label: "Paused", color: "warning", icon: "mdi-pause-circle-outline", ready: false },
38
+ CHARGING_CYCLE: { label: "Charging", color: "info", icon: "mdi-battery-charging", ready: false },
39
+ MAINTENANCE: { label: "Maintenance", color: "warning", icon: "mdi-wrench-outline", ready: false },
40
+ IN_TRANSIT: { label: "Changing floor", color: "info", icon: "mdi-elevator-passenger-outline", ready: false },
41
+ MANUAL: { label: "Manual control", color: "warning", icon: "mdi-hand-back-right-outline", ready: false },
42
+ UNAVAILABLE: { label: "Unavailable", color: "error", icon: "mdi-alert-circle-outline", ready: false },
43
+ };
44
+
45
+ const UNKNOWN: TRobotDisplay = {
46
+ label: "Unknown",
47
+ color: "error",
48
+ icon: "mdi-help-circle-outline",
49
+ ready: false,
50
+ };
51
+
52
+ /**
53
+ * A mode we do not recognise shows as "Unknown" and is NEVER ready.
54
+ *
55
+ * The branch that matters. A firmware state this build has not seen must not
56
+ * render as a green "Ready" chip with a Clean button beside it — a person would
57
+ * press it, and the robot would refuse, and the screen would look broken.
58
+ */
59
+ export function robotDisplay(mode: unknown): TRobotDisplay {
60
+ if (typeof mode !== "string") return UNKNOWN;
61
+ return DISPLAY[mode as TRobotMode] ?? UNKNOWN;
62
+ }
63
+
64
+ /**
65
+ * May the Clean / Return buttons be offered?
66
+ *
67
+ * Offline beats everything: a robot we cannot reach cannot be commanded,
68
+ * whatever its last known mode said.
69
+ */
70
+ export function canDispatch(state: {
71
+ online?: unknown;
72
+ dispatchable?: unknown;
73
+ mode?: unknown;
74
+ } | null | undefined): boolean {
75
+ if (!state) return false;
76
+ if (state.online === false) return false;
77
+ // The server already decided this; the client agrees rather than re-deriving,
78
+ // so the two can never disagree about whether a button should be there.
79
+ return state.dispatchable === true;
80
+ }
81
+
82
+ /**
83
+ * Return-to-dock is offered even when a robot is busy.
84
+ *
85
+ * It is how an operator recovers a robot, so it has to be reachable precisely
86
+ * when the robot is doing something wrong. Only an unreachable robot hides it.
87
+ */
88
+ export function canRecall(state: { online?: unknown } | null | undefined): boolean {
89
+ if (!state) return false;
90
+ return state.online !== false;
91
+ }
92
+
93
+ /**
94
+ * The floor to show, when the robot does not report one.
95
+ *
96
+ * The vendor's tracking stream carries no floor, so anything claiming to know it
97
+ * must say how sure it is. An unknown floor is shown as unknown rather than
98
+ * guessed — a robot displayed on the wrong storey is worse than one displayed
99
+ * on no storey.
100
+ */
101
+ export function floorLabel(state: {
102
+ floorNo?: unknown;
103
+ floorKnown?: unknown;
104
+ } | null | undefined): string {
105
+ if (!state || state.floorKnown !== true) return "Floor unknown";
106
+ return typeof state.floorNo === "number" ? `Floor ${state.floorNo}` : "Floor unknown";
107
+ }
108
+
109
+ /**
110
+ * Turn a failed fleet call into something worth reading.
111
+ *
112
+ * These calls cross to the vendor's cloud, so the useful message is usually the
113
+ * server's own — "Robot X is Cleaning and cannot take a new job" tells an
114
+ * operator what to do; "Request failed" does not.
115
+ */
116
+ export function robotErrorMessage(error: unknown, fallback = "Could not reach the robot."): string {
117
+ const e = error as any;
118
+ const fromServer =
119
+ e?.data?.message ?? e?.response?._data?.message ?? e?.data?.msg;
120
+ if (typeof fromServer === "string" && fromServer.trim()) return fromServer.trim();
121
+ if (typeof e?.message === "string" && e.message.trim()) return e.message.trim();
122
+ return fallback;
123
+ }