@7365admin1/layer-common 4.25.0 → 4.27.0

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.
@@ -4,7 +4,7 @@
4
4
  <template #left>
5
5
  <AppSelect
6
6
  v-model="selectedFloor"
7
- :items="floorOptions"
7
+ :items="editing ? realFloorOptions : floorOptions"
8
8
  item-title="title"
9
9
  item-value="value"
10
10
  label="Level"
@@ -16,8 +16,23 @@
16
16
  <span v-if="wallCount" class="text-caption text-medium-emphasis ml-4">
17
17
  {{ wallCount }} walls found
18
18
  </span>
19
+ <span v-if="savedMap" class="text-caption text-medium-emphasis ml-3">
20
+ · saved layout (version {{ savedMap.version }})
21
+ </span>
22
+ <span v-else-if="savedLoadFailed" class="text-caption text-error ml-3">
23
+ · saved layout could not be loaded
24
+ </span>
19
25
  </template>
20
26
  <template #right>
27
+ <AppButton
28
+ v-if="canEdit && !editing && !savedLoadFailed"
29
+ variant="ghost"
30
+ icon="mdi-pencil-ruler"
31
+ :disabled="loading || !!error"
32
+ @click="startEditing"
33
+ >
34
+ {{ savedMap ? "Edit layout" : "Add doors & lifts" }}
35
+ </AppButton>
21
36
  <AppButton
22
37
  variant="icon"
23
38
  icon="mdi-rotate-left"
@@ -36,14 +51,54 @@
36
51
  variant="icon"
37
52
  :icon="tilted ? 'mdi-cube-outline' : 'mdi-floor-plan'"
38
53
  :aria-label="tilted ? 'Show as a flat plan' : 'Show in 3D'"
39
- :disabled="loading"
54
+ :disabled="loading || editing"
40
55
  @click="toggleTilt"
41
56
  />
42
57
  </template>
43
58
  </CardToolbar>
44
59
 
45
- <div ref="stage" class="robot-map3d">
46
- <canvas ref="canvasEl" class="robot-map3d__canvas" />
60
+ <!--
61
+ Editing happens on the flat plan of one floor, so a click lands exactly
62
+ where it looks like it lands.
63
+ -->
64
+ <div v-if="editing" class="robot-map3d__editbar px-4 py-2">
65
+ <AppSegmented v-model="tool" :options="toolOptions" />
66
+ <v-text-field
67
+ v-model.number="currentHeight"
68
+ type="number"
69
+ step="0.1"
70
+ label="Floor height (m)"
71
+ density="compact"
72
+ hide-details
73
+ style="max-width: 150px"
74
+ />
75
+ <span class="text-caption text-medium-emphasis">{{ toolHint }}</span>
76
+ <v-spacer />
77
+ <AppButton
78
+ v-if="savedMap"
79
+ variant="ghost"
80
+ icon="mdi-delete-outline"
81
+ :disabled="saving"
82
+ @click="removeSaved"
83
+ >
84
+ {{ confirmRemove ? "Confirm remove" : "Remove saved layout" }}
85
+ </AppButton>
86
+ <AppButton variant="ghost" :disabled="saving" @click="cancelEditing">Cancel</AppButton>
87
+ <AppButton icon="mdi-content-save-outline" :disabled="saving" @click="save">
88
+ {{ saving ? "Saving…" : "Save layout" }}
89
+ </AppButton>
90
+ </div>
91
+ <p v-if="editError" class="text-body-2 text-error px-4 pt-2 mb-0">{{ editError }}</p>
92
+
93
+ <div ref="stage" class="robot-map3d" :class="{ 'robot-map3d--placing': editing && tool !== 'select' }">
94
+ <canvas
95
+ ref="canvasEl"
96
+ class="robot-map3d__canvas"
97
+ @pointerdown="onPointerDown"
98
+ @pointermove="onPointerMove"
99
+ @pointerup="onPointerUp"
100
+ @pointercancel="onPointerUp"
101
+ />
47
102
 
48
103
  <div v-if="loading" class="robot-map3d__overlay">
49
104
  <v-progress-circular indeterminate size="28" />
@@ -58,22 +113,126 @@
58
113
  <div v-else-if="error" class="robot-map3d__overlay">
59
114
  <v-icon size="36" class="mb-2">mdi-map-marker-off-outline</v-icon>
60
115
  <p class="text-body-2 mb-3">{{ error }}</p>
61
- <AppButton size="small" variant="outlined" @click="load">Try again</AppButton>
116
+ <AppButton variant="ghost" @click="load">Try again</AppButton>
62
117
  </div>
63
118
 
64
- <div v-else-if="!wallCount" class="robot-map3d__overlay">
119
+ <div v-else-if="!wallCount && !featureCount && !editing" class="robot-map3d__overlay">
65
120
  <v-icon size="36" class="mb-2">mdi-floor-plan</v-icon>
66
121
  <p class="text-body-2 mb-0">
67
122
  No walls could be found in this floor plan.
68
123
  </p>
69
124
  </div>
70
125
  </div>
