@margoengine/labels 0.0.0-stage → 1.0.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.
package/README.md CHANGED
@@ -1,3 +1,507 @@
1
- # Temporary Holding Version
1
+ # @margoengine/labels
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Import `margoengine/labels` from the `margoengine` package, or `@margoengine/labels` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ HTML labels and CSS 3D objects kept in register with a Margo Engine canvas.
6
+
7
+ Build from source with `npm run build` in `packages/labels`.
8
+
9
+ ```ts
10
+ import {LabelRenderer} from 'margoengine/labels';
11
+ import {Engine} from 'margoengine/core';
12
+ import {box} from 'margoengine/core';
13
+ const makeButton = () => Object.assign(document.createElement('button'), {textContent: 'Open'});
14
+ const isBlocked = (from: readonly number[], to: readonly number[]) => to[1] < from[1] - 10; // your own ray test
15
+ const engine = await Engine.create(document.querySelector('canvas')!);
16
+ const pump = engine.createMesh().setGeometry(box());
17
+ const screen = engine.createMesh().setGeometry(box());
18
+
19
+ const labels = LabelRenderer.attach(engine);
20
+
21
+ // A 2D label 0.8 units above a mesh origin (mesh-local offset, like a child object).
22
+ const name = document.createElement('div');
23
+ name.textContent = 'Pump 3';
24
+ const label = labels.add(name, {mesh: pump, offset: [0, 0.8, 0], anchor: [0.5, 1], distanceScale: {reference: 6, min: 0.5, max: 1.5}});
25
+
26
+ // An interactive label at a world point.
27
+ const button = labels.add(makeButton(), {position: [2, 1, 0], pointerEvents: 'auto'});
28
+
29
+ // A CSS 3D panel that rotates and scales with its mesh: 1 CSS pixel = 0.01 world units.
30
+ const manual = Object.assign(document.createElement('div'), {textContent: 'Pump manual'});
31
+ const panel = labels.add3D(manual, {mesh: screen, pixelScale: 0.005});
32
+
33
+ // Custom occlusion, for example a BVH raycast from the camera.
34
+ labels.occlude = (label, info) => isBlocked(engine.camera.position, info.world); // your own test
35
+
36
+ engine.render();
37
+ label.remove();
38
+ labels.dispose(); // Direct disposal detaches the renderer.
39
+ engine.dispose();
40
+ // engine.removePlugin(labels.name) also disposes the renderer.
41
+ ```
42
+
43
+ `attach` uses plugin name `margoengine-labels` by default. If a subsystem such as
44
+ sciviz Axes already attached it, reuse that LabelRenderer from `engine.plugins`,
45
+ or attach your annotations with an unused name, for example
46
+ `LabelRenderer.attach(engine, {name: 'annotations', layout: callouts})`.
47
+ A duplicate name throws a MargoError with linked code `state`, names the collision and explains these choices before
48
+ creating an overlay; the existing renderer, layout and labels are preserved.
49
+
50
+ ## How it works
51
+
52
+ - **Overlay.** `setup` inserts one `div` right after the canvas (or into `parent`), absolutely positioned over the canvas content box with `pointer-events: none` and `overflow: hidden`. Each frame it measures the canvas and corrects the overlay offset, so it stays aligned inside any containing block, border or padding, and under a CSS `scale()` on the canvas's ancestors (see [Scaled pages](#scaled-pages)).
53
+ - **Projection.** A frame pass (order 1000, after the scene) projects every label with `camera.matrix`: reversed-Z WebGPU clip space (z from 0 to w) or WebGL2 clip space (z from -w to w), chosen from `engine.backend`. Labels behind the camera are always hidden; labels outside the frustum are hidden unless `frustumCulling: false`. Mesh labels read `engineRuntime(engine).store.matrices`, so they follow parents, rotation and scale, and hide while the mesh or an ancestor is hidden (`followVisibility`) or once the mesh is disposed.
54
+ - **Placement.** `transform: translate(x, y) [scale(s)] translate(-anchorX%, -anchorY%)` with `transform-origin: 0 0`, so the anchor point of the element sits exactly on the projected point, with or without distance scaling.
55
+ - **Depth order.** Visible labels are sorted by distance to the camera every frame and get `z-index` 1..n, nearest on top. `sort: false` leaves a label's z-index alone.
56
+ - **CSS 3D.** A viewer element gets `perspective: (height / 2) / tan(fov / 2)` and a `preserve-3d` camera element gets `translateZ(perspective) matrix3d(view with Y flipped) translate(width / 2, height / 2)`. Each object gets `translate(-50%, -50%) matrix3d(world * scale(pixelScale) with Y flipped)`. The view matrix is rebuilt from `camera.position` and `camera.target` with the same Y-up look-at the core camera uses. CSS cannot clip at the near plane, so the renderer does: an object partly behind it is cut there with a `clip-path` (see [Depth with CSS 3D objects](#depth-with-css-3d-objects)), and one wholly behind it is hidden.
57
+ - **Orthographic cameras.** When `camera.matrix` has a constant clip w (for example with `CameraProjection` from `@margoengine/cameras`, which the package does not depend on), the viewer gets `perspective: none` and the camera element `orthographicCSSTransform(matrix, width, height, backend)`: the clip matrix scaled to CSS pixels around the viewport centre, Y flipped, with Z scaled like Y so CSS depth sorting follows the camera. Objects are cut or hidden at the near plane the same way. 2D labels need nothing special; `distanceScale` uses the distance at which a perspective camera with the same fov shows the same zoom, so labels grow when zooming in and do not change with depth. `isOrthographic(matrix)` is exported.
58
+ - **Minimal DOM writes.** Every style property is cached per element and written only when its string changes; `renderer.writes` reports how many writes the last update made (0 on a static frame).
59
+ - **Engine views.** `new LabelRenderer({view})` (or `labels.view = {camera, viewport, pixels?}`) places labels through that view's camera inside its rectangle, clipped to it; hook coordinates are then relative to the view's corner. One renderer per view.
60
+ - **Occlusion hook.** Depth-buffer occlusion is not built in. `occlude(label, {x, y, depth, distance, world})` on the renderer or a label returns true to hide that label this frame; the per-label hook overrides the renderer one.
61
+
62
+ ## Moving a label
63
+
64
+ `label.position` is getter-only. Assignment throws TypeError with code `transform`
65
+ and the same message as core mesh refs: `Retained vector: use a transform setter`,
66
+ followed by the help link. `setPosition` validates and copies a world position,
67
+ and stops following a mesh:
68
+
69
+ ```ts
70
+ import { Engine } from '@margoengine/core';
71
+ import { LabelRenderer } from '@margoengine/labels';
72
+
73
+ const engine = await Engine.create(document.querySelector('canvas')!);
74
+ const labels = LabelRenderer.attach(engine);
75
+ const label = labels.add(document.createElement('span'), { position: [0, 1, 0] });
76
+ label.element.textContent = 'Valve';
77
+ label.setPosition([2, 1, 0]);
78
+ engine.render();
79
+ engine.dispose();
80
+ ```
81
+
82
+ ## Pinning to a box: boxAnchorPoint
83
+
84
+ `boxAnchorPoint(min, max, anchor, matrix?)` returns the world position of a box corner, edge, face centre or centre.
85
+ `anchor` is a face name (`'left'`, `'right'`, `'bottom'`, `'top'`, `'back'`, `'front'`), `'center'` (the default) or a
86
+ `[x, y, z]` triple of -1 (min side), 0 (middle) and 1 (max side), so `[1, 1, 1]` is the max corner. Pass the box's
87
+ world matrix and the point follows a moved, rotated or scaled box. A bad box or anchor throws a RangeError that says
88
+ how to fix it.
89
+
90
+ ```ts
91
+ import { Engine } from '@margoengine/core';
92
+ import { LabelRenderer, boxAnchorPoint } from '@margoengine/labels';
93
+
94
+ const engine = await Engine.create(document.querySelector('canvas')!);
95
+ const labels = LabelRenderer.attach(engine);
96
+ const label = labels.add(document.createElement('span'));
97
+ label.element.textContent = 'Roof';
98
+ const min: [number, number, number] = [-1, 0, -1];
99
+ const max: [number, number, number] = [1, 2, 1];
100
+ label.setPosition(boxAnchorPoint(min, max, 'top'));
101
+ engine.render();
102
+ engine.dispose();
103
+ ```
104
+
105
+ ## Pinning to a deformed mesh: Hotspot
106
+
107
+ `Hotspot` is a fixed point inside one triangle of a skinned or morphed mesh, given as a triangle index and
108
+ barycentric weights of its three corners. `worldPosition()` blends the triangle's posed corners at the current pose,
109
+ so the point rides the surface as it bends; `project(camera.matrix, width, height)` gives CSS pixels, and `pin(label)`
110
+ moves a label to it. Any source with `posePickingGeometry()` works, such as `skin.picking` from
111
+ `@margoengine/animation` (the same source `Raycaster.intersectPosed` reads, so its posed vertices are cached per pose).
112
+ `Hotspot.fromHit(source, hit)` takes `primitiveIndex`, `faceIndex` and `barycoord` from a pick hit. Weights must be 0 or
113
+ more and sum to 1; a bad face, primitive or weight throws a RangeError that names the fix.
114
+
115
+ ```ts
116
+ import { Hotspot } from '@margoengine/labels';
117
+
118
+ const triangle = new Float32Array(60); // three stride-20 vertices, xyz first
119
+ triangle.set([2, 0, 0], 20);
120
+ triangle.set([0, 2, 0], 40);
121
+ const snapshot = { vertices: triangle, indices: new Uint32Array([0, 1, 2]), matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] };
122
+ const hotspot = new Hotspot({ posePickingGeometry: () => [snapshot] }, { face: 0, barycentric: [0.5, 0.25, 0.25] });
123
+ console.log(hotspot.worldPosition()); // [0.5, 0.5, 0]
124
+ snapshot.vertices[42] = 4; // the pose bends the third corner up
125
+ console.log(hotspot.worldPosition()); // [0.5, 0.5, 1]
126
+ ```
127
+
128
+ ## Scaled pages
129
+
130
+ A CSS scale on an element around the canvas (a zoomed preview, a slide, a fitted dashboard tile) scales what the browser draws but not the `left` and `top` the overlay is placed with. Each update the renderer reads the overlay's drawn width against the width it gave it, converts its correction by that scale, and lands on the canvas content box in the same update at any scale. An overlay in another `parent`, outside the scaled element, is scaled itself (`transform: scale(k)`, origin at its corner) so a CSS pixel of the labels is a CSS pixel of the canvas.
131
+
132
+ ```ts
133
+ import {LabelRenderer} from 'margoengine/labels';
134
+ import {Engine} from 'margoengine/core';
135
+ const canvas = document.querySelector('canvas')!;
136
+ const engine = await Engine.create(canvas);
137
+
138
+ canvas.parentElement!.style.transformOrigin = '0 0';
139
+ canvas.parentElement!.style.transform = 'scale(0.75)'; // a zoomed-out preview
140
+ const tag = (text: string) => Object.assign(document.createElement('div'), {textContent: text});
141
+ const beside = LabelRenderer.attach(engine); // beside the canvas: shares its scale
142
+ beside.add(tag('Pump 3'), {position: [0, 1, 0]});
143
+ const outside = LabelRenderer.attach(engine, {parent: document.body, name: 'labels-outside'}); // scaled to match
144
+ outside.add(tag('Valve'), {position: [1, 0, 0]});
145
+ ```
146
+
147
+ - **Beside the canvas** (the default) the overlay shares the canvas's ancestors and needs no scale of its own; no `transform` is written on it.
148
+ - **Another parent.** The canvas's scale is its drawn width over `offsetWidth`, which the browser rounds to whole pixels, so a canvas of fractional CSS width is matched to about half a pixel over its width.
149
+ - **Not followed.** Rotations and skews on the ancestors, and a transform on the canvas element itself.
150
+
151
+ ## Decluttering
152
+
153
+ `@margoengine/labels/declutter` hides or moves labels that would overlap, so a dense scene stays readable. Labels are taken by `priority` (higher first), then, among equal priorities, the ones shown at the last update (so they do not swap places as the camera moves), then nearer ones. Each is placed with its own anchor, or the first of `positions` that overlaps no label placed before it, and is hidden when none is free.
154
+
155
+ ```ts
156
+ import {LabelRenderer} from 'margoengine/labels';
157
+ import {Declutter, eightPositions} from 'margoengine/labels/declutter';
158
+ import {Engine} from 'margoengine/core';
159
+ const engine = await Engine.create(document.querySelector('canvas')!);
160
+
161
+ const declutter = new Declutter({positions: eightPositions, padding: 4});
162
+ const labels = LabelRenderer.attach(engine, {layout: declutter});
163
+ for (const [name, x, priority] of [['Main valve', 0, 2], ['Drain', 0.05, 1], ['Gauge', 0.1, 0]] as const) {
164
+ const element = document.createElement('div');
165
+ element.textContent = name;
166
+ labels.add(element, {position: [x, 1, 0], priority});
167
+ }
168
+ // After a frame: declutter.hidden labels had no free position, declutter.moved were moved around their point.
169
+ ```
170
+
171
+ - **Positions.** `eightPositions` tries above right, above left, below left, below right, right, above, left and below the point, in that order (the ranking in Figure 1 of Christensen, Marks and Shieber 1995); `fourPositions` the four corners. Without `positions` an overlapping label is hidden.
172
+ - **Sizes.** Each element is measured once (`offsetWidth`, `offsetHeight`) and scaled by its `distanceScale`; call `label.remeasure()` after its text or style changes its size.
173
+ - **Cost.** The overlap test buckets placed boxes in a grid of `cell` pixels (default 64), so each label tests only its neighbours. A still frame writes nothing to the DOM.
174
+ - **Own layouts.** `layout` takes any `{arrange(labels, context)}`: `context.size(label)`, `context.hide(label)` and `context.place(label, anchor)` run before anything is drawn, with `label.screen`, `label.distance` and `label.scale` already set for the update.
175
+
176
+ | Declutter option | Default |
177
+ | --- | --- |
178
+ | `padding` (free gap between labels, CSS px) | 2 |
179
+ | `positions` (anchors tried after the label's own) | none: hide |
180
+ | `inside` (boxes must stay inside the view) | false |
181
+ | `sticky` (labels shown last time win ties) | true |
182
+ | `cell` (grid cell, CSS px) | 64 |
183
+
184
+ ## Leader lines and callouts
185
+
186
+ `@margoengine/labels/callouts` draws leader lines, for CAD and product annotations: move a label off its point with `screenOffset` (CSS pixels, x right, y down) and `Callouts` draws a line from the projected point to the nearest point of the label's box, with a dot on the point. It is a `layout`; wrap `Declutter` with its `layout` option to remove overlaps first.
187
+
188
+ ```ts
189
+ import {LabelRenderer} from 'margoengine/labels';
190
+ import {Callouts} from 'margoengine/labels/callouts';
191
+ import {Declutter} from 'margoengine/labels/declutter';
192
+ import {Engine} from 'margoengine/core';
193
+ const engine = await Engine.create(document.querySelector('canvas')!);
194
+
195
+ const callouts = new Callouts({layout: new Declutter({padding: 4}), color: '#ffd166', dot: 3});
196
+ const labels = LabelRenderer.attach(engine, {layout: callouts});
197
+ const notes = [
198
+ ['Inlet flange', [-0.6, 0.4, 0], [-90, -50]],
199
+ ['Bolt M8 x 4', [0.2, 0.55, 0.1], [80, -60]],
200
+ ['Seal face', [0.5, -0.2, 0], [90, 40]],
201
+ ] as const;
202
+ for (const [name, position, screenOffset] of notes) {
203
+ const element = document.createElement('div');
204
+ element.textContent = name;
205
+ labels.add(element, {position, screenOffset});
206
+ }
207
+ // After a frame: callouts.lines lines are drawn; callouts.svg holds them.
208
+ ```
209
+
210
+ - **Which labels.** Every shown label whose box does not cover its projected point: one moved with `screenOffset`, or placed off its point by the wrapped layout. Lines shorter than `minLength` are not drawn, so a label `Declutter` placed at a corner of its point gets none. Labels on their point are not even measured.
211
+ - **Wrapped layouts.** `layout` runs first and its decisions stand: a label it hides gets no line, one it places with another anchor gets its line from that box. `Declutter` tests the moved boxes; it does not keep lines from crossing labels or each other.
212
+ - **Drawing.** One `<svg>` sits first in the overlay, under every label, with `pointer-events: none`; each callout is a `<line>` and a `<circle>`. Attributes are written only when they change (`callouts.writes` is 0 on a still frame); the lines of hidden labels are hidden and those of removed labels deleted. `className` names the SVG for your own CSS, for example `.leaders line {stroke-dasharray: 4 2}`; `clear()` removes it.
213
+
214
+ | Callouts option | Default |
215
+ | --- | --- |
216
+ | `layout` (run first, decisions kept) | none |
217
+ | `color` (line and dot, any CSS colour) | `'currentColor'` |
218
+ | `width` (line width, CSS px) | 1 |
219
+ | `dot` (dot radius, CSS px; 0 for none) | 2 |
220
+ | `minLength` (shorter lines are not drawn, CSS px) | 2 |
221
+ | `className` (of the SVG) | none |
222
+
223
+ ## GPU label collections: /gpu
224
+
225
+ `GPULabelLayer` draws SDF text in the canvas, with no DOM element per label.
226
+ Importing the labels root does not load it; `create`/`attach` loads text support
227
+ lazily. `await GPULabelLayer.attach(engine, options)` creates and registers the
228
+ layer, or call `create(options)` and then `engine.use(layer)` yourself.
229
+ Creation checks `signal` before and after loading the font; passing a font
230
+ keeps font ownership with the caller.
231
+
232
+ ```ts
233
+ import {Engine} from '@margoengine/core';
234
+ import {GPULabelLayer} from '@margoengine/labels/gpu';
235
+
236
+ const canvas = document.createElement('canvas'); document.body.append(canvas);
237
+ const engine = await Engine.create(canvas, {camera: {position: [0, 0, 4]}});
238
+ const controller = new AbortController();
239
+ const layer = await GPULabelLayer.attach(engine, {signal: controller.signal});
240
+ layer.setLabels([
241
+ {text: 'Pump 3', position: [0, 0, 0], fontSize: 18, color: [1, 0.7, 0, 1], priority: 2},
242
+ {text: 'Outlet', position: [1, 0, 0], offset: [0, -12]},
243
+ ]);
244
+ engine.start();
245
+ // On teardown: layer.dispose(); engine.dispose(); canvas.remove();
246
+ ```
247
+
248
+ Label positions are world units; fontSize (16) and offset ([0, 0]) are CSS
249
+ pixels independent of camera distance and device pixel ratio. Color defaults
250
+ to white straight RGBA, visible to true, priority to 0. `setLabels` replaces
251
+ the borrowed collection; fields may be edited between frames. Higher priority
252
+ wins text-bound decluttering, with input order breaking ties. This is
253
+ screen annotation, without per-pixel occlusion by scene geometry.
254
+
255
+ | Layer option | Default | Meaning |
256
+ | --- | --- | --- |
257
+ | name / order | gpu-labels / 24 | Plugin name and frame-pass order |
258
+ | font | new Font() | Lazily loaded text font |
259
+ | declutter | true | Hide overlapping labels |
260
+ | cell / padding | 64 / 2 | Grid cell and label spacing, CSS pixels |
261
+ | atlasSize / maxPages | 1024 / 32 | Atlas side in texels and page cap, subject to GPU limits |
262
+ | signal | none | Cancel asynchronous creation |
263
+
264
+ `stats` reports labels, glyphs, hidden, comparisons and drawCalls for the
265
+ latest preparation/render. Glyphs across atlas pages share one instanced draw
266
+ per rendered view. `prepare(matrix, cssWidth, cssHeight, backend?)` returns
267
+ reused packed storage for headless layout inspection (backend defaults to
268
+ webgpu); copy it before another call. Atlas overflow and unsupported device
269
+ limits reject rather than silently dropping glyphs. Resources allocate lazily
270
+ on drawing, rebuild after device restoration, and are freed by `dispose()` or
271
+ `using`; the layer's label collection and CPU font data can be reused on
272
+ reattachment. Disposal detaches from the owning scene, including secondary
273
+ scenes. Native WebGPU, full compatibility and the WebGL2 preview have draw
274
+ paths; GPU glyphs do not become accessible HTML or interactive buttons.
275
+
276
+ ## Distance policies: /distance
277
+
278
+ `DistanceLabels` runs before an optional nested layout, so decluttering and
279
+ callout boxes see the final scale. It leaves `label.visible` alone. Defaults
280
+ show distances from 0 through Infinity (inclusive), opacity 1 and scale 1.
281
+ Each opacity/scale curve is `{near, nearValue, far, farValue}`: finite distances
282
+ must satisfy `0 <= near < far`; linear interpolation clamps to its endpoint
283
+ values outside that range. Opacity values are 0..1 and scale is nonnegative.
284
+ A zero opacity or scale hides the label even at an inclusive show boundary.
285
+
286
+ ```ts
287
+ import {Engine} from '@margoengine/core';
288
+ import {LabelRenderer} from '@margoengine/labels';
289
+ import {DistanceLabels, evaluateLabelDistance} from '@margoengine/labels/distance';
290
+ import {Declutter} from '@margoengine/labels/declutter';
291
+
292
+ const canvas = document.createElement('canvas'); document.body.append(canvas);
293
+ const engine = await Engine.create(canvas, {camera: {position: [0, 0, 4]}});
294
+ const distance = new DistanceLabels({layout: new Declutter()});
295
+ const labels = LabelRenderer.attach(engine, {layout: distance});
296
+ const element = Object.assign(document.createElement('span'), {textContent: 'Valve'});
297
+ element.style.opacity = '0.8';
298
+ const label = labels.add(element, {position: [0, 0, 0]});
299
+ const policy = {
300
+ near: 0, far: 20,
301
+ opacity: {near: 5, nearValue: 1, far: 20, farValue: 0},
302
+ scale: {near: 5, nearValue: 1, far: 20, farValue: 0.5},
303
+ };
304
+ distance.set(label, policy);
305
+ console.log(evaluateLabelDistance(10, policy)); // Same policy for a GPU consumer.
306
+ engine.start();
307
+ // On teardown: labels.dispose(); distance.dispose(); engine.dispose(); canvas.remove();
308
+ ```
309
+
310
+ `defaults` supplies the policy for labels without a `set(label, policy)`
311
+ override. Policies are validated and copied. Opacity multiplies the original
312
+ inline opacity and scale multiplies the renderer's distanceScale; projected
313
+ orthographic zoom behavior remains the renderer's. `delete(label)` restores
314
+ its opacity and drops the override. `clear`/`dispose` restores all managed
315
+ opacities and clears policies, without disposing the nested layout. Detach a
316
+ layout before clearing it if rendering continues. `evaluateLabelDistance`
317
+ returns `{opacity, scale, visible}` without DOM access and requires a finite,
318
+ nonnegative distance.
319
+
320
+ ## Screen-space clusters: /cluster
321
+
322
+ `ClusterLabels` forms connected components of projected anchors within
323
+ `radius` CSS pixels (default 40). A chain may span more than radius end to end.
324
+ Groups with at least `minCount` (2) show a count bubble at the centroid; their
325
+ original label handles remain in `clusters[i].members`, in input order. Camera
326
+ motion and projection zoom recompute the groups each update.
327
+
328
+ ```ts
329
+ import {Engine} from '@margoengine/core';
330
+ import {LabelRenderer} from '@margoengine/labels';
331
+ import {ClusterLabels} from '@margoengine/labels/cluster';
332
+ import {Declutter} from '@margoengine/labels/declutter';
333
+
334
+ const canvas = document.createElement('canvas'); document.body.append(canvas);
335
+ const engine = await Engine.create(canvas, {camera: {position: [0, 0, 4]}});
336
+ const clusters = new ClusterLabels({radius: 40, maxZoom: 8, layout: new Declutter()});
337
+ const labels = LabelRenderer.attach(engine, {layout: clusters});
338
+ for (let i = 0; i < 8; i++) {
339
+ const element = Object.assign(document.createElement('span'), {textContent: `Sensor ${i}`});
340
+ labels.add(element, {position: [i * 0.02, 0, 0]});
341
+ }
342
+ engine.render();
343
+ for (const group of clusters.clusters) {
344
+ group.element.style.background = '#384050';
345
+ group.element.onclick = () => console.log(group.members, group.count);
346
+ }
347
+ clusters.setZoom(9); // Logical application zoom; above maxZoom, show individual labels.
348
+ engine.start();
349
+ // On teardown: labels.dispose(); clusters.dispose(); engine.dispose(); canvas.remove();
350
+ ```
351
+
352
+ Logical `zoom` defaults to 0 and `maxZoom` to Infinity; they do not move the
353
+ camera. `setZoom` controls only this threshold. `className` defaults to
354
+ margo-label-cluster; bubbles have pointer-events auto and can be styled via
355
+ `clusters[i].element`. The nested layout sees only unclustered labels, not
356
+ bubbles. Each cluster also exposes x/y and zoom; `comparisons` counts exact
357
+ distance tests in the last update. Radius must be finite and >= 1, minCount
358
+ an integer >= 2. `clear`/`dispose` removes bubbles, leaving original labels and
359
+ the nested layout owned by their callers; a still-attached layout recreates
360
+ bubbles on its next update.
361
+
362
+ ## Routed external callouts: /callouts-route
363
+
364
+ `RoutedCallouts` places labels in a side column and may reorder their ports to
365
+ keep the angled-elbow leaders from crossing each other. This is distinct from
366
+ Callouts' direct straight leaders. Boxes must have nonzero finite measured
367
+ sizes; call `remeasure()` after changing text/styles. It does not solve
368
+ arbitrary obstacle avoidance through other scene objects.
369
+
370
+ ```ts
371
+ import {Engine} from '@margoengine/core';
372
+ import {LabelRenderer} from '@margoengine/labels';
373
+ import {RoutedCallouts, routeCalloutLeaders} from '@margoengine/labels/callouts-route';
374
+
375
+ const canvas = document.createElement('canvas');
376
+ canvas.style.cssText = 'width:640px;height:360px'; document.body.append(canvas);
377
+ const engine = await Engine.create(canvas, {camera: {position: [0, 0, 4]}});
378
+ const routes = new RoutedCallouts({side: 'right', gap: 16, color: '#ffd166'});
379
+ const labels = LabelRenderer.attach(engine, {layout: routes});
380
+ for (let i = 0; i < 3; i++) {
381
+ const element = Object.assign(document.createElement('span'), {textContent: `Port ${i}`});
382
+ element.style.cssText = 'display:block;width:72px;height:22px';
383
+ labels.add(element, {position: [0, i * 0.3, 0]});
384
+ }
385
+ console.log(routeCalloutLeaders([[10, 10], [20, 40]], [[100, 15], [100, 50]], 80));
386
+ engine.start();
387
+ // On teardown: labels.dispose(); routes.dispose(); engine.dispose(); canvas.remove();
388
+ ```
389
+
390
+ Defaults: side auto (more room), gap 16, padding 4, margin 8 CSS pixels,
391
+ color currentColor, stroke width 1, overflow true. Auto chooses one side for
392
+ the entire group. Overflow permits a column outside the view and temporarily
393
+ sets the overlay's overflow to visible; false throws if it cannot fit.
394
+ `routes` reports source index, assigned port index and three CSS-coordinate
395
+ points. `writes` counts changed SVG point attributes. `clear`/`dispose` removes
396
+ the SVG and restores the original overlay overflow.
397
+
398
+ The pure `routeCalloutLeaders(sources, ports, bendX)` requires equal counts of
399
+ finite 2D points, ports in one x column at distinct y values, and bendX strictly
400
+ between every source and that column. Empty inputs return []. Invalid inputs
401
+ throw RangeError. It returns routes in source order, allowing coincident
402
+ sources to share an origin without sharing leader segments. Near-collinear
403
+ orientation uses exact binary64 integer predicates. Recursive angular
404
+ partitions have worst-case O(n squared log n) sorting work; budget dense
405
+ annotation sets accordingly. No wall-clock performance claim is implied.
406
+
407
+ ## Ownership and core compatibility
408
+
409
+ `LabelRenderer.dispose()` detaches itself and removes its overlay and owned
410
+ label/CSS3D elements. Removing it from the engine has the same effect. It does
411
+ not dispose a caller-supplied layout: detach the renderer, then dispose or
412
+ clear DistanceLabels, ClusterLabels or RoutedCallouts yourself. `using` is
413
+ available for these helpers. Each renderer/layer needs its own plugin name;
414
+ reuse an existing renderer when sharing one overlay.
415
+
416
+ Built packages declare the core requirements checked at attachment. A
417
+ mismatched core rejects with linked MargoError code version; use matching
418
+ packages built from this repository. Merely importing an entry neither creates
419
+ an overlay nor loads GPU label fonts.
420
+
421
+
422
+ ## Depth with CSS 3D objects
423
+
424
+ CSS 3D objects are HTML in the overlay, so they sit above the canvas, and CSS perspective draws whatever is behind the camera inverted. The renderer measures each element once (`offsetWidth`, `offsetHeight`), works out how far each of its four corners is in front of the camera's near plane, and then shows it whole, cuts it at the plane with `clip-path: polygon(...)` in the element's own pixels, or hides it when no part is in front. A panel you walk through stays drawn up to the plane instead of vanishing. Scene geometry in front of an object is your `occlude` hook's call, as for labels.
425
+
426
+ ```ts
427
+ import {LabelRenderer} from 'margoengine/labels';
428
+ import {Engine} from 'margoengine/core';
429
+ const engine = await Engine.create(document.querySelector('canvas')!);
430
+ const isBlocked = (from: readonly number[], to: readonly number[]) => to[1] < from[1] - 10; // your own ray test
431
+
432
+ const labels = LabelRenderer.attach(engine);
433
+ const sign = document.createElement('div');
434
+ sign.textContent = 'Exit';
435
+ const panel = labels.add3D(sign, {
436
+ position: [0, 1, 0],
437
+ pixelScale: 0.01,
438
+ // Hide the panel while scene geometry is between it and the camera.
439
+ occlude: (object, info) => isBlocked(engine.camera.position, info.world),
440
+ });
441
+ // After a frame: panel.clipped is true while part of it is behind the near plane.
442
+ sign.textContent = 'Emergency exit';
443
+ panel.remeasure(); // its size changed: measure it again at the next update
444
+ ```
445
+
446
+ - **Cut, not hidden.** The cut is exact for the element's rectangle: its corners' distances from the plane are affine over the element, so the polygon is the rectangle clipped by one plane (3 to 5 points). Orthographic cameras cut at depth 0.
447
+ - **Writes.** `clip-path` is written only while an object is cut, and once more to clear it; a still frame writes nothing.
448
+ - **Sizes.** An element is measured once; call `object.remeasure()` after its content changes its size. An element that is not laid out yet measures 0 and is treated as its origin point.
449
+ - **Children.** `clip-path` flattens an element's own 3D children while it is cut (CSS grouping property); the object itself stays in the 3D scene.
450
+
451
+ ## API
452
+
453
+ | Export | Purpose |
454
+ | --- | --- |
455
+ | `LabelRenderer` | Engine plugin: `add(element, options)`, `add3D(element, options)`, `remove(item)`, `update()`, `occlude`, `layout`, `root`, `writes`, `dispose()` |
456
+ | `Label` | `element`, `visible`, `onScreen`, `screen` (x, y, depth, w), `world`, `distance`, `setMesh`, `setPosition`, `setOffset`, `anchor`, `screenOffset`, `distanceScale`, `frustumCulling`, `followVisibility`, `sort`, `priority`, `scale`, `placedAnchor`, `remeasure()`, `occlude`, `remove()` |
457
+ | `CSS3DObject` | `element`, `visible`, `onScreen`, `clipped`, `matrix`, `pixelScale`, `occlude`, `remeasure()`, `setMesh`, `setMatrix`, `setPose(position, quaternion)`, `remove()` |
458
+ | `projectPoint`, `isOrthographic` (from `@margoengine/math/mat4`) | World point to CSS pixels plus normalized depth and frustum flags, for either backend; the renderer uses math's |
459
+ | `Declutter`, `eightPositions`, `fourPositions` (from `@margoengine/labels/declutter`) | Overlap removal by priority, as a `layout` |
460
+ | `Callouts` (from `@margoengine/labels/callouts`) | Leader lines from moved labels to their points, as a `layout` that can wrap another |
461
+ | `LabelLayout`, `LayoutContext` | Types for your own layout (`context.root` is the overlay, for layouts that draw) |
462
+ | `lookAtView`, `cssPerspective`, `cameraCSSTransform`, `objectCSSTransform`, `cssPointToWorld`, `composeMatrix` | The CSS 3D math, exported for custom layouts and tests (`lookAtView(position, target, out?, up?)` takes core's `camera.up`, default +Y, so exact top-down views work) |
463
+
464
+ ## Options
465
+
466
+ | Option | Applies to | Default |
467
+ | --- | --- | --- |
468
+ | `parent` | renderer | Canvas parent, inserted right after the canvas |
469
+ | `zIndex`, `className` | renderer (overlay root) | 1, none |
470
+ | `occlude` | renderer, label, CSS 3D (`(object, info) => boolean`) | none |
471
+ | `layout` | renderer | none |
472
+ | `priority` | label | 0 |
473
+ | `mesh` / `position` | label, CSS 3D | none / origin |
474
+ | `offset`, `offsetSpace` | label | [0, 0, 0], `'local'` (or `'world'`) |
475
+ | `anchor` | label | [0.5, 0.5] (element center) |
476
+ | `screenOffset` | label | [0, 0]; CSS px the element moves from its point, for callouts |
477
+ | `pointerEvents` | label, CSS 3D | `'none'` (pass through to the canvas); `'auto'` to interact |
478
+ | `frustumCulling` | label | true |
479
+ | `followVisibility` | label, CSS 3D | true |
480
+ | `distanceScale` | label | none; a number or `{reference, min, max}` gives `reference / distance` |
481
+ | `sort` | label | true |
482
+ | `matrix`, `quaternion` | CSS 3D | identity |
483
+ | `pixelScale` | CSS 3D | 0.01 world units per CSS pixel |
484
+
485
+ ## Limits
486
+
487
+ - CSS 3D objects are not depth-tested per pixel against WebGL/WebGPU geometry and sit above the canvas; the `occlude` hook hides a whole object. They are cut at the near plane by their rectangle, so content painted outside the element box (shadows, overflow) is cut with it.
488
+ - Overlay alignment follows CSS scales on the canvas's ancestors, not rotations, skews or a transform on the canvas itself.
489
+ - Occlusion against scene geometry is left to the `occlude` hook.
490
+ - Callouts draws straight leaders under labels; those leaders can cross. RoutedCallouts offers reordered side-column leaders instead.
491
+ - Decluttering tests the element's box, not its painted shape, and measures it once; a box that changes size needs `remeasure()`.
492
+
493
+ ## Tests
494
+
495
+ `npm test` in `packages/labels` runs Node checks: `projectPoint` against hand-computed values on both clip spaces (near, far, behind, outside), `lookAtView` against the core camera matrix, a CSS transform-chain evaluator showing CSS 3D element corners land on the projected world corners, and the renderer on a fake DOM (overlay placement, mesh following, local and world offsets, anchors, frustum and visibility hiding, z-order, zero writes on a static frame, distance scaling, occlusion hooks, WebGL2, CSS 3D transforms, dispose), decluttering (priority wins, positions tried in order, padding, `inside`, sticky ties, distance-scaled boxes, sizes measured once, still frames write nothing, and 400 random labels placed exactly as a test of every pair places them), CSS 3D depth (panels through the near plane with the origin on either side shown and cut, every polygon point on or in front of the plane, 60 random poses checked on a 21 x 21 grid of element points against the plane, an orthographic cut at depth 0, `clip-path` written only while cut, the CSS 3D `occlude` hook), scaled ancestors (the overlay on the content box in one update at scales 0.5 to 4 beside the canvas with no scale of its own, an overlay in another parent scaled to the canvas, the scale cleared again, still frames writing nothing), callouts (a line from the point to the nearest corner or edge of the moved box with a dot, none for labels on their point and those not measured, lines that follow, hide with their labels, hide when no label is shown and are deleted with removed ones, a still frame writing nothing, a wrapped `Declutter` whose hidden labels get no line and whose boxes use the offset, anchors placed by a wrapped layout, checked options), plus orthographic cameras from `@margoengine/cameras` (projection on both clip spaces, CSS 3D corners and depth order, `perspective: none`, near-plane hiding, zoom-based `distanceScale`). `npm run test:browser` (a real-GPU script) runs a real engine in Chromium on WebGPU and then WebGL2: a label sits over its mesh's projected center within 1 px (with the mesh color read back under it), follows a moving mesh, hides behind the camera, stays within 1 px of its point in one update with the canvas's frame scaled by 0.75 and 2 (and a second overlay in `document.body` too, drawn at the frame's scale), passes pointer events through, z-orders by depth under hit testing and re-sorts when the camera moves, CSS 3D corner markers land within 2 px of the projected world corners, a tilted CSS 3D panel whose origin is behind the near plane is hit in its far half and not in its near half, a callout's line starts within 1 px of the projected point and ends within 1 px of the nearest point of the label's laid-out box, there are zero WebGPU validation errors, and removing the plugin leaves no overlay elements.
496
+
497
+ Apache-2.0 licensed.
498
+
499
+ ## Preview tier contract
500
+
501
+ `GPULabelLayer` (`@margoengine/labels/gpu`) is a reviewed preview route in `scripts/check-preview-contract.mjs` (2026-11-10, 1 `backend` test): on the small WebGL2 preview it draws its glyph batch with WebGL2, elsewhere with WebGPU. Pixel evidence for native WebGPU, the WebGL2 preview and the full compatibility layer: `tests/gpu-browser.js` (`npm run test:browser`). No behaviour changed; the missing row kept `npm run verify` red.
502
+
503
+ ## Works with
504
+
505
+ The [scientific dashboard](../../docs/integration-sciviz.md) composes labels with
506
+ scientific visualization and camera controls. Its guide gives the runnable
507
+ page, test command and measured limits of the integration fixture.
@@ -0,0 +1,58 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Label, LabelLayout, LayoutContext } from './renderer.js';
3
+ /** A leader from one input source to one reordered label port, with an angled elbow. */
4
+ export interface CalloutLeaderRoute {
5
+ readonly source: number;
6
+ readonly port: number;
7
+ readonly points: readonly [readonly [number, number], readonly [number, number], readonly [number, number]];
8
+ }
9
+ /** A finite projected point in CSS pixels. */
10
+ export type CalloutScreenPoint = readonly [number, number];
11
+ /**
12
+ * Crossing-free source/port assignment. Ports share one column, with distinct y coordinates;
13
+ * bendX lies strictly between every source and that column. Labels may be reordered.
14
+ * Each leader has one angled segment and one horizontal segment, meeting on bendX.
15
+ * Coincident sources may share their origin; they never share a leader segment.
16
+ */
17
+ export declare function routeCalloutLeaders(sources: readonly CalloutScreenPoint[], ports: readonly CalloutScreenPoint[], bendX: number): CalloutLeaderRoute[];
18
+ /** Configuration for a crossing-free external callout column. */
19
+ export interface RoutedCalloutsOptions {
20
+ /** Default auto: choose the side with more room. */
21
+ side?: 'left' | 'right' | 'auto';
22
+ /** Source-to-elbow and elbow-to-label minimum gap in CSS pixels. Default 16. */
23
+ gap?: number;
24
+ /** Gap between label boxes in CSS pixels. Default 4. */
25
+ padding?: number;
26
+ /** View edge margin in CSS pixels. Default 8. */
27
+ margin?: number;
28
+ /** Stroke color, default currentColor. */
29
+ color?: string;
30
+ /** Stroke width in CSS pixels, default 1. */
31
+ width?: number;
32
+ /** Permit the callout column to extend beyond the view when it cannot fit. Default true. */
33
+ overflow?: boolean;
34
+ }
35
+ /**
36
+ * One-column external callout layout. Reorders label slots with a planar matching, places
37
+ * boxes without overlaps, and draws one angled elbow per label in a shared SVG.
38
+ */
39
+ export declare class RoutedCallouts implements LabelLayout {
40
+ private readonly options;
41
+ private readonly records;
42
+ private root?;
43
+ private originalOverflow;
44
+ /** Shared SVG, created at the first nonempty update. */
45
+ svg: Element | null;
46
+ /** Routes in the most recent update, in the input label order. */
47
+ routes: readonly CalloutLeaderRoute[];
48
+ /** Number of SVG geometry writes in the last update, zero on a still frame. */
49
+ writes: number;
50
+ constructor(options?: RoutedCalloutsOptions);
51
+ arrange(labels: readonly Label[], context: LayoutContext): void;
52
+ private mount;
53
+ private restoreOverflow;
54
+ /** Removes every leader and restores the overlay's previous overflow style. */
55
+ clear(): void;
56
+ dispose(): void;
57
+ [Symbol.dispose](): void;
58
+ }