@spellkave/world-map 0.0.0-bootstrap → 0.0.0-stage

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/src/export.ts DELETED
@@ -1,861 +0,0 @@
1
- /**
2
- * ADR-0123 D-1..D-4 exporter: place rows → OSM primitives + backdrops sidecar.
3
- *
4
- * LEVEL_HEIGHT_M = 3.0 (ADR-0123 D-2): level index = round(elevation / 3.0).
5
- * Backdrop metres via the owning graph's metres_per_unit (G-5 amendment).
6
- * Stairs inferred from level delta when pose_dt_elevation is absent.
7
- */
8
-
9
- import {
10
- cellRes10ToHex,
11
- type PlacedNode,
12
- projectSheetPoint,
13
- projectWorld,
14
- type WorldOffset,
15
- } from "./coords.ts";
16
- import { IdRegistry } from "./ids.ts";
17
- import type {
18
- BackdropEntry,
19
- ExportManifest,
20
- OsmDocument,
21
- OsmExport,
22
- OsmMember,
23
- OsmNode,
24
- OsmRelation,
25
- OsmWay,
26
- } from "./model.ts";
27
- import { isPoiNamespace, type PoiMetadataPayload, parsePoiMetadata } from "./poi.ts";
28
- import type {
29
- EdgeAffordanceRow,
30
- EdgeStateRow,
31
- GraphRow,
32
- MapLayerRow,
33
- NicheDefinitionRow,
34
- NodeRow,
35
- NodeStateRow,
36
- SpatialNicheAttachmentRow,
37
- WorldOsmInput,
38
- } from "./rows.ts";
39
- import { normalizeWorldOsmInput } from "./rows.ts";
40
- import { buildCoordinateKindMap, levelIndex, type SpatialClass, spatialClassOf } from "./tags.ts";
41
-
42
- export { LEVEL_HEIGHT_M } from "./tags.ts";
43
-
44
- export const PACKAGE_VERSION = "0.0.0";
45
- export const GENERATOR = `spellkave world-osm ${PACKAGE_VERSION}`;
46
-
47
- export interface ExportWorldOpts {
48
- timestamp?: string;
49
- tick?: number;
50
- /** Override generator string (tests / spike parity). */
51
- generator?: string;
52
- diagnostics?: string[];
53
- }
54
-
55
- /** Internal result with test hooks. */
56
- export interface ExportWorldResult extends OsmExport {
57
- placed: Map<string, PlacedNode>;
58
- nodeOsmId: Map<string, string>;
59
- levelByNodeId: Map<string, number>;
60
- kindBySubstrate: Map<string, string>;
61
- }
62
-
63
- function classOf(substrateId: string, kindBySubstrate: ReadonlyMap<string, string>): SpatialClass {
64
- return spatialClassOf(substrateId, kindBySubstrate);
65
- }
66
-
67
- function parseExtent(
68
- shapeId: string,
69
- paramsJson: string,
70
- defaultShape: string,
71
- defaultParams: string,
72
- ): { shape: "cube" | "sphere"; x_m: number; y_m: number } | null {
73
- const shape = shapeId || defaultShape;
74
- const json = paramsJson || defaultParams;
75
- if (!shape) return null;
76
- if (shape !== "core/area/cube" && shape !== "core/area/sphere") return null;
77
- let params: Record<string, unknown> = {};
78
- try {
79
- params = JSON.parse(json || "{}") as Record<string, unknown>;
80
- } catch {
81
- params = {};
82
- }
83
- const n = (k: string): number | undefined => {
84
- const v = params[k];
85
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
86
- };
87
- if (shape === "core/area/sphere") {
88
- const rx = n("radius_x_m") ?? n("radius_m");
89
- const ry = n("radius_y_m") ?? n("radius_m") ?? rx;
90
- if (rx === undefined || rx <= 0) return null;
91
- return { shape: "sphere", x_m: rx, y_m: ry ?? rx };
92
- }
93
- const ex = n("extent_x_m") ?? n("extent_m");
94
- const ey = n("extent_y_m") ?? n("extent_m") ?? ex;
95
- if (ex === undefined || ex <= 0) return null;
96
- return { shape: "cube", x_m: ex, y_m: ey ?? ex };
97
- }
98
-
99
- /** Rotate a local east/north offset by clockwise bearing. */
100
- function rotateEn(east: number, north: number, bearingDeg: number): WorldOffset {
101
- const r = (bearingDeg * Math.PI) / 180;
102
- const cos = Math.cos(r);
103
- const sin = Math.sin(r);
104
- return {
105
- east_m: east * cos + north * sin,
106
- north_m: -east * sin + north * cos,
107
- };
108
- }
109
-
110
- function cellTag(value: unknown): string | null {
111
- const hex = cellRes10ToHex(value);
112
- if (hex === null) return null;
113
- try {
114
- return BigInt(`0x${hex}`).toString(10);
115
- } catch {
116
- return null;
117
- }
118
- }
119
-
120
- function metaAttrs(timestamp: string) {
121
- return {
122
- version: 1,
123
- changeset: 1,
124
- uid: 1,
125
- user: "spellkave",
126
- visible: true,
127
- timestamp,
128
- };
129
- }
130
-
131
- /**
132
- * Export plain spatial rows to an in-memory OSM document + backdrops + manifest.
133
- * Operator rows = full world (ADR-0123 identity requirement).
134
- */
135
- export function exportWorld(input: WorldOsmInput, opts: ExportWorldOpts = {}): ExportWorldResult {
136
- const timestamp = opts.timestamp ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
137
- const tick = opts.tick ?? 0;
138
- const generator = opts.generator ?? GENERATOR;
139
- const meta = metaAttrs(timestamp);
140
-
141
- const normalized = normalizeWorldOsmInput(input);
142
- const { kindBySubstrate, usedBootstrapFallback } = buildCoordinateKindMap(
143
- normalized.substrate_definitions,
144
- );
145
- const diagnostics: string[] = [...(opts.diagnostics ?? [])];
146
- if (usedBootstrapFallback) {
147
- diagnostics.push(
148
- "substrate_kind_fallback: no substrate_definitions rows; using kernel bootstrap seed (outdoor→h3_cell, indoor→graph_local, tactical→tactical_grid)",
149
- );
150
- }
151
-
152
- const projection = projectWorld(input, { diagnostics: [] });
153
- // Re-use projection diagnostics only once (projectWorld may also emit fallback).
154
- for (const d of projection.diagnostics) {
155
- if (!diagnostics.includes(d)) diagnostics.push(d);
156
- }
157
-
158
- const graphs = normalized.place_graphs.filter(
159
- (g) => classOf(g.substrate_id, kindBySubstrate) !== "drop",
160
- );
161
- const nodes = normalized.place_nodes.filter(
162
- (n) => classOf(n.substrate_id, kindBySubstrate) !== "drop",
163
- );
164
- const edges = normalized.place_edges;
165
-
166
- const { placed, unplaced: unplacedGraphs, origin } = projection;
167
-
168
- const unplacedIds = new Set(unplacedGraphs.map((u) => u.place_graph_id));
169
- const exportableNodes = [...placed.values()].filter(
170
- (p) => !unplacedIds.has(p.node.place_graph_id),
171
- );
172
-
173
- const poiByNodeId = new Map<string, PoiMetadataPayload>();
174
- const poiByGraphId = new Map<string, PoiMetadataPayload>();
175
- for (const att of normalized.metadata_attachments) {
176
- if (!isPoiNamespace(att.namespace)) continue;
177
- const poi = parsePoiMetadata(att.payload_json);
178
- if (!poi) continue;
179
- if (att.target_kind === "place_node") {
180
- poiByNodeId.set(att.target_ref, poi);
181
- } else if (att.target_kind === "place_graph") {
182
- poiByGraphId.set(att.target_ref, poi);
183
- }
184
- }
185
-
186
- const affordancesByEdgeKey = new Map<string, EdgeAffordanceRow[]>();
187
- for (const aff of normalized.place_edge_affordances) {
188
- const list = affordancesByEdgeKey.get(aff.edge_key) ?? [];
189
- list.push(aff);
190
- affordancesByEdgeKey.set(aff.edge_key, list);
191
- }
192
-
193
- const statesByEdgeId = new Map<string, EdgeStateRow[]>();
194
- const statesByEdgeKey = new Map<string, EdgeStateRow[]>();
195
- for (const st of normalized.edge_states) {
196
- if (st.edge_id) {
197
- const list = statesByEdgeId.get(st.edge_id) ?? [];
198
- list.push(st);
199
- statesByEdgeId.set(st.edge_id, list);
200
- }
201
- if (st.edge_key) {
202
- const list = statesByEdgeKey.get(st.edge_key) ?? [];
203
- list.push(st);
204
- statesByEdgeKey.set(st.edge_key, list);
205
- }
206
- }
207
-
208
- const nodeIds = new IdRegistry();
209
- const wayIds = new IdRegistry();
210
- const relIds = new IdRegistry();
211
-
212
- const osmNodes: OsmNode[] = [];
213
- const osmWays: OsmWay[] = [];
214
- const osmRelations: OsmRelation[] = [];
215
-
216
- const nodeOsmId = new Map<string, string>();
217
- const levelByNodeId = new Map<string, number>();
218
- const extentWayByNode = new Map<string, string>();
219
- const edgeWayByKey = new Map<string, string>();
220
- const graphRelById = new Map<string, string>();
221
-
222
- const nicheDefsById = new Map<string, NicheDefinitionRow>();
223
- for (const nd of normalized.niche_definitions) {
224
- if (nd.niche_id) nicheDefsById.set(nd.niche_id, nd);
225
- }
226
-
227
- const nichesByNodeId = new Map<string, SpatialNicheAttachmentRow[]>();
228
- for (const sn of normalized.spatial_niche_attachments) {
229
- if (sn.place_node_id) {
230
- const list = nichesByNodeId.get(sn.place_node_id) ?? [];
231
- list.push(sn);
232
- nichesByNodeId.set(sn.place_node_id, list);
233
- }
234
- }
235
-
236
- const statesByNodeId = new Map<string, NodeStateRow[]>();
237
- for (const ns of normalized.node_states) {
238
- if (ns.node_id) {
239
- const list = statesByNodeId.get(ns.node_id) ?? [];
240
- list.push(ns);
241
- statesByNodeId.set(ns.node_id, list);
242
- }
243
- }
244
-
245
- const swimNodes = new Set<string>();
246
- for (const e of edges) {
247
- const hashKey = e.edge_key || `edge:${e.edge_id ?? `${e.from_node_id}->${e.to_node_id}`}`;
248
- const affs =
249
- affordancesByEdgeKey.get(hashKey) ??
250
- (e.edge_key ? affordancesByEdgeKey.get(e.edge_key) : undefined) ??
251
- [];
252
- for (const aff of affs) {
253
- if (aff.mode_id === "swim") {
254
- swimNodes.add(e.from_node_id);
255
- swimNodes.add(e.to_node_id);
256
- }
257
- }
258
- }
259
-
260
- // ── place_node → OSM node (+ optional extent way) ────────────────────────
261
- for (const p of exportableNodes) {
262
- const n = p.node;
263
- const osmId = nodeIds.id(n.node_id);
264
- nodeOsmId.set(n.node_id, osmId);
265
- const tags: Record<string, string> = {
266
- "spellkave:node_id": n.node_id,
267
- "spellkave:bundle": n.bundle_id,
268
- "spellkave:graph": n.place_graph_id,
269
- "spellkave:substrate": n.substrate_id,
270
- };
271
- if (n.local_id) tags.ref = n.local_id;
272
- if (n.display_name) tags.name = n.display_name;
273
- if (n.description) tags.description = n.description;
274
- const c10 = cellTag(n.cell_res10);
275
- const c7 = cellTag(n.cell_res7);
276
- const c4 = cellTag(n.cell_res4);
277
- if (c10) tags["spellkave:cell_res10"] = c10;
278
- if (c7) tags["spellkave:cell_res7"] = c7;
279
- if (c4) tags["spellkave:cell_res4"] = c4;
280
- if (n.pos_present) {
281
- tags["spellkave:pos_x"] = String(n.pos_x);
282
- tags["spellkave:pos_y"] = String(n.pos_y);
283
- }
284
- const nCls = classOf(n.substrate_id, kindBySubstrate);
285
- const lvl = levelIndex(n.pose_elevation_present, n.pose_elevation, nCls);
286
- if (lvl !== null) {
287
- tags.level = String(lvl);
288
- levelByNodeId.set(n.node_id, lvl);
289
- tags["spellkave:elevation_m"] = String(n.pose_elevation);
290
- } else if (n.pose_elevation_present) {
291
- tags["spellkave:elevation_m"] = String(n.pose_elevation);
292
- }
293
-
294
- const graph = graphs.find((g) => g.place_graph_id === n.place_graph_id);
295
- const gCls = graph ? classOf(graph.substrate_id, kindBySubstrate) : "outdoor";
296
- const isAnchor = graph?.anchor_node_id === n.node_id;
297
- if (isAnchor) tags["spellkave:anchor"] = "yes";
298
- if (isAnchor && gCls === "indoor") tags.entrance = "yes";
299
-
300
- const extent = parseExtent(
301
- n.extent_shape_id,
302
- n.extent_params_json,
303
- normalized.default_extent_shape_id,
304
- normalized.default_extent_params_json,
305
- );
306
- if (nCls === "indoor") {
307
- tags.indoor = "room";
308
- } else if (nCls === "tactical") {
309
- tags["spellkave:tactical"] = "cell";
310
- }
311
- if (extent) {
312
- tags["spellkave:extent_shape"] = n.extent_shape_id || normalized.default_extent_shape_id;
313
- }
314
-
315
- // Project POI metadata attachment (from place_node or inheriting from place_graph anchor)
316
- const nodePoi =
317
- poiByNodeId.get(n.node_id) ?? (isAnchor ? poiByGraphId.get(n.place_graph_id) : undefined);
318
- if (nodePoi) {
319
- if (nodePoi.icon) tags["spellkave:poi_icon"] = nodePoi.icon;
320
- if (nodePoi.category) tags["spellkave:poi_category"] = nodePoi.category;
321
- if (nodePoi.badge) tags["spellkave:poi_badge"] = nodePoi.badge;
322
- if (nodePoi.color) tags["spellkave:poi_color"] = nodePoi.color;
323
- if (nodePoi.label && !tags.name) tags.name = nodePoi.label;
324
- }
325
-
326
- // Project hazard niches, states, and categories
327
- let hazardType: string | undefined;
328
- const nodeNiches = nichesByNodeId.get(n.node_id) ?? [];
329
- for (const sn of nodeNiches) {
330
- const nId = sn.niche_id.toLowerCase();
331
- const def = nicheDefsById.get(sn.niche_id);
332
- const dName = (def?.display_name ?? "").toLowerCase();
333
- if (nId.includes("acid") || dName.includes("acid")) hazardType = "acid";
334
- else if (nId.includes("slime") || dName.includes("slime")) hazardType = "slime";
335
- else if (nId.includes("lava") || dName.includes("lava")) hazardType = "lava";
336
- else if (nId.includes("hazard") || dName.includes("hazard") || nId.includes("pool")) {
337
- hazardType = hazardType ?? (nId.includes("pool") ? "slime" : "hazard");
338
- }
339
- }
340
-
341
- if (nodePoi?.category === "hazard" || nodePoi?.icon === "hazard") {
342
- const lbl = (nodePoi.label ?? "").toLowerCase();
343
- if (lbl.includes("acid")) hazardType = "acid";
344
- else if (lbl.includes("slime")) hazardType = "slime";
345
- else if (lbl.includes("lava")) hazardType = "lava";
346
- else hazardType = hazardType ?? "hazard";
347
- }
348
-
349
- const nodeStates = statesByNodeId.get(n.node_id) ?? [];
350
- for (const st of nodeStates) {
351
- const sId = st.state_id.toLowerCase();
352
- if (sId.includes("acid")) hazardType = "acid";
353
- else if (sId.includes("slime")) hazardType = "slime";
354
- else if (sId.includes("lava")) hazardType = "lava";
355
- else if (sId.includes("hazard")) hazardType = hazardType ?? "hazard";
356
- }
357
-
358
- if (hazardType) {
359
- tags["spellkave:hazard"] = hazardType;
360
- tags.hazard = "yes";
361
- }
362
-
363
- // Project liquid / water body
364
- let waterType: string | undefined;
365
- const lowerName = (n.display_name ?? n.local_id ?? n.node_id).toLowerCase();
366
- if (swimNodes.has(n.node_id)) {
367
- waterType = lowerName.includes("river")
368
- ? "river"
369
- : lowerName.includes("pool")
370
- ? "pool"
371
- : "water";
372
- } else if (
373
- lowerName.includes("river") ||
374
- lowerName.includes("stream") ||
375
- lowerName.includes("brook") ||
376
- lowerName.includes("water") ||
377
- lowerName.includes("lake") ||
378
- lowerName.includes("swamp") ||
379
- lowerName.includes("pond") ||
380
- lowerName.includes("pool")
381
- ) {
382
- if (lowerName.includes("river") || lowerName.includes("stream")) waterType = "river";
383
- else if (lowerName.includes("lake")) waterType = "lake";
384
- else if (lowerName.includes("swamp")) waterType = "swamp";
385
- else if (lowerName.includes("pool")) waterType = "pool";
386
- else if (lowerName.includes("pond")) waterType = "pond";
387
- else waterType = "water";
388
- } else if (nodePoi?.category === "water") {
389
- waterType = "water";
390
- }
391
-
392
- if (waterType) {
393
- tags.natural = "water";
394
- tags.water = waterType;
395
- }
396
-
397
- // Project difficult terrain
398
- for (const st of nodeStates) {
399
- const sId = st.state_id.toLowerCase();
400
- if (sId.includes("difficult_terrain")) {
401
- tags["spellkave:terrain"] = "difficult";
402
- break;
403
- }
404
- }
405
-
406
- osmNodes.push({
407
- type: "node",
408
- id: osmId,
409
- lat: p.lat,
410
- lon: p.lon,
411
- tags,
412
- ...meta,
413
- });
414
-
415
- if (extent) {
416
- const cornerRefs: string[] = [];
417
- const cornersEn: Array<{ e: number; n: number }> = [];
418
- if (extent.shape === "cube") {
419
- const hx = extent.x_m / 2;
420
- const hy = extent.y_m / 2;
421
- cornersEn.push({ e: -hx, n: hy }, { e: hx, n: hy }, { e: hx, n: -hy }, { e: -hx, n: -hy });
422
- } else {
423
- for (let i = 0; i < 16; i++) {
424
- const a = (i / 16) * Math.PI * 2;
425
- cornersEn.push({
426
- e: Math.cos(a) * extent.x_m,
427
- n: Math.sin(a) * extent.y_m,
428
- });
429
- }
430
- }
431
- for (let i = 0; i < cornersEn.length; i++) {
432
- const key = `extent:${n.node_id}:${i}`;
433
- const cid = nodeIds.id(key);
434
- const rot = rotateEn(cornersEn[i]!.e, cornersEn[i]!.n, p.composed_bearing_deg);
435
- const lat = p.lat + rot.north_m / 111_320;
436
- const cosLat = Math.cos((p.lat * Math.PI) / 180);
437
- const lon = p.lon + rot.east_m / (111_320 * (cosLat === 0 ? 1e-12 : cosLat));
438
- osmNodes.push({
439
- type: "node",
440
- id: cid,
441
- lat,
442
- lon,
443
- tags: {},
444
- ...meta,
445
- });
446
- cornerRefs.push(cid);
447
- }
448
- const closed = [...cornerRefs, cornerRefs[0]!];
449
- const wayKey = `extent:${n.node_id}`;
450
- const wayId = wayIds.id(wayKey);
451
- extentWayByNode.set(n.node_id, wayId);
452
- const wtags: Record<string, string> = {
453
- "spellkave:node_id": n.node_id,
454
- "spellkave:graph": n.place_graph_id,
455
- "spellkave:extent_shape": n.extent_shape_id || normalized.default_extent_shape_id,
456
- "spellkave:extent_params": n.extent_params_json || normalized.default_extent_params_json,
457
- };
458
- if (n.display_name) wtags.name = n.display_name;
459
- if (nCls === "indoor") {
460
- wtags.indoor = "room";
461
- } else {
462
- wtags["spellkave:extent"] = "yes";
463
- }
464
- if (lvl !== null) wtags.level = String(lvl);
465
- if (tags["spellkave:hazard"]) {
466
- wtags["spellkave:hazard"] = tags["spellkave:hazard"];
467
- wtags.hazard = "yes";
468
- }
469
- if (tags.natural === "water") {
470
- wtags.natural = "water";
471
- if (tags.water) wtags.water = tags.water;
472
- }
473
- if (tags["spellkave:terrain"]) {
474
- wtags["spellkave:terrain"] = tags["spellkave:terrain"];
475
- }
476
- if (tags["spellkave:poi_category"])
477
- wtags["spellkave:poi_category"] = tags["spellkave:poi_category"];
478
- if (tags["spellkave:poi_icon"]) wtags["spellkave:poi_icon"] = tags["spellkave:poi_icon"];
479
- if (tags["spellkave:poi_color"]) wtags["spellkave:poi_color"] = tags["spellkave:poi_color"];
480
- osmWays.push({
481
- type: "way",
482
- id: wayId,
483
- refs: closed,
484
- tags: wtags,
485
- ...meta,
486
- });
487
- }
488
- }
489
-
490
- // ── place_edge → 2-node way ──────────────────────────────────────────────
491
- const nodeGraph = new Map(nodes.map((n) => [n.node_id, n]));
492
- for (const e of edges) {
493
- const fromOsm = nodeOsmId.get(e.from_node_id);
494
- const toOsm = nodeOsmId.get(e.to_node_id);
495
- if (!fromOsm || !toOsm) continue;
496
- const hashKey = e.edge_key || `edge:${e.edge_id ?? `${e.from_node_id}->${e.to_node_id}`}`;
497
- const wayId = wayIds.id(hashKey);
498
- edgeWayByKey.set(hashKey, wayId);
499
- const fromN = nodeGraph.get(e.from_node_id)!;
500
- const toN = nodeGraph.get(e.to_node_id)!;
501
- const fromLvl = levelByNodeId.get(e.from_node_id);
502
- const toLvl = levelByNodeId.get(e.to_node_id);
503
- const bothIndoor =
504
- classOf(fromN.substrate_id, kindBySubstrate) === "indoor" &&
505
- classOf(toN.substrate_id, kindBySubstrate) === "indoor";
506
- const tags: Record<string, string> = {
507
- "spellkave:edge_key": hashKey,
508
- "spellkave:bundle": e.bundle_id,
509
- "spellkave:from_node": e.from_node_id,
510
- "spellkave:to_node": e.to_node_id,
511
- oneway: "yes",
512
- "spellkave:inherit_movement_default": e.inherit_movement_default ? "yes" : "no",
513
- };
514
- if (e.description) tags.description = e.description;
515
-
516
- const isPortal = (e.place_graph_id ?? "").trim() === "";
517
- if (isPortal) {
518
- tags["spellkave:portal"] = "yes";
519
- } else {
520
- tags["spellkave:graph"] = e.place_graph_id;
521
- }
522
-
523
- const fromCls = classOf(fromN.substrate_id, kindBySubstrate);
524
- const toCls = classOf(toN.substrate_id, kindBySubstrate);
525
- if (fromCls === "tactical" || toCls === "tactical") {
526
- tags["spellkave:tactical"] = "edge";
527
- }
528
-
529
- const dtPresent = e.pose_dt_elevation_present && e.pose_dt_elevation !== 0;
530
- const levelsDiffer = fromLvl !== undefined && toLvl !== undefined && fromLvl !== toLvl;
531
- if (dtPresent || levelsDiffer) {
532
- tags.highway = "steps";
533
- if (dtPresent) {
534
- tags.incline = e.pose_dt_elevation > 0 ? "up" : "down";
535
- tags["spellkave:elevation_delta_m"] = String(e.pose_dt_elevation);
536
- } else if (levelsDiffer) {
537
- tags.incline = (toLvl ?? 0) > (fromLvl ?? 0) ? "up" : "down";
538
- }
539
- if (fromLvl !== undefined && toLvl !== undefined) {
540
- tags.level = `${fromLvl};${toLvl}`;
541
- }
542
- } else {
543
- tags.highway = bothIndoor ? "corridor" : "path";
544
- if (fromLvl !== undefined && fromLvl === toLvl) {
545
- tags.level = String(fromLvl);
546
- }
547
- }
548
- if (bothIndoor) tags.indoor = "room";
549
-
550
- if (e.substrate_crossing) {
551
- tags.door = "yes";
552
- tags["spellkave:substrate_crossing"] = "yes";
553
- }
554
- if (e.cell_anchor_present) {
555
- const ca = cellTag(e.cell_anchor);
556
- if (ca) tags["spellkave:cell_anchor"] = ca;
557
- tags["spellkave:cell_anchor_u"] = String(e.cell_anchor_u);
558
- tags["spellkave:cell_anchor_v"] = String(e.cell_anchor_v);
559
- }
560
- if (e.from_anchor_side) {
561
- tags["spellkave:from_side"] = e.from_anchor_side;
562
- tags["spellkave:from_offset"] = String(e.from_anchor_offset);
563
- }
564
- if (e.to_anchor_side) {
565
- tags["spellkave:to_side"] = e.to_anchor_side;
566
- tags["spellkave:to_offset"] = String(e.to_anchor_offset);
567
- }
568
-
569
- // Project edge affordances (traversal mode, seals/barriers)
570
- const affs =
571
- affordancesByEdgeKey.get(hashKey) ??
572
- (e.edge_key ? affordancesByEdgeKey.get(e.edge_key) : undefined) ??
573
- [];
574
- for (const aff of affs) {
575
- if (aff.mode_id) {
576
- tags["spellkave:traversal_mode"] = aff.mode_id;
577
- }
578
- const tpl = aff.affordance_template_id;
579
- if (tpl) {
580
- tags["spellkave:affordance_template"] = tpl;
581
- const lower = tpl.toLowerCase();
582
- if (
583
- lower.includes("seal") ||
584
- lower.includes("threshold") ||
585
- lower.includes("gate") ||
586
- lower.includes("lock")
587
- ) {
588
- tags.barrier = "gate";
589
- tags["spellkave:seal"] = tpl;
590
- tags.door = "yes";
591
- }
592
- }
593
- }
594
-
595
- // Check dynamic edge state for open/locked status
596
- const edgeStates = [
597
- ...(e.edge_id !== undefined ? (statesByEdgeId.get(String(e.edge_id)) ?? []) : []),
598
- ...(statesByEdgeKey.get(hashKey) ?? []),
599
- ...(e.edge_key ? (statesByEdgeKey.get(e.edge_key) ?? []) : []),
600
- ];
601
- let isLocked: boolean | undefined;
602
- for (const st of edgeStates) {
603
- const sId = st.state_id.toLowerCase();
604
- if (sId.endsWith("-open") || sId.endsWith(".open") || sId.includes("open")) {
605
- isLocked = !st.value;
606
- } else if (sId.includes("locked")) {
607
- isLocked = Boolean(st.value);
608
- }
609
- }
610
- if (isLocked !== undefined) {
611
- tags["spellkave:locked"] = isLocked ? "yes" : "no";
612
- } else if (tags["spellkave:seal"]) {
613
- tags["spellkave:locked"] = "yes";
614
- }
615
-
616
- osmWays.push({
617
- type: "way",
618
- id: wayId,
619
- refs: [fromOsm, toOsm],
620
- tags,
621
- ...meta,
622
- });
623
- }
624
-
625
- // ── place_graph_definition → relation ────────────────────────────────────
626
- const placedGraphIds = new Set(exportableNodes.map((p) => p.node.place_graph_id));
627
- for (const g of graphs) {
628
- if (!placedGraphIds.has(g.place_graph_id)) continue;
629
- const relId = relIds.id(g.place_graph_id);
630
- graphRelById.set(g.place_graph_id, relId);
631
- }
632
-
633
- for (const g of graphs) {
634
- const relId = graphRelById.get(g.place_graph_id);
635
- if (!relId) continue;
636
- const members: OsmMember[] = [];
637
- const graphNodes = exportableNodes.filter((p) => p.node.place_graph_id === g.place_graph_id);
638
- const levels: number[] = [];
639
- for (const p of graphNodes) {
640
- const oid = nodeOsmId.get(p.node.node_id)!;
641
- const role = g.anchor_node_id === p.node.node_id ? "anchor" : "node";
642
- members.push({ type: "node", ref: oid, role });
643
- const lvl = levelByNodeId.get(p.node.node_id);
644
- if (lvl !== undefined) levels.push(lvl);
645
- const ext = extentWayByNode.get(p.node.node_id);
646
- if (ext) members.push({ type: "way", ref: ext, role: "extent" });
647
- }
648
- for (const e of edges) {
649
- if (e.place_graph_id !== g.place_graph_id) continue;
650
- const hashKey = e.edge_key || `edge:${e.edge_id ?? ""}`;
651
- const wid = edgeWayByKey.get(hashKey);
652
- if (wid) members.push({ type: "way", ref: wid, role: "edge" });
653
- }
654
- const graphNodeSet = new Set(graphNodes.map((p) => p.node.node_id));
655
- for (const e of edges) {
656
- if ((e.place_graph_id ?? "").trim() !== "") continue;
657
- if (!graphNodeSet.has(e.from_node_id) && !graphNodeSet.has(e.to_node_id)) continue;
658
- const hashKey = e.edge_key || `edge:${e.edge_id ?? ""}`;
659
- const wid = edgeWayByKey.get(hashKey);
660
- if (wid) members.push({ type: "way", ref: wid, role: "portal" });
661
- }
662
- for (const child of graphs) {
663
- if (child.parent_graph_id !== g.place_graph_id) continue;
664
- const childRel = graphRelById.get(child.place_graph_id);
665
- if (childRel) members.push({ type: "relation", ref: childRel, role: "child" });
666
- }
667
-
668
- const tags: Record<string, string> = {
669
- "spellkave:graph_id": g.place_graph_id,
670
- "spellkave:bundle": g.bundle_id,
671
- "spellkave:substrate": g.substrate_id,
672
- "spellkave:bearing": String(g.bearing),
673
- "spellkave:metres_per_unit": String(g.metres_per_unit),
674
- "spellkave:anchor_node": g.anchor_node_id,
675
- };
676
- if (g.display_name) tags.name = g.display_name;
677
- if (g.description) tags.description = g.description;
678
- if (g.blueprint_id) tags["spellkave:blueprint"] = g.blueprint_id;
679
- if (g.parent_graph_id) tags["spellkave:parent_graph"] = g.parent_graph_id;
680
- const o10 = cellTag(g.origin_cell_res10);
681
- const o7 = cellTag(g.origin_cell_res7);
682
- const o4 = cellTag(g.origin_cell_res4);
683
- if (o10) tags["spellkave:origin_cell_res10"] = o10;
684
- if (o7) tags["spellkave:origin_cell_res7"] = o7;
685
- if (o4) tags["spellkave:origin_cell_res4"] = o4;
686
-
687
- const graphPoi = poiByGraphId.get(g.place_graph_id);
688
- if (graphPoi) {
689
- if (graphPoi.icon) tags["spellkave:poi_icon"] = graphPoi.icon;
690
- if (graphPoi.category) tags["spellkave:poi_category"] = graphPoi.category;
691
- if (graphPoi.badge) tags["spellkave:poi_badge"] = graphPoi.badge;
692
- if (graphPoi.color) tags["spellkave:poi_color"] = graphPoi.color;
693
- }
694
-
695
- const gSubCls = classOf(g.substrate_id, kindBySubstrate);
696
- if (gSubCls === "indoor") {
697
- tags.type = "building";
698
- tags.building = "yes";
699
- if (levels.length > 0) {
700
- const minL = Math.min(...levels);
701
- const maxL = Math.max(...levels);
702
- tags.min_level = String(minL);
703
- tags.max_level = String(maxL);
704
- tags["building:levels"] = String(maxL - Math.min(minL, 0) + 1);
705
- }
706
- } else if (gSubCls === "tactical") {
707
- tags.type = "site";
708
- tags.site = "spellkave_tactical_grid";
709
- tags["spellkave:tactical"] = "grid";
710
- } else {
711
- tags.type = "site";
712
- tags.site = "spellkave_graph";
713
- }
714
-
715
- osmRelations.push({
716
- type: "relation",
717
- id: relId,
718
- members,
719
- tags,
720
- ...meta,
721
- });
722
- }
723
-
724
- // ── map_layer → backdrops.json ───────────────────────────────────────────
725
- const backdrops: BackdropEntry[] = [];
726
- if (origin) {
727
- for (const layer of normalized.map_layers) {
728
- if (unplacedIds.has(layer.place_graph_id)) continue;
729
- if (!placedGraphIds.has(layer.place_graph_id)) continue;
730
- const g = graphs.find((gg) => gg.place_graph_id === layer.place_graph_id);
731
- if (!g) continue;
732
- const entry = backdropEntry(layer, g, placed, origin, graphRelById);
733
- if (entry) backdrops.push(entry);
734
- }
735
- }
736
-
737
- const doc: OsmDocument = {
738
- generator,
739
- tick,
740
- timestamp,
741
- nodes: osmNodes,
742
- ways: osmWays,
743
- relations: osmRelations,
744
- };
745
-
746
- const manifest: ExportManifest = {
747
- generator,
748
- timestamp,
749
- tick,
750
- origin: origin
751
- ? {
752
- lat: origin.lat,
753
- lon: origin.lon,
754
- cell_res10_hex: origin.hex,
755
- cell_res10_decimal: BigInt(`0x${origin.hex}`).toString(10),
756
- }
757
- : null,
758
- counts: {
759
- nodes: osmNodes.length,
760
- ways: osmWays.length,
761
- relations: osmRelations.length,
762
- backdrops: backdrops.length,
763
- unplaced_graphs: unplacedGraphs.length,
764
- },
765
- unplaced_graphs: unplacedGraphs,
766
- diagnostics,
767
- };
768
-
769
- return {
770
- doc,
771
- backdrops,
772
- manifest,
773
- placed,
774
- nodeOsmId,
775
- levelByNodeId,
776
- kindBySubstrate,
777
- };
778
- }
779
-
780
- function backdropEntry(
781
- layer: MapLayerRow,
782
- graph: GraphRow,
783
- placed: Map<string, PlacedNode>,
784
- origin: { lat: number; lon: number; hex: string },
785
- graphRelById: Map<string, string>,
786
- ): BackdropEntry | null {
787
- let anchorSheet = { x: 0, y: 0 };
788
- let baseWorld: WorldOffset = { east_m: 0, north_m: 0 };
789
- const anchorPlaced = placed.get(graph.anchor_node_id);
790
- const parentId = (graph.parent_graph_id ?? "").trim();
791
- if (!parentId) {
792
- if (anchorPlaced) {
793
- anchorSheet = { x: anchorPlaced.node.pos_x, y: anchorPlaced.node.pos_y };
794
- baseWorld = { east_m: 0, north_m: 0 };
795
- }
796
- } else {
797
- // Nested graphs nest at the anchor in elven-mini; use anchor as sheet origin.
798
- const nestPlaced = placed.get(graph.anchor_node_id) ?? anchorPlaced;
799
- if (nestPlaced) {
800
- anchorSheet = { x: nestPlaced.node.pos_x, y: nestPlaced.node.pos_y };
801
- baseWorld = { east_m: nestPlaced.east_m, north_m: nestPlaced.north_m };
802
- } else {
803
- return null;
804
- }
805
- }
806
-
807
- const grid = layer.grid_size_px > 0 ? layer.grid_size_px : 1;
808
- // G-5: metres via the owning graph's metres_per_unit (sheet unit nodes use).
809
- const metres =
810
- graph.metres_per_unit > 0
811
- ? graph.metres_per_unit
812
- : layer.grid_distance_m > 0
813
- ? layer.grid_distance_m
814
- : 1;
815
- const bearing = (graph.bearing ?? 0) + (layer.rotation_deg ?? 0);
816
-
817
- const pxCorners: Array<[number, number]> = [
818
- [0, 0],
819
- [layer.image_width_px, 0],
820
- [layer.image_width_px, layer.image_height_px],
821
- [0, layer.image_height_px],
822
- ];
823
- const coordinates = pxCorners.map(([px, py]) => {
824
- const sheetX = px / grid - layer.image_origin_x;
825
- const sheetY = py / grid - layer.image_origin_y;
826
- const { lat, lon } = projectSheetPoint(
827
- sheetX,
828
- sheetY,
829
- anchorSheet,
830
- baseWorld,
831
- bearing,
832
- metres,
833
- origin.lat,
834
- origin.lon,
835
- );
836
- return [lon, lat] as [number, number];
837
- }) as BackdropEntry["coordinates"];
838
-
839
- const entry: BackdropEntry = {
840
- id: layer.map_layer_id,
841
- graph: layer.place_graph_id,
842
- relation_id: graphRelById.get(layer.place_graph_id) ?? "",
843
- name: layer.display_name,
844
- url: `asset://${layer.asset_module}/${layer.asset_path}`,
845
- asset: { module: layer.asset_module, path: layer.asset_path },
846
- source: layer.source_kind,
847
- license: layer.posture,
848
- state: layer.state,
849
- size_px: [layer.image_width_px, layer.image_height_px],
850
- coordinates,
851
- grid_distance_m: layer.grid_distance_m,
852
- };
853
- if (layer.min_zoom > 0) entry.minzoom = layer.min_zoom;
854
- if (layer.max_zoom > 0) entry.maxzoom = layer.max_zoom;
855
- return entry;
856
- }
857
-
858
- /** Convenience: level index for a typed node row. */
859
- export function nodeLevelIndex(node: NodeRow, cls: SpatialClass): number | null {
860
- return levelIndex(node.pose_elevation_present, node.pose_elevation, cls);
861
- }