126
+
127
+ <!-- The feature being edited. -->
128
+ <div v-if="editing && selectedFeature" class="robot-map3d__panel px-4 py-3">
129
+ <v-text-field
130
+ v-model="selectedFeature.name"
131
+ :label="selected?.kind === 'lift' ? 'Lift name' : 'Door name'"
132
+ density="compact"
133
+ hide-details
134
+ maxlength="60"
135
+ style="max-width: 220px"
136
+ />
137
+ <AppSelect
138
+ v-if="selected?.kind === 'door'"
139
+ v-model="doorType"
140
+ :items="doorTypes"
141
+ item-title="title"
142
+ item-value="value"
143
+ label="Type"
144
+ density="compact"
145
+ hide-details
146
+ style="max-width: 160px"
147
+ />
148
+ <AppSelect
149
+ v-if="selected?.kind === 'lift'"
150
+ v-model="liftFloors"
151
+ :items="realFloorOptions"
152
+ item-title="title"
153
+ item-value="value"
154
+ label="Stops at"
155
+ multiple
156
+ chips
157
+ density="compact"
158
+ hide-details
159
+ style="min-width: 260px"
160
+ />
161
+ <v-spacer />
162
+ <AppButton variant="ghost" icon="mdi-delete-outline" @click="removeSelected">Remove</AppButton>
163
+ </div>
164
+
165
+ <!--
166
+ The lift queue. The car is a SIMULATOR - there is no lift driver until
167
+ the lift maker supplies its register map - and the panel says so.
168
+ -->
169
+ <div v-if="!editing && savedMap?.lifts?.length" class="robot-map3d__lifts px-4 py-3">
170
+ <div class="d-flex align-center mb-2">
171
+ <span class="font-weight-medium">Lifts</span>
172
+ <span class="text-caption text-medium-emphasis ml-2">simulated — no real lift is controlled</span>
173
+ </div>
174
+ <p v-if="liftError" class="text-body-2 text-error mb-2">{{ liftError }}</p>
175
+ <div v-for="lift in liftQueue" :key="lift.liftName" class="robot-map3d__lift mb-3">
176
+ <div class="text-body-2">
177
+ <strong>{{ lift.liftName }}</strong>
178
+ — floor {{ lift.state?.currentFloor }}, {{ motionLabel(lift.state) }}, doors {{ doorLabel(lift.state) }}.
179
+ {{ phaseLabel(lift) }}
180
+ </div>
181
+ <div v-if="lift.active" class="text-body-2 mt-1 d-flex align-center flex-wrap ga-2">
182
+ <span>
183
+ In the lift: <strong>{{ lift.active.robotName }}</strong>
184
+ (floor {{ lift.active.fromFloor }} → {{ lift.active.toFloor }}), released automatically
185
+ {{ untilLabel(lift.active.expiresAt) }} unless it finishes first.
186
+ </span>
187
+ <AppButton v-if="canEdit" variant="ghost" @click="release(lift.active)">Release</AppButton>
188
+ </div>
189
+ <div v-for="(row, i) in lift.queue" :key="row._id" class="text-body-2 mt-1 d-flex align-center flex-wrap ga-2">
190
+ <span>Waiting {{ i + 1 }}: {{ row.robotName }} (floor {{ row.fromFloor }} → {{ row.toFloor }})</span>
191
+ <AppButton v-if="canEdit" variant="ghost" @click="release(row)">Remove from queue</AppButton>
192
+ </div>
193
+ <div v-if="!lift.active && !lift.queue?.length" class="text-caption text-medium-emphasis">
194
+ Nobody is waiting.
195
+ </div>
196
+
197
+ <div v-if="canEdit && robotBrand === 'demo' && !thisRobotWaiting" class="d-flex align-center flex-wrap ga-2 mt-2">
198
+ <AppSelect
199
+ v-model="requestFrom[lift.liftName]"
200
+ :items="lift.floors"
201
+ label="From floor"
202
+ density="compact"
203
+ hide-details
204
+ style="max-width: 130px"
205
+ />
206
+ <AppSelect
207
+ v-model="requestTo[lift.liftName]"
208
+ :items="lift.floors"
209
+ label="To floor"
210
+ density="compact"
211
+ hide-details
212
+ style="max-width: 130px"
213
+ />
214
+ <AppButton
215
+ variant="ghost"
216
+ icon="mdi-elevator-passenger-outline"
217
+ :disabled="requesting"
218
+ @click="askForLift(lift)"
219
+ >
220
+ Request lift for {{ robotName || "this robot" }}
221
+ </AppButton>
222
+ </div>
223
+ </div>
224
+ <p v-if="robotBrand !== 'demo'" class="text-caption text-medium-emphasis mb-0">
225
+ Only demo robots can ride a lift for now. Real lifts need the lift maker's driver, which is not available yet.
226
+ </p>
227
+ </div>
71
228
  </AppCard>
72
229
  </template>
73
230
 
74
231
  <script lang="ts" setup>
75
232
  /**
76
- * The building, in 3D, generated from the robot's own floor plan.
233
+ * The building, in 3D, generated from the robot's own floor plan - plus the
234
+ * saved layout: doors, lift shafts and floor heights, which the floor plan
235
+ * cannot say by itself.
77
236
  *
78
237
  * Nobody draws walls. The robot's map image is a SLAM occupancy grid — walls
79
238
  * are already dark pixels — so it is fetched into a canvas, thresholded, traced
@@ -81,6 +240,13 @@
81
240
  * annotated plan; this skips the annotation because the robot has surveyed the
82
241
  * building already.
83
242
  *
243
+ * ## The saved layout
244
+ *
245
+ * Doors and lift shafts are placed by hand in edit mode (flat plan, one floor)
246
+ * and saved to the building map (`/api/robots/building-maps`). With no saved
247
+ * map the view is exactly what it was before - the saved map only adds. A lift
248
+ * shaft runs through every floor it stops at, which the stacked view shows.
249
+ *
84
250
  * ## Why the image is fetched every time
85
251
  *
86
252
  * The vendor signs its map URLs for about an hour. A URL kept in a record is a
@@ -100,12 +266,22 @@
100
266
  */
101
267
  import {
102
268
  depthOf,
269
+ distanceToSegment,
270
+ doorSolid,
103
271
  fitView,
104
272
  gridFromImageData,
273
+ insideLift,
274
+ levelElevations,
105
275
  levelSolids,
276
+ liftSolid,
277
+ nextFeatureName,
106
278
  projectPoint,
279
+ unprojectPoint,
107
280
  wallCorners,
108
281
  wallsFromOccupancyGrid,
282
+ type TMapDoor,
283
+ type TMapLift,
284
+ type TMapPointM,
109
285
  type TView,
110
286
  type TWallSolid,
111
287
  } from "../../utils/building-map";
@@ -116,32 +292,73 @@ const props = defineProps<{
116
292
  robotId: string;
117
293
  /** Drawn on the plan when its position and floor are both known. */
118
294
  robotState?: Record<string, any> | null;
295
+ /** May this person save the layout and use the lift (`update-robot`)? */
296
+ canEdit?: boolean;
297
+ robotName?: string;
298
+ /** Only the demo brand can ride the simulated lift. */
299
+ robotBrand?: string;
119
300
  }>();
120
301
 
121
- const { getRobotMaps, getRobotMapImages } = useRobots();
302
+ const {
303
+ getRobotMaps,
304
+ getRobotMapImages,
305
+ listBuildingMaps,
306
+ getBuildingMap,
307
+ createBuildingMap,
308
+ updateBuildingMap,
309
+ deleteBuildingMap,
310
+ getLiftQueue,
311
+ requestLift,
312
+ releaseLiftSession,
313
+ } = useRobots();
122
314
 
123
315
  const stage = ref<HTMLElement | null>(null);
124
316
  const canvasEl = ref<HTMLCanvasElement | null>(null);
125
317
 
126
318
  const maps = ref<Array<Record<string, any>>>([]);
127
319
  const selectedFloor = ref<number | null>(null);
128
- const solids = ref<TWallSolid[]>([]);
129
- const imageHeight = ref(0);
320
+ const wallSolids = ref<TWallSolid[]>([]);
130
321
  const loading = ref(true);
131
322
  const error = ref("");
132
323
  const rotation = ref(Math.PI / 5);
133
324
  const tilted = ref(true);
134
325
 
135
- const wallCount = computed(() => solids.value.length);
326
+ /* The saved layout, and the working copy the editor changes. */
327
+ const savedMap = ref<Record<string, any> | null>(null);
328
+ const savedLoadFailed = ref(false);
329
+ const doors = ref<TMapDoor[]>([]);
330
+ const lifts = ref<TMapLift[]>([]);
331
+ const heights = ref<Record<number, number | undefined>>({});
136
332
 
137
- const floorOptions = computed(() =>
333
+ const wallCount = computed(() => wallSolids.value.length);
334
+ const featureCount = computed(() => doors.value.length + lifts.value.length);
335
+
336
+ /**
337
+ * "All levels" stacks every floor the robot has mapped.
338
+ * A sentinel rather than null, because null already means "nothing chosen".
339
+ */
340
+ const ALL_LEVELS = -1_000_000;
341
+
342
+ const realFloorOptions = computed(() =>
138
343
  maps.value
139
- .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: m.floorNo }))
344
+ .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: Number(m.floorNo) }))
140
345
  .sort((a, b) => a.value - b.value),
141
346
  );
142
347
 
143
- const currentMap = computed(() =>
144
- maps.value.find((m) => m.floorNo === selectedFloor.value) ?? null,
348
+ const floorOptions = computed(() =>
349
+ realFloorOptions.value.length > 1
350
+ ? [...realFloorOptions.value, { title: "All levels (stacked)", value: ALL_LEVELS }]
351
+ : realFloorOptions.value,
352
+ );
353
+
354
+ const stacked = computed(() => selectedFloor.value === ALL_LEVELS);
355
+
356
+ /** Each floor's height: saved where set, otherwise one storey apart. */
357
+ const elevations = computed(() =>
358
+ levelElevations(
359
+ maps.value.map((m) => Number(m.floorNo)),
360
+ Object.entries(heights.value).map(([f, h]) => ({ floorNo: Number(f), elevationM: h })),
361
+ ),
145
362
  );
146
363
 
147
364
  /* ------------------------------------------------------------------ load */
@@ -159,6 +376,7 @@ async function load() {
159
376
  }
160
377
  selectedFloor.value = floorOptions.value[0]?.value ?? null;
161
378
  }
379
+ await loadSaved();
162
380
  await buildLevel();
163
381
  } catch (e) {
164
382
  error.value = robotErrorMessage(e, "Could not load this building's floor plan.");
@@ -167,24 +385,78 @@ async function load() {
167
385
  }
168
386
  }
169
387
 
170
- /** Fetch this floor's plan, trace its walls, and extrude them. */
388
+ /**
389
+ * The newest saved map, if any. Never fails the view: without a saved map the
390
+ * building shows exactly as it always did. A map that exists but could not be
391
+ * read turns editing OFF - saving blind would create a second map beside it.
392
+ */
393
+ async function loadSaved() {
394
+ savedLoadFailed.value = false;
395
+ try {
396
+ const list = await listBuildingMaps(props.robotId, { limit: 1 });
397
+ const first = list?.items?.[0];
398
+ savedMap.value = first ? await getBuildingMap(String(first._id)) : null;
399
+ } catch {
400
+ savedMap.value = null;
401
+ savedLoadFailed.value = true;
402
+ }
403
+ applySaved(savedMap.value);
404
+ pollLifts();
405
+ }
406
+
407
+ function applySaved(map: Record<string, any> | null) {
408
+ const copy = (v: unknown) => JSON.parse(JSON.stringify(v ?? []));
409
+ doors.value = copy(map?.doors);
410
+ lifts.value = copy(map?.lifts);
411
+ const h: Record<number, number | undefined> = {};
412
+ for (const level of map?.levels ?? []) {
413
+ if (typeof level.elevationM === "number") h[Number(level.floorNo)] = level.elevationM;
414
+ }
415
+ heights.value = h;
416
+ }
417
+
418
+ /**
419
+ * Fetch the selected floor's plan - or every floor's, stacked - trace the
420
+ * walls and extrude them.
421
+ */
171
422
  async function buildLevel() {
172
- const map = currentMap.value;
173
- solids.value = [];
174
- if (!map?.backgroundFileKey) {
423
+ wallSolids.value = [];
424
+ const chosen = stacked.value
425
+ ? [...maps.value].sort((a, b) => a.floorNo - b.floorNo)
426
+ : maps.value.filter((m) => Number(m.floorNo) === selectedFloor.value);
427
+
428
+ if (!chosen.length || chosen.some((m) => !m.backgroundFileKey)) {
175
429
  error.value = "This floor has no plan image.";
176
430
  return;
177
431
  }
178
432
 
179
- const files = await getRobotMapImages(props.robotId, [map.backgroundFileKey]);
180
- const url = files?.items?.find((f: any) => f.fileKey === map.backgroundFileKey)?.url;
181
- if (!url) {
182
- error.value = "The floor plan image could not be fetched.";
183
- return;
433
+ const keys = chosen.map((m) => m.backgroundFileKey);
434
+ const files = await getRobotMapImages(props.robotId, keys);
435
+
436
+ const built: TWallSolid[] = [];
437
+ for (const map of chosen) {
438
+ const url = files?.items?.find((f: any) => f.fileKey === map.backgroundFileKey)?.url;
439
+ if (!url) {
440
+ error.value = "The floor plan image could not be fetched.";
441
+ return;
442
+ }
443
+ const z = stacked.value ? elevations.value.get(Number(map.floorNo)) ?? 0 : 0;
444
+ const level = await traceLevel(map, url, z);
445
+ if (!level) return;
446
+ built.push(...level);
184
447
  }
185
448
 
449
+ wallSolids.value = built;
450
+ draw();
451
+ }
452
+
453
+ /** One floor plan image to extruded wall boxes, at a given height. */
454
+ async function traceLevel(
455
+ map: Record<string, any>,
456
+ url: string,
457
+ elevationM: number,
458
+ ): Promise<TWallSolid[] | null> {
186
459
  const image = await loadImage(url);
187
- imageHeight.value = image.height;
188
460
 
189
461
  const work = document.createElement("canvas");
190
462
  work.width = image.width;
@@ -192,7 +464,7 @@ async function buildLevel() {
192
464
  const wctx = work.getContext("2d", { willReadFrequently: true });
193
465
  if (!wctx) {
194
466
  error.value = "This browser could not read the floor plan image.";
195
- return;
467
+ return null;
196
468
  }
197
469
  wctx.drawImage(image, 0, 0);
198
470
 
@@ -200,10 +472,10 @@ async function buildLevel() {
200
472
  const grid = gridFromImageData(data, image.width, image.height);
201
473
  const { vertices, walls } = wallsFromOccupancyGrid(grid, { minRunPx: 6 });
202
474
 
203
- solids.value = levelSolids(
475
+ return levelSolids(
204
476
  {
205
477
  name: map.mapName ?? `L${map.floorNo}`,
206
- elevationM: 0,
478
+ elevationM,
207
479
  scaleMPerPx: Number(map.resolution) || 0.05,
208
480
  originXM: Number(map.originX) || 0,
209
481
  originYM: Number(map.originY) || 0,
@@ -212,8 +484,6 @@ async function buildLevel() {
212
484
  },
213
485
  image.height,
214
486
  );
215
-
216
- draw();
217
487
  }
218
488
 
219
489
  /**
@@ -233,6 +503,52 @@ function loadImage(url: string): Promise<HTMLImageElement> {
233
503
 
234
504
  /* ------------------------------------------------------------------ draw */
235
505
 
506
+ /** Solids that are the thing being edited, so they draw highlighted. */
507
+ let highlighted = new WeakSet<TWallSolid>();
508
+
509
+ /** Doors, lift shafts and the simulated car, for the current view. */
510
+ function featureSolids(): TWallSolid[] {
511
+ highlighted = new WeakSet();
512
+ const out: TWallSolid[] = [];
513
+ const elev = elevations.value;
514
+ const floor = selectedFloor.value ?? undefined;
515
+
516
+ doors.value.forEach((door, i) => {
517
+ if (stacked.value ? !elev.has(door.floorNo) : door.floorNo !== floor) return;
518
+ const solid = doorSolid(door, stacked.value ? elev.get(door.floorNo) ?? 0 : 0);
519
+ if (!solid) return;
520
+ if (selected.value?.kind === "door" && selected.value.index === i) highlighted.add(solid);
521
+ out.push(solid);
522
+ });
523
+
524
+ lifts.value.forEach((lift, i) => {
525
+ const solid = stacked.value ? liftSolid(lift, elev) : liftSolid(lift, elev, floor);
526
+ if (!solid) return;
527
+ if (selected.value?.kind === "lift" && selected.value.index === i) highlighted.add(solid);
528
+ out.push(solid);
529
+ });
530
+
531
+ // The simulated car, on the floor it is at - stacked only, where floors differ.
532
+ if (stacked.value && !editing.value) {
533
+ for (const q of liftQueue.value) {
534
+ const lift = lifts.value.find((l) => l.name === q.liftName);
535
+ const at = Number(q.state?.currentFloor);
536
+ if (!lift || !elev.has(at)) continue;
537
+ out.push({
538
+ kind: "car",
539
+ centre: { x: lift.x, y: lift.y, z: (elev.get(at) ?? 0) + 1.1 },
540
+ lengthM: lift.widthM * 0.8,
541
+ thicknessM: lift.depthM * 0.8,
542
+ heightM: 2.2,
543
+ yaw: 0,
544
+ });
545
+ }
546
+ }
547
+ return out;
548
+ }
549
+
550
+ let lastView: TView | null = null;
551
+
236
552
  function draw() {
237
553
  const canvas = canvasEl.value;
238
554
  const host = stage.value;
@@ -251,20 +567,48 @@ function draw() {
251
567
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
252
568
  ctx.clearRect(0, 0, width, height);
253
569
 
254
- const view: TView = fitView(solids.value, { width, height }, {
570
+ const features = featureSolids();
571
+ const scene = [...wallSolids.value, ...features];
572
+
573
+ // Framed on the walls when there are any, so adding or dragging a feature
574
+ // does not move the whole picture under the pointer.
575
+ const view: TView = fitView(wallSolids.value.length ? wallSolids.value : scene, { width, height }, {
255
576
  rotation: rotation.value,
256
577
  tilt: tilted.value ? 0.95 : 0,
257
578
  });
579
+ lastView = view;
258
580
 
259
581
  // Painter's algorithm: with no depth buffer, draw order IS the depth test.
260
- const ordered = [...solids.value].sort(
261
- (a, b) => depthOf(a.centre, view) - depthOf(b.centre, view),
582
+ // Lower storeys first when stacked - seen from above, a floor hides the one
583
+ // beneath it, never the other way round.
584
+ const ordered = [...scene].sort(
585
+ (a, b) => a.centre.z - b.centre.z || depthOf(a.centre, view) - depthOf(b.centre, view),
262
586
  );
263
587
 
264
588
  for (const solid of ordered) drawBox(ctx, solid, view);
589
+ drawPending(ctx, view);
265
590
  drawRobot(ctx, view);
266
591
  }
267
592
 
593
+ /** Fill colour per kind of box; the face shade multiplies it. */
594
+ function fillFor(solid: TWallSolid, shade: number): string {
595
+ const lit = highlighted.has(solid) ? 1.15 : 1;
596
+ const c = (r: number, g: number, b: number, a = 1) =>
597
+ `rgba(${Math.min(255, Math.round(r * shade * lit))},${Math.min(255, Math.round(g * shade * lit))},${Math.min(255, Math.round(b * shade * lit))},${a})`;
598
+ switch (solid.kind) {
599
+ case "door":
600
+ return c(196, 128, 66);
601
+ case "lift":
602
+ return c(60, 130, 230, highlighted.has(solid) ? 0.45 : 0.28);
603
+ case "car":
604
+ return c(255, 150, 40);
605
+ default: {
606
+ const v = Math.round(150 * shade + 60);
607
+ return `rgb(${v},${v + 4},${v + 8})`;
608
+ }
609
+ }
610
+ }
611
+
268
612
  /** The three visible faces of a box: top, and two sides. */
269
613
  function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView) {
270
614
  const c = wallCorners(solid).map((p) => projectPoint(p.x, p.y, p.z, view));
@@ -281,15 +625,25 @@ function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView)
281
625
  ctx.beginPath();
282
626
  face.idx.forEach((i, n) => (n === 0 ? ctx.moveTo(c[i].x, c[i].y) : ctx.lineTo(c[i].x, c[i].y)));
283
627
  ctx.closePath();
284
- const v = Math.round(150 * face.shade + 60);
285
- ctx.fillStyle = `rgb(${v},${v + 4},${v + 8})`;
628
+ ctx.fillStyle = fillFor(solid, face.shade);
286
629
  ctx.fill();
287
- ctx.strokeStyle = "rgba(20,28,38,0.22)";
288
- ctx.lineWidth = 0.6;
630
+ ctx.strokeStyle = highlighted.has(solid) ? "rgba(255,90,31,0.9)" : "rgba(20,28,38,0.22)";
631
+ ctx.lineWidth = highlighted.has(solid) ? 1.4 : 0.6;
289
632
  ctx.stroke();
290
633
  }
291
634
  }
292
635
 
636
+ /** The first click of a door being drawn. */
637
+ function drawPending(ctx: CanvasRenderingContext2D, view: TView) {
638
+ const p = pendingDoorStart.value;
639
+ if (!editing.value || !p) return;
640
+ const s = projectPoint(p.x, p.y, 0, view);
641
+ ctx.beginPath();
642
+ ctx.arc(s.x, s.y, 5, 0, Math.PI * 2);
643
+ ctx.fillStyle = "#C48042";
644
+ ctx.fill();
645
+ }
646
+
293
647
  /**
294
648
  * The robot, only when its position AND its floor are both known.
295
649
  *
@@ -301,10 +655,12 @@ function drawRobot(ctx: CanvasRenderingContext2D, view: TView) {
301
655
  const state = props.robotState;
302
656
  const pos = state?.position;
303
657
  if (!pos || state?.floorKnown !== true) return;
304
- if (state.floorNo !== selectedFloor.value) return;
658
+ if (!stacked.value && state.floorNo !== selectedFloor.value) return;
305
659
 
306
- const base = projectPoint(pos.x, pos.y, 0, view);
307
- const top = projectPoint(pos.x, pos.y, 0.9, view);
660
+ // Stacked, the robot stands on its own storey.
661
+ const z = stacked.value ? elevations.value.get(Number(state.floorNo)) ?? 0 : 0;
662
+ const base = projectPoint(pos.x, pos.y, z, view);
663
+ const top = projectPoint(pos.x, pos.y, z + 0.9, view);
308
664
 
309
665
  ctx.beginPath();
310
666
  ctx.moveTo(base.x, base.y);
@@ -331,7 +687,380 @@ function toggleTilt() {
331
687
  draw();
332
688
  }
333
689
 
690
+ /* ------------------------------------------------------------------- edit */
691
+
692
+ const editing = ref(false);
693
+ const tool = ref<"select" | "door" | "lift">("select");
694
+ const selected = ref<{ kind: "door" | "lift"; index: number } | null>(null);
695
+ const pendingDoorStart = ref<TMapPointM | null>(null);
696
+ const saving = ref(false);
697
+ const editError = ref("");
698
+ const confirmRemove = ref(false);
699
+ let dragging: { kind: "door" | "lift"; index: number; last: TMapPointM } | null = null;
700
+
701
+ const toolOptions = [
702
+ { label: "Select / move", value: "select" },
703
+ { label: "Add door", value: "door" },
704
+ { label: "Add lift shaft", value: "lift" },
705
+ ];
706
+ const doorTypes = [
707
+ { title: "Hinged", value: "hinged" },
708
+ { title: "Sliding", value: "sliding" },
709
+ ];
710
+
711
+ const toolHint = computed(() => {
712
+ if (tool.value === "door") {
713
+ return pendingDoorStart.value ? "Click where the door ends." : "Click where the door starts.";
714
+ }
715
+ if (tool.value === "lift") return "Click the middle of the lift shaft.";
716
+ return "Click a door or lift to select it; drag to move it.";
717
+ });
718
+
719
+ const selectedFeature = computed<TMapDoor | TMapLift | null>(() => {
720
+ const s = selected.value;
721
+ if (!s) return null;
722
+ return (s.kind === "door" ? doors.value[s.index] : lifts.value[s.index]) ?? null;
723
+ });
724
+
725
+ /* The selected door's type and the selected lift's floors, as plain models. */
726
+ const doorType = computed<string>({
727
+ get: () => (selected.value?.kind === "door" ? doors.value[selected.value.index]?.type ?? "hinged" : "hinged"),
728
+ set: (v) => {
729
+ const s = selected.value;
730
+ if (s?.kind === "door" && doors.value[s.index]) doors.value[s.index].type = v === "sliding" ? "sliding" : "hinged";
731
+ },
732
+ });
733
+ const liftFloors = computed<number[]>({
734
+ get: () => (selected.value?.kind === "lift" ? lifts.value[selected.value.index]?.floors ?? [] : []),
735
+ set: (v) => {
736
+ const s = selected.value;
737
+ if (s?.kind === "lift" && lifts.value[s.index]) {
738
+ lifts.value[s.index].floors = [...new Set(v.map(Number))].sort((a, b) => a - b);
739
+ draw();
740
+ }
741
+ },
742
+ });
743
+
744
+ /** The selected floor's saved height, editable. Blank = one storey above. */
745
+ const currentHeight = computed<number | string>({
746
+ get: () => (selectedFloor.value !== null ? heights.value[selectedFloor.value] ?? "" : ""),
747
+ set: (v) => {
748
+ if (selectedFloor.value === null) return;
749
+ const n = typeof v === "number" ? v : parseFloat(String(v));
750
+ heights.value = { ...heights.value, [selectedFloor.value]: Number.isFinite(n) ? n : undefined };
751
+ },
752
+ });
753
+
754
+ function startEditing() {
755
+ editing.value = true;
756
+ editError.value = "";
757
+ confirmRemove.value = false;
758
+ tool.value = "select";
759
+ selected.value = null;
760
+ tilted.value = false;
761
+ if (stacked.value) selectedFloor.value = realFloorOptions.value[0]?.value ?? null;
762
+ else draw();
763
+ }
764
+
765
+ function stopEditing() {
766
+ editing.value = false;
767
+ selected.value = null;
768
+ pendingDoorStart.value = null;
769
+ dragging = null;
770
+ draw();
771
+ }
772
+
773
+ function cancelEditing() {
774
+ applySaved(savedMap.value);
775
+ stopEditing();
776
+ }
777
+
778
+ function worldAt(e: PointerEvent): TMapPointM | null {
779
+ const canvas = canvasEl.value;
780
+ if (!canvas || !lastView) return null;
781
+ const r = canvas.getBoundingClientRect();
782
+ return unprojectPoint(e.clientX - r.left, e.clientY - r.top, lastView, 0);
783
+ }
784
+
785
+ /** The feature under the pointer on this floor, lifts first (they are bigger). */
786
+ function hitTest(p: TMapPointM): { kind: "door" | "lift"; index: number } | null {
787
+ const tolerance = lastView ? 10 / lastView.zoom : 0.5;
788
+ const floor = selectedFloor.value;
789
+ const li = lifts.value.findIndex((l) => l.floors.includes(floor ?? NaN) && insideLift(p, l));
790
+ if (li >= 0) return { kind: "lift", index: li };
791
+ const di = doors.value.findIndex(
792
+ (d) => d.floorNo === floor && distanceToSegment(p, d.start, d.end) <= tolerance,
793
+ );
794
+ return di >= 0 ? { kind: "door", index: di } : null;
795
+ }
796
+
797
+ const round = (n: number) => Math.round(n * 100) / 100;
798
+ const roundPoint = (p: TMapPointM) => ({ x: round(p.x), y: round(p.y) });
799
+
800
+ function onPointerDown(e: PointerEvent) {
801
+ if (!editing.value || selectedFloor.value === null) return;
802
+ const p = worldAt(e);
803
+ if (!p) return;
804
+ editError.value = "";
805
+
806
+ if (tool.value === "door") {
807
+ const start = pendingDoorStart.value;
808
+ if (!start) {
809
+ pendingDoorStart.value = roundPoint(p);
810
+ } else {
811
+ pendingDoorStart.value = null;
812
+ if (Math.hypot(p.x - start.x, p.y - start.y) >= 0.3) {
813
+ doors.value.push({
814
+ name: nextFeatureName(doors.value.map((d) => d.name), "door"),
815
+ floorNo: selectedFloor.value,
816
+ type: "hinged",
817
+ start,
818
+ end: roundPoint(p),
819
+ });
820
+ selected.value = { kind: "door", index: doors.value.length - 1 };
821
+ } else {
822
+ editError.value = "A door must be at least 30 cm wide.";
823
+ }
824
+ }
825
+ draw();
826
+ return;
827
+ }
828
+
829
+ if (tool.value === "lift") {
830
+ const floors = realFloorOptions.value.map((f) => f.value);
831
+ if (floors.length < 2) {
832
+ editError.value = "A lift shaft needs at least two floors on this robot's map.";
833
+ return;
834
+ }
835
+ lifts.value.push({
836
+ name: nextFeatureName(lifts.value.map((l) => l.name), "lift"),
837
+ ...roundPoint(p),
838
+ widthM: 2,
839
+ depthM: 2,
840
+ floors,
841
+ });
842
+ selected.value = { kind: "lift", index: lifts.value.length - 1 };
843
+ tool.value = "select";
844
+ draw();
845
+ return;
846
+ }
847
+
848
+ selected.value = hitTest(p);
849
+ if (selected.value) {
850
+ dragging = { ...selected.value, last: p };
851
+ canvasEl.value?.setPointerCapture?.(e.pointerId);
852
+ }
853
+ draw();
854
+ }
855
+
856
+ function onPointerMove(e: PointerEvent) {
857
+ if (!dragging) return;
858
+ const p = worldAt(e);
859
+ if (!p) return;
860
+ const dx = p.x - dragging.last.x;
861
+ const dy = p.y - dragging.last.y;
862
+ dragging.last = p;
863
+ if (dragging.kind === "lift") {
864
+ const lift = lifts.value[dragging.index];
865
+ lift.x = round(lift.x + dx);
866
+ lift.y = round(lift.y + dy);
867
+ } else {
868
+ const door = doors.value[dragging.index];
869
+ door.start = roundPoint({ x: door.start.x + dx, y: door.start.y + dy });
870
+ door.end = roundPoint({ x: door.end.x + dx, y: door.end.y + dy });
871
+ }
872
+ draw();
873
+ }
874
+
875
+ function onPointerUp() {
876
+ dragging = null;
877
+ }
878
+
879
+ function removeSelected() {
880
+ const s = selected.value;
881
+ if (!s) return;
882
+ if (s.kind === "door") doors.value.splice(s.index, 1);
883
+ else lifts.value.splice(s.index, 1);
884
+ selected.value = null;
885
+ draw();
886
+ }
887
+
888
+ /** What gets saved. Drawn walls and zones already on the map are kept as they are. */
889
+ function payload() {
890
+ const savedLevels: Array<Record<string, any>> = savedMap.value?.levels ?? [];
891
+ const floorNos = [
892
+ ...new Set([...maps.value.map((m) => Number(m.floorNo)), ...savedLevels.map((l) => Number(l.floorNo))]),
893
+ ].sort((a, b) => a - b);
894
+
895
+ const levels = floorNos.map((floorNo) => {
896
+ const saved = savedLevels.find((l) => Number(l.floorNo) === floorNo) ?? {};
897
+ const robotMap = maps.value.find((m) => Number(m.floorNo) === floorNo);
898
+ const level: Record<string, any> = {
899
+ floorNo,
900
+ name: robotMap?.mapName?.trim() || saved.name || "",
901
+ };
902
+ if (saved.walls?.length) level.walls = saved.walls;
903
+ if (saved.zones?.length) level.zones = saved.zones;
904
+ const h = heights.value[floorNo];
905
+ if (typeof h === "number" && Number.isFinite(h)) level.elevationM = h;
906
+ return level;
907
+ });
908
+
909
+ return {
910
+ name: savedMap.value?.name || `${props.robotName || "Robot"} building`,
911
+ levels,
912
+ doors: doors.value.map((d) => ({ ...d, name: d.name.trim() || "Door" })),
913
+ lifts: lifts.value.map((l) => ({ ...l, name: l.name.trim() || "Lift" })),
914
+ };
915
+ }
916
+
917
+ async function save() {
918
+ const body = payload();
919
+ const short = body.lifts.find((l) => l.floors.length < 2);
920
+ if (short) {
921
+ editError.value = `${short.name} must stop at two floors or more.`;
922
+ return;
923
+ }
924
+ saving.value = true;
925
+ editError.value = "";
926
+ try {
927
+ if (savedMap.value?._id) {
928
+ await updateBuildingMap(String(savedMap.value._id), { ...body, version: savedMap.value.version });
929
+ savedMap.value = await getBuildingMap(String(savedMap.value._id));
930
+ } else {
931
+ const res = await createBuildingMap({ ...body, robotId: props.robotId });
932
+ savedMap.value = await getBuildingMap(String(res.id));
933
+ }
934
+ applySaved(savedMap.value);
935
+ stopEditing();
936
+ // Heights may have changed the stack.
937
+ if (stacked.value) await buildLevel();
938
+ pollLifts();
939
+ } catch (e) {
940
+ editError.value = robotErrorMessage(e, "Could not save the layout.");
941
+ } finally {
942
+ saving.value = false;
943
+ }
944
+ }
945
+
946
+ let confirmTimer: ReturnType<typeof setTimeout> | undefined;
947
+ async function removeSaved() {
948
+ if (!savedMap.value?._id) return;
949
+ if (!confirmRemove.value) {
950
+ confirmRemove.value = true;
951
+ clearTimeout(confirmTimer);
952
+ confirmTimer = setTimeout(() => (confirmRemove.value = false), 4000);
953
+ return;
954
+ }
955
+ saving.value = true;
956
+ try {
957
+ await deleteBuildingMap(String(savedMap.value._id));
958
+ savedMap.value = null;
959
+ liftQueue.value = [];
960
+ applySaved(null);
961
+ stopEditing();
962
+ } catch (e) {
963
+ editError.value = robotErrorMessage(e, "Could not remove the layout.");
964
+ } finally {
965
+ saving.value = false;
966
+ confirmRemove.value = false;
967
+ }
968
+ }
969
+
970
+ /* ------------------------------------------------------------------ lifts */
971
+
972
+ const liftQueue = ref<Array<Record<string, any>>>([]);
973
+ const liftError = ref("");
974
+ const requesting = ref(false);
975
+ const requestFrom = ref<Record<string, number>>({});
976
+ const requestTo = ref<Record<string, number>>({});
977
+
978
+ const thisRobotWaiting = computed(() =>
979
+ liftQueue.value.some(
980
+ (l) =>
981
+ String(l.active?.robotId ?? "") === props.robotId ||
982
+ (l.queue ?? []).some((q: any) => String(q.robotId) === props.robotId),
983
+ ),
984
+ );
985
+
986
+ async function pollLifts() {
987
+ const id = savedMap.value?._id;
988
+ if (!id || !savedMap.value?.lifts?.length || editing.value) return;
989
+ try {
990
+ const res = await getLiftQueue(String(id));
991
+ liftQueue.value = res?.items ?? [];
992
+ liftError.value = "";
993
+ for (const lift of liftQueue.value) {
994
+ requestFrom.value[lift.liftName] ??= lift.floors?.[0];
995
+ requestTo.value[lift.liftName] ??= lift.floors?.[lift.floors.length - 1];
996
+ }
997
+ if (stacked.value) draw();
998
+ } catch (e) {
999
+ liftError.value = robotErrorMessage(e, "Could not read the lift queue.");
1000
+ }
1001
+ }
1002
+
1003
+ async function askForLift(lift: Record<string, any>) {
1004
+ if (!savedMap.value?._id) return;
1005
+ requesting.value = true;
1006
+ liftError.value = "";
1007
+ try {
1008
+ await requestLift(String(savedMap.value._id), lift.liftName, {
1009
+ robotId: props.robotId,
1010
+ fromFloor: Number(requestFrom.value[lift.liftName]),
1011
+ toFloor: Number(requestTo.value[lift.liftName]),
1012
+ });
1013
+ await pollLifts();
1014
+ } catch (e) {
1015
+ liftError.value = robotErrorMessage(e, "Could not request the lift.");
1016
+ } finally {
1017
+ requesting.value = false;
1018
+ }
1019
+ }
1020
+
1021
+ async function release(row: Record<string, any>) {
1022
+ liftError.value = "";
1023
+ try {
1024
+ await releaseLiftSession(String(row._id));
1025
+ await pollLifts();
1026
+ } catch (e) {
1027
+ liftError.value = robotErrorMessage(e, "Could not release the lift.");
1028
+ }
1029
+ }
1030
+
1031
+ function motionLabel(state: any) {
1032
+ return ["stopped", "going up", "going down", "position unknown"][state?.motionState] ?? "position unknown";
1033
+ }
1034
+ function doorLabel(state: any) {
1035
+ return ["closed", "moving", "open"][state?.doorState] ?? "unknown";
1036
+ }
1037
+ function phaseLabel(lift: any) {
1038
+ const a = lift.active;
1039
+ switch (lift.phase) {
1040
+ case "to-pickup":
1041
+ return `Going to floor ${a?.fromFloor} to collect ${a?.robotName}.`;
1042
+ case "boarding":
1043
+ return `${a?.robotName} is getting in.`;
1044
+ case "to-destination":
1045
+ return `Carrying ${a?.robotName} to floor ${a?.toFloor}.`;
1046
+ case "arrived":
1047
+ return `${a?.robotName} can get out at floor ${a?.toFloor}.`;
1048
+ default:
1049
+ return "Free.";
1050
+ }
1051
+ }
1052
+ function untilLabel(when: string) {
1053
+ const ms = new Date(when).getTime() - Date.now();
1054
+ if (!Number.isFinite(ms) || ms <= 0) return "now";
1055
+ const s = Math.round(ms / 1000);
1056
+ return `in ${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
1057
+ }
1058
+
1059
+ /* ---------------------------------------------------------------- watches */
1060
+
334
1061
  watch(selectedFloor, async () => {
1062
+ selected.value = null;
1063
+ pendingDoorStart.value = null;
335
1064
  if (!maps.value.length) return;
336
1065
  loading.value = true;
337
1066
  error.value = "";
@@ -344,16 +1073,27 @@ watch(selectedFloor, async () => {
344
1073
  }
345
1074
  });
346
1075
 
1076
+ watch(tool, () => {
1077
+ pendingDoorStart.value = null;
1078
+ draw();
1079
+ });
1080
+
347
1081
  watch(() => props.robotState, draw, { deep: true });
348
1082
 
349
1083
  let onResize: (() => void) | undefined;
1084
+ let pollTimer: ReturnType<typeof setInterval> | undefined;
350
1085
  onMounted(() => {
351
1086
  load();
352
1087
  onResize = () => draw();
353
1088
  window.addEventListener("resize", onResize);
1089
+ // The queue moves on its own (leases run out, the car travels), so it is
1090
+ // re-read while the layout is open - and only then.
1091
+ pollTimer = setInterval(pollLifts, 3000);
354
1092
  });
355
1093
  onBeforeUnmount(() => {
356
1094
  if (onResize) window.removeEventListener("resize", onResize);
1095
+ clearInterval(pollTimer);
1096
+ clearTimeout(confirmTimer);
357
1097
  });
358
1098
  </script>
359
1099
 
@@ -364,10 +1104,14 @@ onBeforeUnmount(() => {
364
1104
  height: 460px;
365
1105
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.02), rgba(0, 0, 0, 0.06));
366
1106
  }
1107
+ .robot-map3d--placing .robot-map3d__canvas {
1108
+ cursor: crosshair;
1109
+ }
367
1110
  .robot-map3d__canvas {
368
1111
  display: block;
369
1112
  width: 100%;
370
1113
  height: 100%;
1114
+ touch-action: none;
371
1115
  }
372
1116
  .robot-map3d__overlay {
373
1117
  position: absolute;
@@ -378,5 +1122,24 @@ onBeforeUnmount(() => {
378
1122
  justify-content: center;
379
1123
  text-align: center;
380
1124
  padding: 24px;
1125
+ pointer-events: none;
1126
+ }
1127
+ .robot-map3d__overlay :deep(button) {
1128
+ pointer-events: auto;
1129
+ }
1130
+ .robot-map3d__editbar,
1131
+ .robot-map3d__panel {
1132
+ display: flex;
1133
+ flex-wrap: wrap;
1134
+ align-items: center;
1135
+ gap: 12px;
1136
+ border-bottom: 1px solid rgba(0, 0, 0, 0.08);
1137
+ }
1138
+ .robot-map3d__panel {
1139
+ border-top: 1px solid rgba(0, 0, 0, 0.08);
1140
+ border-bottom: none;
1141
+ }
1142
+ .robot-map3d__lifts {
1143
+ border-top: 1px solid rgba(0, 0, 0, 0.08);
381
1144
  }
382
1145
  </style>