@adatechnology/game-urban 0.3.13 → 0.5.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.
@@ -0,0 +1,2070 @@
1
+ // src/networks/classes.ts
2
+ var EDGE_NETWORK = {
3
+ mv_span: "power_mv",
4
+ lv_span: "power_lv",
5
+ service_drop: "power_lv",
6
+ light_feed: "lighting",
7
+ telecom_span: "telecom",
8
+ telecom_drop: "telecom",
9
+ sewer_main: "sewer",
10
+ sewer_lateral: "sewer",
11
+ storm_gallery: "storm",
12
+ storm_lateral: "storm",
13
+ storm_gutter: "storm",
14
+ water_main: "water",
15
+ water_service: "water"
16
+ };
17
+ var EDGE_CLASS = {
18
+ mv_span: "power_mv",
19
+ lv_span: "power_lv",
20
+ service_drop: "service_drop",
21
+ light_feed: "street_light",
22
+ telecom_span: "telecom",
23
+ telecom_drop: "telecom",
24
+ sewer_main: "sewer",
25
+ sewer_lateral: "sewer",
26
+ storm_gallery: "storm",
27
+ storm_lateral: "storm",
28
+ storm_gutter: "storm",
29
+ water_main: "water",
30
+ water_service: "water"
31
+ };
32
+ var AERIAL = /* @__PURE__ */ new Set(["mv_span", "lv_span", "telecom_span", "service_drop", "telecom_drop", "light_feed"]);
33
+ function isAerialEdgeKind(kind) {
34
+ return AERIAL.has(kind);
35
+ }
36
+ var CONNECTION_NETWORK = {
37
+ power: "power_lv",
38
+ telecom: "telecom",
39
+ sewer: "sewer",
40
+ storm: "storm",
41
+ water: "water"
42
+ };
43
+ var NETWORK_FLOW = {
44
+ power_mv: "supply",
45
+ power_lv: "supply",
46
+ lighting: "supply",
47
+ telecom: "supply",
48
+ water: "supply",
49
+ sewer: "drain",
50
+ storm: "drain"
51
+ };
52
+ var NETWORK_ENDS = {
53
+ power_mv: ["feed"],
54
+ power_lv: ["transformer"],
55
+ lighting: [],
56
+ telecom: ["feed"],
57
+ water: ["reservoir"],
58
+ sewer: ["treatment", "outfall"],
59
+ storm: ["outfall"]
60
+ };
61
+
62
+ // src/networks/codes.ts
63
+ var NETWORK_VIOLATION = {
64
+ DUPLICATE_ID: "duplicate_id",
65
+ UNKNOWN_NODE: "unknown_node",
66
+ NOT_CARRIED: "not_carried",
67
+ NOT_RADIAL: "not_radial",
68
+ DISCONNECTED: "disconnected",
69
+ LOOP_AT_END: "loop_at_end",
70
+ CONNECTION_IN_PLAN_FRAME: "connection_in_plan_frame",
71
+ LOT_UNCONNECTED: "lot_unconnected",
72
+ LOT_CONNECTED_TWICE: "lot_connected_twice",
73
+ LOT_DECLARED_TWICE: "lot_declared_twice",
74
+ ORPHAN_CONNECTION: "orphan_connection",
75
+ CONNECTION_MOVED: "connection_moved",
76
+ DROP_TOO_LONG: "drop_too_long",
77
+ DROP_SKEWED: "drop_skewed",
78
+ DROP_OFF_FRONTAGE: "drop_off_frontage",
79
+ DROP_OVER_OTHER_LOT: "drop_over_other_lot",
80
+ POLE_TOO_MANY_DROPS: "pole_too_many_drops",
81
+ MISSING_SAG: "missing_sag",
82
+ CLEARANCE: "clearance",
83
+ MV_OVER_LOT: "mv_over_lot",
84
+ SPAN_OVER_BUILDING: "span_over_building",
85
+ SPAN_THROUGH_CROWN: "span_through_crown",
86
+ MISSING_INVERT: "missing_invert",
87
+ MISSING_DIAMETER: "missing_diameter",
88
+ SLOPE: "slope",
89
+ SLOPE_MISMATCH: "slope_mismatch",
90
+ COVER: "cover",
91
+ TOO_DEEP: "too_deep",
92
+ CROSSING_TOO_CLOSE: "crossing_too_close",
93
+ CROSSING_ORDER: "crossing_order",
94
+ LATERAL_TOO_DEEP: "lateral_too_deep",
95
+ MANHOLE_SPACING: "manhole_spacing",
96
+ UNKNOWN_TRANSFORMER: "unknown_transformer",
97
+ TRANSFORMER_OVERLOADED: "transformer_overloaded",
98
+ LV_CIRCUIT_TOO_LONG: "lv_circuit_too_long"
99
+ };
100
+
101
+ // src/networks/graph.ts
102
+ var NONE = [];
103
+ var ofNetwork = (edges, network) => {
104
+ if (edges === void 0) return NONE;
105
+ return network === void 0 ? edges : edges.filter((edge) => EDGE_NETWORK[edge.kind] === network);
106
+ };
107
+ function buildNetworkGraph(input) {
108
+ const nodes = /* @__PURE__ */ new Map();
109
+ for (const node of input.nodes) if (!nodes.has(node.id)) nodes.set(node.id, node);
110
+ const edges = /* @__PURE__ */ new Map();
111
+ const out = /* @__PURE__ */ new Map();
112
+ const into = /* @__PURE__ */ new Map();
113
+ for (const edge of input.edges) {
114
+ if (edges.has(edge.id)) continue;
115
+ edges.set(edge.id, edge);
116
+ if (!nodes.has(edge.from) || !nodes.has(edge.to)) continue;
117
+ out.set(edge.from, [...out.get(edge.from) ?? [], edge]);
118
+ into.set(edge.to, [...into.get(edge.to) ?? [], edge]);
119
+ }
120
+ return {
121
+ nodes,
122
+ edges,
123
+ outgoing: (nodeId, network) => ofNetwork(out.get(nodeId), network),
124
+ incoming: (nodeId, network) => ofNetwork(into.get(nodeId), network)
125
+ };
126
+ }
127
+ function sourcesOf(graph, network) {
128
+ if (network === "lighting") return [...connectedNodes(graph, "power_lv")];
129
+ const kinds = NETWORK_ENDS[network];
130
+ const ends = [...graph.nodes.values()].filter((node) => kinds.includes(node.kind) && node.carries.includes(network)).map((node) => node.id);
131
+ if (network !== "power_lv") return ends;
132
+ const medium = connectedNodes(graph, "power_mv");
133
+ return ends.filter((id) => medium.has(id));
134
+ }
135
+ function connectedNodes(graph, network) {
136
+ const reached = /* @__PURE__ */ new Set();
137
+ const pending = sourcesOf(graph, network);
138
+ const forward = NETWORK_FLOW[network] === "supply";
139
+ while (pending.length > 0) {
140
+ const id = pending.pop();
141
+ if (reached.has(id)) continue;
142
+ reached.add(id);
143
+ const next = forward ? graph.outgoing(id, network).map((edge) => edge.to) : graph.incoming(id, network).map((edge) => edge.from);
144
+ for (const nextId of next) if (!reached.has(nextId)) pending.push(nextId);
145
+ }
146
+ return reached;
147
+ }
148
+ function edgeLength(graph, edge) {
149
+ const from = graph.nodes.get(edge.from);
150
+ const to = graph.nodes.get(edge.to);
151
+ if (from === void 0 || to === void 0) return 0;
152
+ return Math.hypot(to.at[0] - from.at[0], to.at[2] - from.at[2]);
153
+ }
154
+ function circuitOf(graph, transformerId) {
155
+ const distance2 = /* @__PURE__ */ new Map([[transformerId, 0]]);
156
+ const pending = [transformerId];
157
+ while (pending.length > 0) {
158
+ const id = pending.pop();
159
+ const base = distance2.get(id) ?? 0;
160
+ for (const edge of graph.outgoing(id, "power_lv")) {
161
+ if (distance2.has(edge.to)) continue;
162
+ distance2.set(edge.to, base + (edge.kind === "lv_span" ? edgeLength(graph, edge) : 0));
163
+ pending.push(edge.to);
164
+ }
165
+ }
166
+ return distance2;
167
+ }
168
+
169
+ // src/networks/rules.ts
170
+ import { deepMerge } from "@adatechnology/game-contracts";
171
+
172
+ // src/networks/layout-rules.ts
173
+ var DEFAULT_NETWORK_LAYOUT = {
174
+ sidewalk: 2.5,
175
+ edgeReach: 5,
176
+ poles: { spacing: [30, 40], curbSetback: 0.4, endInset: 1, minGap: 3, crossingClearance: 5, snap: 5, slide: 6, slideStep: 0.25 },
177
+ sag: { mv: 0.5, lv: 0.6, telecom: 0.6, drop: 0.2, telecomDrop: 0.15 },
178
+ telecom: { spliceEvery: 4, cableGap: 0.1, cables: { clean: [1, 2], periphery: [3, 5] } },
179
+ periphery: { kinds: ["residential_popular"], hookupShare: 0.1 },
180
+ slopeMargin: 5e-4,
181
+ coverMargin: 0.05,
182
+ sewer: { mainDiameter: 0.15, lateralDiameter: 0.1, dropOffset: 1, interceptorOffset: 2 },
183
+ storm: { galleryOffset: 2, galleryDiameter: 0.6, lateralDiameter: 0.4, inletSpacing: 60, inletSetback: 0.3, inletFromCorner: 1, riverLevel: -4 },
184
+ water: { mainDiameter: 0.075, serviceDiameter: 0.02, sidewalkShare: 1 / 3, hydrantOffset: 0.6 },
185
+ connection: { frontInset: 0.3, sewerInset: 1, meterFromSide: 1, waterFromSide: 1.6, downspoutFromSide: 1, powerHeight: 5.7, telecomBelowPower: 0.6, sewerDepth: 0.6, sewerLeastDepth: 0.3 }
186
+ };
187
+
188
+ // src/networks/rules.ts
189
+ var LOW_VOLTAGE = { road: 5.5, sidewalk: 4.5, lot: 3.5 };
190
+ var DEFAULT_NETWORK_RULES = {
191
+ clearance: {
192
+ power_mv: { road: 7, sidewalk: 6, lot: null },
193
+ power_lv: LOW_VOLTAGE,
194
+ service_drop: LOW_VOLTAGE,
195
+ street_light: LOW_VOLTAGE,
196
+ telecom: { road: 5, sidewalk: 4.5, lot: 3 }
197
+ },
198
+ catenarySamples: 16,
199
+ power: {
200
+ dropMaxLength: 30,
201
+ dropMaxSkew: 30,
202
+ dropFrontageSlack: 0.5,
203
+ dropsPerPole: 4,
204
+ lvCircuitMaxLength: 200,
205
+ maxLoading: 0.8,
206
+ transformers: [
207
+ { id: "t30", kva: 30 },
208
+ { id: "t45", kva: 45 },
209
+ { id: "t75", kva: 75 },
210
+ { id: "t112", kva: 112.5 }
211
+ ],
212
+ installedSplitKva: 5,
213
+ diversity: [
214
+ { consumers: 5, low: 2, high: 3 },
215
+ { consumers: 15, low: 1.5, high: 2.4 },
216
+ { consumers: 30, low: 1.2, high: 2 },
217
+ { consumers: 60, low: 1, high: 1.7 },
218
+ { consumers: Number.POSITIVE_INFINITY, low: 0.9, high: 1.5 }
219
+ ]
220
+ },
221
+ lighting: { lampKva: 0.15 },
222
+ telecom: { dropMaxLength: 30 },
223
+ minSlope: { sewer_main: 5e-3, sewer_lateral: 0.01, storm_gallery: 5e-3, storm_lateral: 5e-3, storm_gutter: 5e-3 },
224
+ cover: {
225
+ water_main: { min: 0.6, max: 0.8 },
226
+ water_service: { min: 0.6, max: 0.8 },
227
+ // the design sets no least cover for the lateral, only that it is buried and passes over a gallery (`sewer.lateralOverGallery`)
228
+ sewer_lateral: { min: 0 },
229
+ storm_lateral: { min: 1, max: 1.2 },
230
+ storm_gallery: { min: 1.2 },
231
+ // the gutter is an open channel at the kerb (diameter 0): its bottom only has to stay at or under the ground
232
+ storm_gutter: { min: 0 },
233
+ sewer_main: { min: 0.9 }
234
+ },
235
+ sewer: { maxDepth: 4.5, coverUnderGallery: 1.8, galleryReach: 3, lateralOverGallery: 0.85, manholeSpacing: 80 },
236
+ crossing: { separation: 0.2, rank: { storm_gutter: 0, water_main: 1, water_service: 1, sewer_lateral: 2, storm_lateral: 3, storm_gallery: 3, sewer_main: 4 } },
237
+ connectionTolerance: 0.01,
238
+ layout: DEFAULT_NETWORK_LAYOUT
239
+ };
240
+ function resolveNetworkRules(patch) {
241
+ return deepMerge(DEFAULT_NETWORK_RULES, patch);
242
+ }
243
+ function diversifiedDemand(installedKva, rules) {
244
+ if (installedKva.length === 0) return 0;
245
+ const band = rules.diversity.find((entry) => installedKva.length <= entry.consumers) ?? rules.diversity[rules.diversity.length - 1];
246
+ if (band === void 0) return 0;
247
+ return installedKva.reduce((sum, installed) => sum + (installed <= rules.installedSplitKva ? band.low : band.high), 0);
248
+ }
249
+ function pickTransformer(demandKva, rules) {
250
+ return [...rules.transformers].sort((a, b) => a.kva - b.kva).find((rating) => demandKva <= rating.kva * rules.maxLoading);
251
+ }
252
+
253
+ // src/networks/slots.ts
254
+ var POLE_SLOT_ORDER = ["mv", "transformer", "lv", "lighting", "telecom"];
255
+ var POLE_SLOT_GAPS = { transformer: 0.3, lv: 0, lighting: 0, telecom: 0.4 };
256
+ var DEFAULT_POLE_SLOTS = {
257
+ height: 11,
258
+ embedment: 1.7,
259
+ bands: { mv: [9, 9.25], transformer: [7.7, 8.7], lv: [7.1, 7.4], lighting: [6.5, 6.8], telecom: [5.7, 6.1] }
260
+ };
261
+ function checkPoleSlots(slots, gaps = POLE_SLOT_GAPS) {
262
+ const violations = [];
263
+ const above = slots.height - slots.embedment;
264
+ for (const band of POLE_SLOT_ORDER) {
265
+ const [bottom, top] = slots.bands[band];
266
+ if (bottom > top) violations.push({ code: "slot_inverted", band, value: bottom, limit: top });
267
+ if (bottom < 0) violations.push({ code: "slot_out_of_pole", band, value: bottom, limit: 0 });
268
+ if (top > above) violations.push({ code: "slot_out_of_pole", band, value: top, limit: above });
269
+ }
270
+ for (let index = 1; index < POLE_SLOT_ORDER.length; index++) {
271
+ const band = POLE_SLOT_ORDER[index];
272
+ const upper = POLE_SLOT_ORDER[index - 1];
273
+ const gap = slots.bands[upper][0] - slots.bands[band][1];
274
+ if (gap < gaps[band]) violations.push({ code: "slot_order", band, value: gap, limit: gaps[band] });
275
+ }
276
+ return violations;
277
+ }
278
+ var isPoleSlots = (value) => typeof value === "object" && value !== null && "bands" in value && "height" in value && "embedment" in value;
279
+ function slotsOfPole(pole) {
280
+ const slots = "slots" in pole.spec ? pole.spec.slots : void 0;
281
+ return isPoleSlots(slots) ? slots : void 0;
282
+ }
283
+
284
+ // src/networks/geometry.ts
285
+ function segmentCrossing(a0, a1, b0, b1) {
286
+ const rx = a1[0] - a0[0];
287
+ const rz = a1[1] - a0[1];
288
+ const sx = b1[0] - b0[0];
289
+ const sz = b1[1] - b0[1];
290
+ const denominator = rx * sz - rz * sx;
291
+ if (Math.abs(denominator) < 1e-12) return void 0;
292
+ const qx = b0[0] - a0[0];
293
+ const qz = b0[1] - a0[1];
294
+ const t = (qx * sz - qz * sx) / denominator;
295
+ const u = (qx * rz - qz * rx) / denominator;
296
+ const inside3 = (value) => value > 1e-9 && value < 1 - 1e-9;
297
+ return inside3(t) && inside3(u) ? [t, u] : void 0;
298
+ }
299
+ function pointInPolygon(point, outline) {
300
+ let inside3 = false;
301
+ for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {
302
+ const a = outline[index];
303
+ const b = outline[previous];
304
+ if (a[1] > point[1] !== b[1] > point[1] && point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]) inside3 = !inside3;
305
+ }
306
+ return inside3;
307
+ }
308
+ function segmentEntersPolygon(a, b, outline) {
309
+ if (outline.length < 3) return false;
310
+ if (pointInPolygon(a, outline) || pointInPolygon(b, outline)) return true;
311
+ for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {
312
+ if (segmentCrossing(a, b, outline[previous], outline[index]) !== void 0) return true;
313
+ }
314
+ return false;
315
+ }
316
+ function nearestShare(a, b, point) {
317
+ const dx = b[0] - a[0];
318
+ const dz = b[1] - a[1];
319
+ const length2 = dx * dx + dz * dz;
320
+ if (length2 === 0) return 0;
321
+ return Math.min(1, Math.max(0, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dz) / length2));
322
+ }
323
+ function catenaryHeight(fromY, toY, sag, t) {
324
+ return fromY + (toY - fromY) * t - 4 * sag * t * (1 - t);
325
+ }
326
+ function polygonCrossings(a, b, outline) {
327
+ const shares = [];
328
+ for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {
329
+ const crossing = segmentCrossing(a, b, outline[previous], outline[index]);
330
+ if (crossing !== void 0) shares.push(crossing[0]);
331
+ }
332
+ return shares.sort((first, second) => first - second);
333
+ }
334
+ function circleShares(a, b, centre, radius) {
335
+ const dx = b[0] - a[0];
336
+ const dz = b[1] - a[1];
337
+ const fx = a[0] - centre[0];
338
+ const fz = a[1] - centre[1];
339
+ const qa = dx * dx + dz * dz;
340
+ const qb = 2 * (fx * dx + fz * dz);
341
+ const qc = fx * fx + fz * fz - radius * radius;
342
+ if (qa === 0) return qc <= 0 ? [0, 1] : void 0;
343
+ const discriminant = qb * qb - 4 * qa * qc;
344
+ if (discriminant < 0) return void 0;
345
+ const root = Math.sqrt(discriminant);
346
+ const start = Math.max(0, (-qb - root) / (2 * qa));
347
+ const end = Math.min(1, (-qb + root) / (2 * qa));
348
+ return start <= end ? [start, end] : void 0;
349
+ }
350
+
351
+ // src/networks/validate-context.ts
352
+ function edgeEnds(context, edge) {
353
+ const from = context.graph.nodes.get(edge.from);
354
+ const to = context.graph.nodes.get(edge.to);
355
+ return from === void 0 || to === void 0 ? void 0 : [from, to];
356
+ }
357
+
358
+ // src/networks/validate-aerial.ts
359
+ var planOf = (node) => [node.at[0], node.at[2]];
360
+ function validateDrop(context, edge) {
361
+ const limit = edge.kind === "service_drop" ? context.rules.power.dropMaxLength : edge.kind === "telecom_drop" ? context.rules.telecom.dropMaxLength : void 0;
362
+ if (limit === void 0) return;
363
+ const length2 = edgeLength(context.graph, edge);
364
+ if (length2 > limit) context.report({ code: NETWORK_VIOLATION.DROP_TOO_LONG, id: edge.id, value: length2, limit });
365
+ }
366
+ function validateClearance(context, span) {
367
+ const row = context.rules.clearance[EDGE_CLASS[span.edge.kind]];
368
+ const samples = Math.max(1, context.rules.catenarySamples);
369
+ const lowest = /* @__PURE__ */ new Map();
370
+ for (let index = 0; index <= samples; index++) {
371
+ const t = index / samples;
372
+ const x = span.from.at[0] + (span.to.at[0] - span.from.at[0]) * t;
373
+ const z = span.from.at[2] + (span.to.at[2] - span.from.at[2]) * t;
374
+ const surface = context.options.surfaceAt === void 0 ? "road" : context.options.surfaceAt(x, z);
375
+ if (surface === void 0) continue;
376
+ const height = catenaryHeight(span.heights[0], span.heights[1], span.sag, t) - (context.options.groundAt?.(x, z) ?? 0);
377
+ lowest.set(surface, Math.min(lowest.get(surface) ?? Number.POSITIVE_INFINITY, height));
378
+ }
379
+ for (const [surface, height] of lowest) {
380
+ const limit = row[surface];
381
+ if (limit === null) context.report({ code: NETWORK_VIOLATION.MV_OVER_LOT, id: span.edge.id, detail: surface });
382
+ else if (height < limit) context.report({ code: NETWORK_VIOLATION.CLEARANCE, id: span.edge.id, detail: surface, value: height, limit });
383
+ }
384
+ }
385
+ var pointAt = (span, t) => [span.from.at[0] + (span.to.at[0] - span.from.at[0]) * t, span.from.at[2] + (span.to.at[2] - span.from.at[2]) * t];
386
+ function heightRange(context, span, start, end) {
387
+ const samples = Math.max(1, context.rules.catenarySamples);
388
+ let low = Number.POSITIVE_INFINITY;
389
+ let high = Number.NEGATIVE_INFINITY;
390
+ for (let index = 0; index <= samples; index++) {
391
+ const y = catenaryHeight(span.heights[0], span.heights[1], span.sag, start + (end - start) * index / samples);
392
+ low = Math.min(low, y);
393
+ high = Math.max(high, y);
394
+ }
395
+ return [low, high];
396
+ }
397
+ function overBuilding(span, building) {
398
+ const a = planOf(span.from);
399
+ const b = planOf(span.to);
400
+ const crossings = polygonCrossings(a, b, building.outline);
401
+ const ownLot = span.to.kind === "connection" && span.to.lot !== void 0 && building.lot === span.to.lot;
402
+ if (ownLot) return crossings.length >= 2 ? [crossings[0], crossings[crossings.length - 1]] : void 0;
403
+ if (!segmentEntersPolygon(a, b, building.outline)) return void 0;
404
+ const start = pointInPolygon(a, building.outline) ? 0 : crossings[0] ?? 0;
405
+ const end = pointInPolygon(b, building.outline) ? 1 : crossings[crossings.length - 1] ?? 1;
406
+ return [start, end];
407
+ }
408
+ function validateBuildings(context, span) {
409
+ for (const building of context.options.buildings ?? []) {
410
+ const over = overBuilding(span, building);
411
+ if (over === void 0) continue;
412
+ const middle = pointAt(span, (over[0] + over[1]) / 2);
413
+ const roof = (context.options.groundAt?.(middle[0], middle[1]) ?? 0) + building.height;
414
+ const [low] = heightRange(context, span, over[0], over[1]);
415
+ if (low < roof) context.report({ code: NETWORK_VIOLATION.SPAN_OVER_BUILDING, id: span.edge.id, detail: building.id, value: low, limit: roof });
416
+ }
417
+ }
418
+ function validateCrowns(context, span) {
419
+ for (const crown of context.options.obstacles?.crowns ?? []) {
420
+ const inside3 = circleShares(planOf(span.from), planOf(span.to), [crown.x, crown.z], crown.radius);
421
+ if (inside3 === void 0) continue;
422
+ const [low, high] = heightRange(context, span, inside3[0], inside3[1]);
423
+ if (low <= crown.top && high >= crown.bottom) context.report({ code: NETWORK_VIOLATION.SPAN_THROUGH_CROWN, id: span.edge.id, detail: `${crown.x},${crown.z}` });
424
+ }
425
+ }
426
+ function validateAerial(context) {
427
+ for (const edge of context.graph.edges.values()) {
428
+ if (!isAerialEdgeKind(edge.kind)) continue;
429
+ validateDrop(context, edge);
430
+ const ends = edgeEnds(context, edge);
431
+ if (ends === void 0) continue;
432
+ if (edge.sag === void 0) {
433
+ context.report({ code: NETWORK_VIOLATION.MISSING_SAG, id: edge.id });
434
+ continue;
435
+ }
436
+ const span = { edge, from: ends[0], to: ends[1], sag: edge.sag, heights: edge.heights ?? [ends[0].at[1], ends[1].at[1]] };
437
+ validateClearance(context, span);
438
+ validateBuildings(context, span);
439
+ validateCrowns(context, span);
440
+ }
441
+ }
442
+
443
+ // src/networks/validate-buried.ts
444
+ var SLOPE_TOLERANCE = 1e-3;
445
+ var lerp = (a, b, t) => a + (b - a) * t;
446
+ function groundAt(context, pipe, t) {
447
+ const x = lerp(pipe.from.at[0], pipe.to.at[0], t);
448
+ const z = lerp(pipe.from.at[2], pipe.to.at[2], t);
449
+ return context.options.groundAt?.(x, z) ?? lerp(pipe.from.at[1], pipe.to.at[1], t);
450
+ }
451
+ function pipeOf(context, edge) {
452
+ if (isAerialEdgeKind(edge.kind)) return void 0;
453
+ const ends = edgeEnds(context, edge);
454
+ if (ends === void 0) return void 0;
455
+ const inverts = edge.inverts ?? (ends[0].invert !== void 0 && ends[1].invert !== void 0 ? [ends[0].invert, ends[1].invert] : void 0);
456
+ if (inverts === void 0) context.report({ code: NETWORK_VIOLATION.MISSING_INVERT, id: edge.id });
457
+ if (edge.diameter === void 0) context.report({ code: NETWORK_VIOLATION.MISSING_DIAMETER, id: edge.id });
458
+ if (inverts === void 0 || edge.diameter === void 0) return void 0;
459
+ return { edge, kind: edge.kind, from: ends[0], to: ends[1], inverts, diameter: edge.diameter };
460
+ }
461
+ function validateSlope(context, pipe) {
462
+ if (pipe.kind === "water_main" || pipe.kind === "water_service") return;
463
+ const length2 = edgeLength(context.graph, pipe.edge);
464
+ if (length2 === 0) return;
465
+ const slope = (pipe.inverts[0] - pipe.inverts[1]) / length2;
466
+ const limit = context.rules.minSlope[pipe.kind];
467
+ if (slope < limit) context.report({ code: NETWORK_VIOLATION.SLOPE, id: pipe.edge.id, value: slope, limit });
468
+ if (pipe.edge.slope !== void 0 && Math.abs(pipe.edge.slope - slope) > SLOPE_TOLERANCE) context.report({ code: NETWORK_VIOLATION.SLOPE_MISMATCH, id: pipe.edge.id, value: pipe.edge.slope, limit: slope });
469
+ }
470
+ var planAt = (pipe, t) => [lerp(pipe.from.at[0], pipe.to.at[0], t), lerp(pipe.from.at[2], pipe.to.at[2], t)];
471
+ function besideGallery(context, main, pipes) {
472
+ const samples = Math.max(1, context.rules.catenarySamples);
473
+ const reach = context.rules.sewer.galleryReach;
474
+ return pipes.some((gallery) => {
475
+ if (gallery.kind !== "storm_gallery") return false;
476
+ const a = planAt(gallery, 0);
477
+ const b = planAt(gallery, 1);
478
+ for (let index = 0; index <= samples; index++) {
479
+ const point = planAt(main, index / samples);
480
+ const nearest = planAt(gallery, nearestShare(a, b, point));
481
+ if (Math.hypot(point[0] - nearest[0], point[1] - nearest[1]) <= reach) return true;
482
+ }
483
+ return false;
484
+ });
485
+ }
486
+ function validateCover(context, pipe, pipes) {
487
+ const base = context.rules.cover[pipe.kind];
488
+ const range = pipe.kind === "sewer_main" && besideGallery(context, pipe, pipes) ? { ...base, min: Math.max(base.min, context.rules.sewer.coverUnderGallery) } : base;
489
+ const samples = Math.max(1, context.rules.catenarySamples);
490
+ let least = Number.POSITIVE_INFINITY;
491
+ let most = Number.NEGATIVE_INFINITY;
492
+ let deepest = Number.NEGATIVE_INFINITY;
493
+ for (let index = 0; index <= samples; index++) {
494
+ const t = index / samples;
495
+ const ground = groundAt(context, pipe, t);
496
+ const invert = lerp(pipe.inverts[0], pipe.inverts[1], t);
497
+ least = Math.min(least, ground - invert - pipe.diameter);
498
+ most = Math.max(most, ground - invert - pipe.diameter);
499
+ deepest = Math.max(deepest, ground - invert);
500
+ }
501
+ if (least < range.min) context.report({ code: NETWORK_VIOLATION.COVER, id: pipe.edge.id, detail: "min", value: least, limit: range.min });
502
+ if (range.max !== void 0 && most > range.max) context.report({ code: NETWORK_VIOLATION.COVER, id: pipe.edge.id, detail: "max", value: most, limit: range.max });
503
+ const isSewer = pipe.kind === "sewer_main" || pipe.kind === "sewer_lateral";
504
+ if (isSewer && deepest > context.rules.sewer.maxDepth) context.report({ code: NETWORK_VIOLATION.TOO_DEEP, id: pipe.edge.id, value: deepest, limit: context.rules.sewer.maxDepth });
505
+ }
506
+ var shareEnds = (a, b) => a.from === b.from || a.from === b.to || a.to === b.from || a.to === b.to;
507
+ function validateCrossing(context, a, b) {
508
+ if (shareEnds(a.edge, b.edge)) return;
509
+ const crossing = segmentCrossing([a.from.at[0], a.from.at[2]], [a.to.at[0], a.to.at[2]], [b.from.at[0], b.from.at[2]], [b.to.at[0], b.to.at[2]]);
510
+ if (crossing === void 0) return;
511
+ const bottomA = lerp(a.inverts[0], a.inverts[1], crossing[0]);
512
+ const bottomB = lerp(b.inverts[0], b.inverts[1], crossing[1]);
513
+ const [upper, lower, upperBottom, lowerBottom] = bottomA >= bottomB ? [a, b, bottomA, bottomB] : [b, a, bottomB, bottomA];
514
+ const gap = upperBottom - (lowerBottom + lower.diameter);
515
+ const id = `${a.edge.id}x${b.edge.id}`;
516
+ const separation = context.rules.crossing.separation;
517
+ if (gap < separation) context.report({ code: NETWORK_VIOLATION.CROSSING_TOO_CLOSE, id, value: gap, limit: separation });
518
+ const rank = context.rules.crossing.rank;
519
+ if (rank[upper.kind] > rank[lower.kind]) context.report({ code: NETWORK_VIOLATION.CROSSING_ORDER, id, detail: `${upper.edge.id} above ${lower.edge.id}` });
520
+ const lateral = a.kind === "sewer_lateral" && b.kind === "storm_gallery" ? { pipe: a, t: crossing[0], bottom: bottomA } : b.kind === "sewer_lateral" && a.kind === "storm_gallery" ? { pipe: b, t: crossing[1], bottom: bottomB } : void 0;
521
+ if (lateral === void 0) return;
522
+ const depth = groundAt(context, lateral.pipe, lateral.t) - lateral.bottom;
523
+ const limit = context.rules.sewer.lateralOverGallery;
524
+ if (depth > limit) context.report({ code: NETWORK_VIOLATION.LATERAL_TOO_DEEP, id, value: depth, limit });
525
+ }
526
+ function validateSpacing(context, pipe) {
527
+ if (pipe.kind !== "sewer_main") return;
528
+ const length2 = edgeLength(context.graph, pipe.edge);
529
+ if (length2 > context.rules.sewer.manholeSpacing) context.report({ code: NETWORK_VIOLATION.MANHOLE_SPACING, id: pipe.edge.id, value: length2, limit: context.rules.sewer.manholeSpacing });
530
+ }
531
+ function validateBuried(context) {
532
+ const pipes = [];
533
+ for (const edge of context.graph.edges.values()) {
534
+ const pipe = pipeOf(context, edge);
535
+ if (pipe !== void 0) pipes.push(pipe);
536
+ }
537
+ for (const pipe of pipes) {
538
+ validateSlope(context, pipe);
539
+ validateCover(context, pipe, pipes);
540
+ validateSpacing(context, pipe);
541
+ }
542
+ for (let first = 0; first < pipes.length; first++) {
543
+ for (let second = first + 1; second < pipes.length; second++) validateCrossing(context, pipes[first], pipes[second]);
544
+ }
545
+ }
546
+
547
+ // src/networks/frame.ts
548
+ function worldOf({ frame, u, v }) {
549
+ return frame.along === "x" ? [u, frame.axis + v] : [frame.axis + v, u];
550
+ }
551
+ function frameOf({ frame, x, z }) {
552
+ return frame.along === "x" ? [x, z - frame.axis] : [z, x - frame.axis];
553
+ }
554
+ var UINT32 = 2 ** 32;
555
+ function hashOf({ seed, id }) {
556
+ let h = 2166136261 ^ seed >>> 0;
557
+ h = Math.imul(h, 16777619);
558
+ h ^= Math.floor(seed / UINT32) >>> 0;
559
+ h = Math.imul(h, 16777619);
560
+ for (let index = 0; index < id.length; index++) {
561
+ h ^= id.charCodeAt(index);
562
+ h = Math.imul(h, 16777619);
563
+ }
564
+ h ^= h >>> 16;
565
+ h = Math.imul(h, 2246822507);
566
+ h ^= h >>> 13;
567
+ h = Math.imul(h, 3266489909);
568
+ h ^= h >>> 16;
569
+ return (h >>> 0) / UINT32;
570
+ }
571
+ function countOf({ seed, id, range }) {
572
+ const [least, most] = range;
573
+ return least + Math.min(most - least, Math.floor(hashOf({ seed, id }) * (most - least + 1)));
574
+ }
575
+ var ordinal = (index) => String(index + 1).padStart(2, "0");
576
+ function planBins(size) {
577
+ const cells = /* @__PURE__ */ new Map();
578
+ const key = (i, k) => `${i},${k}`;
579
+ return {
580
+ add(x, z, item) {
581
+ const id = key(Math.floor(x / size), Math.floor(z / size));
582
+ cells.set(id, [...cells.get(id) ?? [], item]);
583
+ },
584
+ near(x, z, radius) {
585
+ const out = [];
586
+ const reach = Math.ceil(radius / size);
587
+ const [ci, ck] = [Math.floor(x / size), Math.floor(z / size)];
588
+ for (let i = ci - reach; i <= ci + reach; i++) for (let k = ck - reach; k <= ck + reach; k++) out.push(...cells.get(key(i, k)) ?? []);
589
+ return out;
590
+ }
591
+ };
592
+ }
593
+
594
+ // src/networks/drop-rules.ts
595
+ function dropMisfitOf({ frontage, pole, anchor, rules }) {
596
+ const [poleU, poleV] = frameOf({ frame: frontage.frame, x: pole.x, z: pole.z });
597
+ if (Math.abs(poleV) > frontage.reach) return void 0;
598
+ const [anchorU, anchorV] = frameOf({ frame: frontage.frame, x: anchor[0], z: anchor[2] });
599
+ if (Math.sign(poleV) === frontage.side) {
600
+ const [low, high] = frontage.span;
601
+ return poleU >= low - rules.dropFrontageSlack && poleU <= high + rules.dropFrontageSlack ? void 0 : "off_frontage";
602
+ }
603
+ const skew = Math.atan2(Math.abs(poleU - anchorU), Math.abs(poleV - anchorV)) * 180 / Math.PI;
604
+ return skew <= rules.dropMaxSkew ? void 0 : "skewed";
605
+ }
606
+ var inside = (x, z, rect) => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3];
607
+ function lotUnderDrop({ from, to, lot, frontages }) {
608
+ const steps = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[1] - from[1]) / 0.25));
609
+ for (let index = 0; index <= steps; index++) {
610
+ const t = index / steps;
611
+ const [x, z] = [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t];
612
+ const other = frontages.find((entry) => entry.lot !== lot && inside(x, z, entry.rect));
613
+ if (other) return other.lot;
614
+ }
615
+ return void 0;
616
+ }
617
+
618
+ // src/networks/validate-drops.ts
619
+ function validateDrops(context) {
620
+ const frontages = context.options.frontages;
621
+ const perPole = /* @__PURE__ */ new Map();
622
+ for (const edge of context.graph.edges.values()) {
623
+ if (edge.kind !== "service_drop" && edge.kind !== "telecom_drop") continue;
624
+ const ends = edgeEnds(context, edge);
625
+ if (!ends) continue;
626
+ const [pole, end] = ends;
627
+ if (edge.kind === "service_drop") perPole.set(pole.id, (perPole.get(pole.id) ?? 0) + 1);
628
+ const lot = end.lot;
629
+ if (frontages === void 0 || lot === void 0) continue;
630
+ const frontage = frontages.find((entry) => entry.lot === lot);
631
+ const misfit = frontage && dropMisfitOf({ frontage, pole: { x: pole.at[0], z: pole.at[2] }, anchor: end.at, rules: context.rules.power });
632
+ if (misfit === "skewed") context.report({ code: NETWORK_VIOLATION.DROP_SKEWED, id: edge.id, limit: context.rules.power.dropMaxSkew });
633
+ if (misfit === "off_frontage") context.report({ code: NETWORK_VIOLATION.DROP_OFF_FRONTAGE, id: edge.id, detail: pole.id });
634
+ const other = lotUnderDrop({ from: [pole.at[0], pole.at[2]], to: [end.at[0], end.at[2]], lot, frontages });
635
+ if (other !== void 0) context.report({ code: NETWORK_VIOLATION.DROP_OVER_OTHER_LOT, id: edge.id, detail: other });
636
+ }
637
+ for (const [pole, count] of perPole) {
638
+ if (count > context.rules.power.dropsPerPole) context.report({ code: NETWORK_VIOLATION.POLE_TOO_MANY_DROPS, id: pole, value: count, limit: context.rules.power.dropsPerPole });
639
+ }
640
+ }
641
+
642
+ // src/networks/validate-load.ts
643
+ function circuitDemand(context, transformerId) {
644
+ const circuit = circuitOf(context.graph, transformerId);
645
+ const installed = new Map((context.options.connections ?? []).filter((connection) => connection.network === "power").map((connection) => [connection.lot, connection.installedKva]));
646
+ const consumers = [];
647
+ let lights = 0;
648
+ for (const id of circuit.keys()) {
649
+ const node = context.graph.nodes.get(id);
650
+ if (node?.kind === "connection" && node.lot !== void 0) consumers.push(installed.get(node.lot) ?? 0);
651
+ lights += context.graph.outgoing(id, "lighting").length;
652
+ }
653
+ return diversifiedDemand(consumers, context.rules.power) + lights * context.rules.lighting.lampKva;
654
+ }
655
+ function validateLoad(context) {
656
+ const power = context.rules.power;
657
+ for (const node of context.graph.nodes.values()) {
658
+ if (node.kind !== "transformer") continue;
659
+ const rating = power.transformers.find((entry) => entry.id === node.spec);
660
+ if (rating === void 0) context.report({ code: NETWORK_VIOLATION.UNKNOWN_TRANSFORMER, id: node.id, detail: node.spec ?? "none" });
661
+ else {
662
+ const loading = circuitDemand(context, node.id) / rating.kva;
663
+ if (loading > power.maxLoading) context.report({ code: NETWORK_VIOLATION.TRANSFORMER_OVERLOADED, id: node.id, value: loading, limit: power.maxLoading });
664
+ }
665
+ const longest = Math.max(0, ...circuitOf(context.graph, node.id).values());
666
+ if (longest > power.lvCircuitMaxLength) context.report({ code: NETWORK_VIOLATION.LV_CIRCUIT_TOO_LONG, id: node.id, value: longest, limit: power.lvCircuitMaxLength });
667
+ }
668
+ }
669
+
670
+ // src/networks/validate-structure.ts
671
+ var NETWORKS = ["power_mv", "power_lv", "lighting", "telecom", "sewer", "storm", "water"];
672
+ function validateIds(context, networks) {
673
+ const seen = /* @__PURE__ */ new Set();
674
+ for (const entry of [...networks.nodes, ...networks.edges]) {
675
+ if (seen.has(entry.id)) context.report({ code: NETWORK_VIOLATION.DUPLICATE_ID, id: entry.id });
676
+ seen.add(entry.id);
677
+ }
678
+ for (const edge of context.graph.edges.values()) {
679
+ const network = EDGE_NETWORK[edge.kind];
680
+ for (const end of [edge.from, edge.to]) {
681
+ const node = context.graph.nodes.get(end);
682
+ if (node === void 0) context.report({ code: NETWORK_VIOLATION.UNKNOWN_NODE, id: edge.id, detail: end });
683
+ else if (!node.carries.includes(network)) context.report({ code: NETWORK_VIOLATION.NOT_CARRIED, id: edge.id, detail: `${end} does not carry ${network}` });
684
+ }
685
+ }
686
+ }
687
+ function validateTrees(context) {
688
+ for (const network of NETWORKS) {
689
+ const supply = NETWORK_FLOW[network] === "supply";
690
+ const connected = connectedNodes(context.graph, network);
691
+ for (const node of context.graph.nodes.values()) {
692
+ if (!node.carries.includes(network)) continue;
693
+ const links = supply ? context.graph.incoming(node.id, network) : context.graph.outgoing(node.id, network);
694
+ if (links.length > 1) context.report({ code: NETWORK_VIOLATION.NOT_RADIAL, id: node.id, detail: network, value: links.length, limit: 1 });
695
+ if (!connected.has(node.id)) context.report({ code: NETWORK_VIOLATION.DISCONNECTED, id: node.id, detail: network });
696
+ const back = supply ? context.graph.incoming(node.id, network) : context.graph.outgoing(node.id, network);
697
+ if (NETWORK_ENDS[network].includes(node.kind) && back.length > 0) context.report({ code: NETWORK_VIOLATION.LOOP_AT_END, id: node.id, detail: network });
698
+ }
699
+ }
700
+ }
701
+ function validateLots(context) {
702
+ const connections = context.options.connections ?? [];
703
+ const connectedByNetwork = /* @__PURE__ */ new Map();
704
+ const nodes = [...context.graph.nodes.values()];
705
+ const declared = /* @__PURE__ */ new Set();
706
+ for (const connection of connections) {
707
+ const id = `${connection.lot}:${connection.network}`;
708
+ if (declared.has(id)) {
709
+ context.report({ code: NETWORK_VIOLATION.LOT_DECLARED_TWICE, id });
710
+ continue;
711
+ }
712
+ declared.add(id);
713
+ if (connection.frame !== "world") {
714
+ context.report({ code: NETWORK_VIOLATION.CONNECTION_IN_PLAN_FRAME, id });
715
+ continue;
716
+ }
717
+ const network = CONNECTION_NETWORK[connection.network];
718
+ const matches = nodes.filter((node2) => node2.kind === "connection" && node2.lot === connection.lot && node2.carries.includes(network));
719
+ if (matches.length > 1) context.report({ code: NETWORK_VIOLATION.LOT_CONNECTED_TWICE, id, value: matches.length, limit: 1 });
720
+ const node = matches[0];
721
+ const connected = connectedByNetwork.get(network) ?? connectedNodes(context.graph, network);
722
+ connectedByNetwork.set(network, connected);
723
+ if (node === void 0 || !connected.has(node.id)) {
724
+ context.report({ code: NETWORK_VIOLATION.LOT_UNCONNECTED, id, detail: network });
725
+ continue;
726
+ }
727
+ const moved = Math.hypot(node.at[0] - connection.at[0], node.at[1] - connection.at[1], node.at[2] - connection.at[2]);
728
+ if (moved > context.rules.connectionTolerance) context.report({ code: NETWORK_VIOLATION.CONNECTION_MOVED, id, value: moved, limit: context.rules.connectionTolerance });
729
+ }
730
+ }
731
+ function validateOrphans(context) {
732
+ const connections = context.options.connections;
733
+ if (connections === void 0) return;
734
+ const declared = new Set(connections.map((connection) => `${connection.lot}:${CONNECTION_NETWORK[connection.network]}`));
735
+ for (const node of context.graph.nodes.values()) {
736
+ if (node.kind !== "connection") continue;
737
+ if (!node.carries.some((network) => declared.has(`${node.lot ?? ""}:${network}`))) context.report({ code: NETWORK_VIOLATION.ORPHAN_CONNECTION, id: node.id });
738
+ }
739
+ }
740
+
741
+ // src/networks/validate.ts
742
+ function validateNetworks(networks, options = {}) {
743
+ const violations = [];
744
+ const context = { graph: buildNetworkGraph(networks), rules: networks.rules, options, report: (violation) => violations.push(violation) };
745
+ validateIds(context, networks);
746
+ validateTrees(context);
747
+ validateLots(context);
748
+ validateOrphans(context);
749
+ validateAerial(context);
750
+ validateDrops(context);
751
+ validateBuried(context);
752
+ validateLoad(context);
753
+ return violations;
754
+ }
755
+
756
+ // src/pole-distribution.ts
757
+ var DISTRIBUTION = {
758
+ mast: { radiusTop: 0.12, radiusBottom: 0.22, height: 9.3, color: 9079428, segments: 4 },
759
+ arm: { reach: 1, y: 6.7, width: 2, height: 0.1, depth: 0.1, color: 6974054 },
760
+ lamp: { reach: 2, y: 6.55, width: 0.5, height: 0.16, depth: 0.3 },
761
+ lens: { lit: 16752704, unlit: 3815994 },
762
+ light: { color: 16751168, intensity: 1.3, distance: 20, y: 6.4 },
763
+ transformer: { offset: 0.45, y: 7.7, radius: 0.32, height: 1, color: 5922402, segments: 8 },
764
+ slots: DEFAULT_POLE_SLOTS,
765
+ crossarm: { reach: 0.3, width: 2, height: 0.1, depth: 0.09, color: 9211014 },
766
+ insulators: { at: [-0.55, 0.35, 1.15], radius: 0.04, color: 14210248 },
767
+ bushings: { spread: 0.16, radius: 0.025, height: 0.14, color: 11055288 },
768
+ lowVoltage: { out: 0.2, color: 6185060 },
769
+ telecom: { out: 0.18, color: 6185060 },
770
+ guy: { reach: 3, color: 8027262 }
771
+ };
772
+
773
+ // src/networks/circuits.ts
774
+ function circuitsOf({ system, consumers, span, rules, isService }) {
775
+ const power = rules.power;
776
+ const capacity = Math.max(...power.transformers.map((rating) => rating.kva)) * power.maxLoading;
777
+ const longest = 2 * power.lvCircuitMaxLength - rules.layout.poles.spacing[1];
778
+ const demandOf = (open) => diversifiedDemand(open.installed, power) + open.poles.filter((pole) => !isService(pole)).length * rules.lighting.lampKva;
779
+ const closed = [];
780
+ const gather = (pole) => {
781
+ const parts = (system.children.get(pole) ?? []).map((child) => {
782
+ const open2 = gather(child);
783
+ return { ...open2, height: open2.height + span({ from: pole, to: child }) };
784
+ });
785
+ parts.sort((a, b) => b.height - a.height);
786
+ const own = () => {
787
+ const heights = parts.map((part) => part.height);
788
+ return {
789
+ poles: [pole, ...parts.flatMap((part) => part.poles)],
790
+ height: Math.max(0, ...heights),
791
+ diameter: Math.max(0, ...parts.map((part) => part.diameter), (heights[0] ?? 0) + (heights[1] ?? 0)),
792
+ installed: [...consumers.get(pole) ?? [], ...parts.flatMap((part) => part.installed)]
793
+ };
794
+ };
795
+ let open = own();
796
+ while (parts.length > 0 && (open.diameter > longest || demandOf(open) > capacity)) {
797
+ closed.push(parts.shift());
798
+ open = own();
799
+ }
800
+ return open;
801
+ };
802
+ closed.push(gather(system.root));
803
+ return closed.map((open) => {
804
+ const transformer = centreOf({ poles: open.poles, system, span, isService });
805
+ const demand = demandOf(open);
806
+ const rating = pickTransformer(demand, power);
807
+ return { poles: open.poles, transformer, rating: rating?.id ?? power.transformers[power.transformers.length - 1]?.id ?? "none", demand, over: rating === void 0 };
808
+ });
809
+ }
810
+ function distancesWithin({ poles, from, system, span }) {
811
+ const members = new Set(poles);
812
+ const distance2 = /* @__PURE__ */ new Map([[from, 0]]);
813
+ const pending = [from];
814
+ while (pending.length > 0) {
815
+ const id = pending.pop();
816
+ const up = system.parent.get(id);
817
+ const near = [...system.children.get(id) ?? [], ...up === void 0 ? [] : [up]].filter((next) => members.has(next) && !distance2.has(next));
818
+ for (const next of near) {
819
+ distance2.set(next, (distance2.get(id) ?? 0) + span({ from: id, to: next }));
820
+ pending.push(next);
821
+ }
822
+ }
823
+ return distance2;
824
+ }
825
+ function centreOf({ poles, system, span, isService }) {
826
+ let best = poles.find((pole) => !isService(pole)) ?? poles[0];
827
+ let bestReach = Number.POSITIVE_INFINITY;
828
+ for (const pole of poles) {
829
+ if (isService(pole)) continue;
830
+ const reach = Math.max(...distancesWithin({ poles, from: pole, system, span }).values());
831
+ if (reach < bestReach - 1e-9) {
832
+ best = pole;
833
+ bestReach = reach;
834
+ }
835
+ }
836
+ return best;
837
+ }
838
+
839
+ // src/networks/pole-tree.ts
840
+ var planDistance = (a, b) => Math.hypot(a.x - b.x, a.z - b.z);
841
+ var spotOf = (station) => `${Math.round(station.x * 20)},${Math.round(station.z * 20)}`;
842
+ function polesAndSpans(chains) {
843
+ const poles = /* @__PURE__ */ new Map();
844
+ const bySpot = /* @__PURE__ */ new Map();
845
+ const spans = /* @__PURE__ */ new Map();
846
+ const link = (a, b) => {
847
+ if (a === b) return;
848
+ spans.set(a, (spans.get(a) ?? /* @__PURE__ */ new Set()).add(b));
849
+ spans.set(b, (spans.get(b) ?? /* @__PURE__ */ new Set()).add(a));
850
+ };
851
+ for (const chain of chains) {
852
+ let previous;
853
+ for (const station of chain) {
854
+ const id = bySpot.get(spotOf(station)) ?? station.id;
855
+ if (!poles.has(id)) {
856
+ poles.set(id, { id, station });
857
+ bySpot.set(spotOf(station), id);
858
+ }
859
+ if (previous !== void 0) link(previous, id);
860
+ previous = id;
861
+ }
862
+ }
863
+ linkCorners(poles, link);
864
+ return { poles, spans };
865
+ }
866
+ function linkCorners(poles, link) {
867
+ const corners = [...poles.values()].filter((pole) => pole.station.role === "corner");
868
+ const runs = new Map(corners.map((pole) => [pole.station.run.id, pole.station.run]));
869
+ for (const run of runs.values()) {
870
+ for (const crossing of run.crossings) {
871
+ const near = (pole, of, at, half) => pole.station.run.id === of.id && Math.abs(pole.station.u - at) <= half + 2;
872
+ const other = runs.get(crossing.run);
873
+ if (other === void 0 || other.id < run.id) continue;
874
+ const mine = corners.filter((pole) => near(pole, run, crossing.at, crossing.half));
875
+ const theirs = corners.filter((pole) => near(pole, other, run.axis, run.width / 2));
876
+ const pairs = mine.flatMap((a) => theirs.map((b) => [a, b])).sort((p, q) => planDistance(p[0].station, p[1].station) - planDistance(q[0].station, q[1].station) || (p[0].id + p[1].id < q[0].id + q[1].id ? -1 : 1));
877
+ const best = pairs[0];
878
+ if (best !== void 0) link(best[0].id, best[1].id);
879
+ }
880
+ }
881
+ }
882
+ function feedOf({ runs, sides, setback, fallback }) {
883
+ for (const run of runs) {
884
+ const v = (sides.get(run.id) ?? -1) * (run.width / 2 + setback);
885
+ if (run.ends[0] === "edge") return worldOf({ frame: run, u: run.from, v });
886
+ if (run.ends[1] === "edge") return worldOf({ frame: run, u: run.to, v });
887
+ }
888
+ return [fallback.station.x, fallback.station.z];
889
+ }
890
+ function treeFrom({ root, poles, spans }) {
891
+ const distance2 = /* @__PURE__ */ new Map([[root, 0]]);
892
+ const parent = /* @__PURE__ */ new Map();
893
+ const done = /* @__PURE__ */ new Set();
894
+ const order = [];
895
+ for (; ; ) {
896
+ const open = [...distance2.entries()].filter(([id2]) => !done.has(id2)).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1))[0];
897
+ if (open === void 0) break;
898
+ const [id, base] = open;
899
+ done.add(id);
900
+ order.push(id);
901
+ for (const next of [...spans.get(id) ?? []].sort()) {
902
+ const length2 = base + planDistance(poles.get(id).station, poles.get(next).station);
903
+ if (done.has(next) || length2 >= (distance2.get(next) ?? Number.POSITIVE_INFINITY)) continue;
904
+ distance2.set(next, length2);
905
+ parent.set(next, id);
906
+ }
907
+ }
908
+ const children = /* @__PURE__ */ new Map();
909
+ const depth = /* @__PURE__ */ new Map();
910
+ for (const id of order) {
911
+ const up = parent.get(id);
912
+ depth.set(id, up === void 0 ? 0 : (depth.get(up) ?? 0) + 1);
913
+ if (up !== void 0) children.set(up, [...children.get(up) ?? [], id]);
914
+ }
915
+ return { root, poles: order, parent, children, distance: distance2, depth };
916
+ }
917
+ function poleTreeOf({ chains, sides, setback }) {
918
+ const { poles, spans } = polesAndSpans(chains);
919
+ const systems = [];
920
+ const seen = /* @__PURE__ */ new Set();
921
+ for (const pole of poles.values()) {
922
+ if (seen.has(pole.id)) continue;
923
+ const members = treeFrom({ root: pole.id, poles, spans }).poles;
924
+ for (const id of members) seen.add(id);
925
+ const runs = [...new Map(members.map((id) => poles.get(id).station.run).map((run) => [run.id, run])).values()];
926
+ const feed = feedOf({ runs, sides, setback, fallback: pole });
927
+ const along = (id) => Math.hypot(poles.get(id).station.x - feed[0], poles.get(id).station.z - feed[1]);
928
+ const root = [...members].filter((id) => poles.get(id).station.role !== "service").sort((a, b) => along(a) - along(b))[0] ?? pole.id;
929
+ systems.push({ ...treeFrom({ root, poles, spans }), feed });
930
+ }
931
+ return { poles, systems };
932
+ }
933
+ var spanLength = ({ tree, from, to }) => planDistance(tree.poles.get(from).station, tree.poles.get(to).station);
934
+
935
+ // src/networks/aerial.ts
936
+ function poleHeightsOf(slots) {
937
+ const { mv, transformer, lv, lighting, telecom } = slots.bands;
938
+ return { mv: mv[1], transformer: (transformer[0] + transformer[1]) / 2, transformerBottom: transformer[0], lv: lv[1] - 0.1, lamp: lighting[0] + 0.1, telecom: telecom[1] };
939
+ }
940
+ function poleFinder(tree) {
941
+ const bins = planBins(40);
942
+ for (const pole of tree.poles.values()) bins.add(pole.station.x, pole.station.z, pole);
943
+ const all = [...tree.poles.values()];
944
+ return ({ x, z, radius }) => {
945
+ const near = bins.near(x, z, radius);
946
+ const pool = near.length > 0 ? near : all;
947
+ return pool.sort((a, b) => Math.hypot(a.station.x - x, a.station.z - z) - Math.hypot(b.station.x - x, b.station.z - z) || (a.id < b.id ? -1 : 1));
948
+ };
949
+ }
950
+ function lampOf({ pole, rules, lampReach }) {
951
+ const { run, side, u, role } = pole.station;
952
+ if (role === "service") return void 0;
953
+ return worldOf({ frame: run, u, v: side * (run.width / 2 + rules.layout.poles.curbSetback - lampReach) });
954
+ }
955
+ function poleAt(tree, at) {
956
+ if (at === void 0) return void 0;
957
+ return [...tree.poles.values()].find((pole) => Math.hypot(pole.station.x - at.x, pole.station.z - at.z) < 1e-6);
958
+ }
959
+ function dropsOf(params) {
960
+ const find = poleFinder(params.tree);
961
+ const out = /* @__PURE__ */ new Map();
962
+ for (const connection of params.connections) {
963
+ const pole = poleAt(params.tree, params.feeds.get(`${connection.lot}:power`)) ?? find({ x: connection.at[0], z: connection.at[2], radius: params.rules.power.dropMaxLength })[0];
964
+ if (pole !== void 0) out.set(pole.id, [...out.get(pole.id) ?? [], connection]);
965
+ }
966
+ return out;
967
+ }
968
+ function powerPlanOf({ params, drops }) {
969
+ const span = ({ from, to }) => spanLength({ tree: params.tree, from, to });
970
+ const isService = (pole) => params.tree.poles.get(pole)?.station.role === "service";
971
+ return params.tree.systems.map((system) => {
972
+ const consumers = new Map(system.poles.map((pole) => [pole, (drops.get(pole) ?? []).map((connection) => connection.installedKva ?? 0)]));
973
+ const circuits = circuitsOf({ system, consumers, span, rules: params.rules, isService });
974
+ const medium = new Set(system.poles.filter((pole) => !isService(pole)));
975
+ for (const circuit of circuits) {
976
+ for (let pole = circuit.transformer; pole !== void 0 && !medium.has(pole); pole = system.parent.get(pole)) medium.add(pole);
977
+ }
978
+ return { system, circuits, medium };
979
+ });
980
+ }
981
+ function layPower(params) {
982
+ const { tree, heights, rules, sink } = params;
983
+ const sag = rules.layout.sag;
984
+ const drops = dropsOf(params);
985
+ for (const { system, circuits, medium } of powerPlanOf({ params, drops })) {
986
+ const feed = `feed:${system.root}`;
987
+ sink.nodes.push({ id: feed, kind: "feed", at: [system.feed[0], heights.mv, system.feed[1]], carries: ["power_mv"] });
988
+ for (const id of system.poles) {
989
+ const pole = tree.poles.get(id);
990
+ const lamp = lampOf({ pole, rules, lampReach: params.pole.lampReach });
991
+ const carries = [...medium.has(id) ? ["power_mv"] : [], "power_lv", ...lamp === void 0 ? [] : ["lighting"], "telecom"];
992
+ sink.nodes.push({ id, kind: "pole", at: [pole.station.x, 0, pole.station.z], carries, spec: params.pole.id, ...pole.station.role === "line" || pole.station.role === "service" ? {} : { guyed: true } });
993
+ if (medium.has(id)) sink.edges.push({ id: `mv:${id}`, kind: "mv_span", from: system.parent.get(id) ?? feed, to: id, sag: sag.mv, heights: [heights.mv, heights.mv], conductors: 3 });
994
+ if (lamp === void 0) continue;
995
+ sink.nodes.push({ id: `light:${id}`, kind: "light", at: [lamp[0], heights.lamp, lamp[1]], carries: ["lighting"], spec: "street_light" });
996
+ sink.edges.push({ id: `light_feed:${id}`, kind: "light_feed", from: id, to: `light:${id}`, sag: 0, heights: [heights.lv, heights.lamp] });
997
+ }
998
+ for (const circuit of circuits) {
999
+ if (circuit.over) sink.warnings.push({ code: "transformer_over_capacity", id: `transformer:${circuit.transformer}`, detail: `${circuit.demand.toFixed(1)} kVA` });
1000
+ layCircuit({ params, system, circuit });
1001
+ }
1002
+ }
1003
+ for (const [poleId, connections] of drops) {
1004
+ for (const connection of connections) {
1005
+ const node = `lot:${connection.lot}:power`;
1006
+ sink.nodes.push({ id: node, kind: "connection", at: connection.at, carries: ["power_lv"], lot: connection.lot, ...params.unmetered.has(connection.lot) ? { spec: "unmetered" } : {} });
1007
+ sink.edges.push({ id: `drop:${connection.lot}`, kind: "service_drop", from: poleId, to: node, sag: sag.drop, heights: [heights.lv, connection.at[1]], conductors: 2 });
1008
+ }
1009
+ }
1010
+ }
1011
+ function layCircuit({ params, system, circuit }) {
1012
+ const { tree, heights, sink } = params;
1013
+ const pole = tree.poles.get(circuit.transformer);
1014
+ const id = `transformer:${circuit.transformer}`;
1015
+ sink.nodes.push({ id, kind: "transformer", at: [pole.station.x, heights.transformer, pole.station.z], carries: ["power_mv", "power_lv"], spec: circuit.rating });
1016
+ sink.edges.push({ id: `mv:${id}`, kind: "mv_span", from: circuit.transformer, to: id, sag: 0, heights: [heights.mv, heights.transformer] });
1017
+ sink.edges.push({ id: `lv:${circuit.transformer}`, kind: "lv_span", from: id, to: circuit.transformer, sag: 0, heights: [heights.transformerBottom, heights.lv] });
1018
+ const span = ({ from, to }) => spanLength({ tree, from, to });
1019
+ const order = [...distancesWithin({ poles: circuit.poles, from: circuit.transformer, system, span }).entries()].sort((a, b) => a[1] - b[1]);
1020
+ const members = new Set(circuit.poles);
1021
+ const reached = /* @__PURE__ */ new Set([circuit.transformer]);
1022
+ for (const [from] of order) {
1023
+ const up = system.parent.get(from);
1024
+ const near = [...system.children.get(from) ?? [], ...up === void 0 ? [] : [up]].filter((next) => members.has(next) && !reached.has(next));
1025
+ for (const next of near) {
1026
+ reached.add(next);
1027
+ sink.edges.push({ id: `lv:${next}`, kind: "lv_span", from, to: next, sag: params.rules.layout.sag.lv, heights: [heights.lv, heights.lv], conductors: 4 });
1028
+ }
1029
+ }
1030
+ }
1031
+
1032
+ // src/networks/connections.ts
1033
+ function defaultConnectionsOf({ served, rules, groundAt: groundAt2 }) {
1034
+ const { run, side, span, front, lot } = served;
1035
+ const rule = rules.layout.connection;
1036
+ const within = (u) => Math.min(Math.max(u, span[0]), span[1]);
1037
+ const centre = (span[0] + span[1]) / 2;
1038
+ const at = (u, v, above) => {
1039
+ const [x, z] = worldOf({ frame: run, u: within(u), v });
1040
+ return [x, groundAt2(x, z) + above, z];
1041
+ };
1042
+ const wall = side * (front + rule.frontInset);
1043
+ const sewer = at(centre, side * (front + rule.sewerInset), 0);
1044
+ const base = { lot: lot.id, frame: "world" };
1045
+ return [
1046
+ { ...base, network: "power", at: at(span[0] + rule.meterFromSide, wall, rule.powerHeight) },
1047
+ { ...base, network: "telecom", at: at(span[0] + rule.meterFromSide, wall, rule.powerHeight - rule.telecomBelowPower) },
1048
+ { ...base, network: "sewer", at: sewer, invert: sewer[1] - sewerDepthOf({ rules, length: front + rule.sewerInset - rules.layout.sewer.dropOffset }) },
1049
+ { ...base, network: "storm", at: at(span[1] - rule.downspoutFromSide, side * (run.width / 2), 0) },
1050
+ { ...base, network: "water", at: at(span[0] + rule.waterFromSide, wall, 0) }
1051
+ ];
1052
+ }
1053
+ function sewerDepthOf({ rules, length: length2 }) {
1054
+ const { connection, slopeMargin, coverMargin } = rules.layout;
1055
+ const fits = rules.sewer.lateralOverGallery - coverMargin - (rules.minSlope.sewer_lateral + slopeMargin) * length2;
1056
+ return Math.max(connection.sewerLeastDepth, Math.min(connection.sewerDepth, fits));
1057
+ }
1058
+ function lotConnectionsOf({ served, declared, rules, groundAt: groundAt2 }) {
1059
+ const own = new Map(declared.map((connection) => [`${connection.lot}:${connection.network}`, connection]));
1060
+ return served.flatMap((entry) => defaultConnectionsOf({ served: entry, rules, groundAt: groundAt2 }).map((fallback) => own.get(`${entry.lot.id}:${fallback.network}`) ?? fallback));
1061
+ }
1062
+ var ofNetwork2 = ({ connections, network }) => connections.filter((connection) => connection.network === network);
1063
+
1064
+ // src/networks/pole-layout.ts
1065
+ function piecesOf(run) {
1066
+ const out = [];
1067
+ let start = run.from;
1068
+ let startEnd = run.ends[0];
1069
+ for (const crossing of run.crossings) {
1070
+ out.push({ from: start, to: crossing.at - crossing.half, ends: [startEnd, "crossing"] });
1071
+ start = crossing.at + crossing.half;
1072
+ startEnd = "crossing";
1073
+ }
1074
+ out.push({ from: start, to: run.to, ends: [startEnd, run.ends[1]] });
1075
+ return out.filter((piece) => piece.to - piece.from > 1);
1076
+ }
1077
+ var inside2 = (x, z, rect) => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3];
1078
+ function lineOf(params) {
1079
+ const lateral = params.side * (params.run.width / 2 + params.rules.poles.curbSetback);
1080
+ const place = (u) => worldOf({ frame: params.run, u, v: lateral });
1081
+ return { place, isFree: (u) => !params.avoid.some((rect) => inside2(...place(u), rect)) };
1082
+ }
1083
+ function slideClear({ u, bounds, isFree, poles }) {
1084
+ for (let step = 0; step <= poles.slide / poles.slideStep; step++) {
1085
+ for (const offset of step === 0 ? [0] : [step * poles.slideStep, -step * poles.slideStep]) {
1086
+ const candidate = u + offset;
1087
+ if (candidate >= bounds.low && candidate <= bounds.high && isFree(candidate)) return candidate;
1088
+ }
1089
+ }
1090
+ return void 0;
1091
+ }
1092
+ function nextStation({ at, last, bounds, boundaries, params }) {
1093
+ const { poles } = params.rules;
1094
+ const { isFree } = lineOf(params);
1095
+ const target = at + (last - at) / Math.ceil((last - at) / poles.spacing[1]);
1096
+ const reach = { low: Math.max(bounds.low, at + 1), high: Math.min(bounds.high, at + poles.spacing[1]) };
1097
+ const inReach = boundaries.filter((u) => u >= reach.low && u <= reach.high).sort((a, b) => Math.abs(a - target) - Math.abs(b - target) || a - b);
1098
+ const first = inReach[0] !== void 0 && Math.abs(inReach[0] - target) <= poles.snap ? inReach[0] : Math.min(Math.max(target, reach.low), reach.high);
1099
+ for (const candidate of [first, ...inReach]) {
1100
+ const slid = slideClear({ u: candidate, bounds: reach, isFree, poles });
1101
+ if (slid !== void 0) return slid;
1102
+ }
1103
+ for (let u = reach.high; u >= reach.low; u -= poles.slideStep) if (isFree(u)) return u;
1104
+ params.warn({ code: "pole_on_avoid", id: `${params.run.id}@${first.toFixed(2)}` });
1105
+ return first;
1106
+ }
1107
+ function piecePoles({ piece, params, boundaries }) {
1108
+ const { poles } = params.rules;
1109
+ const { isFree } = lineOf(params);
1110
+ const endAt = (end, at2, inward) => {
1111
+ const u = at2 + inward * (end === "crossing" ? poles.curbSetback : poles.endInset);
1112
+ const role = end === "crossing" ? "corner" : "end";
1113
+ for (let step = 0; step <= poles.slide / poles.slideStep; step++) {
1114
+ const candidate = u + inward * step * poles.slideStep;
1115
+ if (isFree(candidate)) return { u: candidate, role };
1116
+ }
1117
+ params.warn({ code: "pole_on_avoid", id: `${params.run.id}@${u.toFixed(2)}` });
1118
+ return { u, role };
1119
+ };
1120
+ const first = endAt(piece.ends[0], piece.from, 1);
1121
+ const last = endAt(piece.ends[1], piece.to, -1);
1122
+ if (last.u - first.u < poles.spacing[0] / 4) return [{ u: (first.u + last.u) / 2, role: first.role }];
1123
+ const bounds = {
1124
+ low: piece.ends[0] === "crossing" ? piece.from + poles.crossingClearance : first.u,
1125
+ high: piece.ends[1] === "crossing" ? piece.to - poles.crossingClearance : last.u
1126
+ };
1127
+ const out = [first];
1128
+ let at = first.u;
1129
+ while (last.u - at > poles.spacing[1]) {
1130
+ const next = nextStation({ at, last: last.u, bounds, boundaries, params });
1131
+ if (next <= at + 1) break;
1132
+ out.push({ u: next, role: "line" });
1133
+ at = next;
1134
+ }
1135
+ out.push(last);
1136
+ return out;
1137
+ }
1138
+ function poleStationsOf(params) {
1139
+ const { run, side } = params;
1140
+ const boundaries = [...new Set(params.served.filter((entry) => entry.run.id === run.id).flatMap((entry) => [entry.span[0], entry.span[1]]))].sort((a, b) => a - b);
1141
+ const { place } = lineOf(params);
1142
+ return piecesOf(run).flatMap((piece) => piecePoles({ piece, params, boundaries })).map((station, index) => {
1143
+ const [x, z] = place(station.u);
1144
+ return { ...station, id: `pole:${run.id}:${ordinal(index)}`, run, side, x, z };
1145
+ });
1146
+ }
1147
+
1148
+ // src/networks/reach.ts
1149
+ var feedKey = (anchor) => `${anchor.lot}:${anchor.network}`;
1150
+ var distance = (station, anchor) => Math.hypot(station.x - anchor.at[0], station.z - anchor.at[2]);
1151
+ function inLine({ run, stations, anchor, params }) {
1152
+ const { poles } = params.rules;
1153
+ const [u] = frameOf({ frame: run, x: anchor.at[0], z: anchor.at[2] });
1154
+ const side = stations[0]?.side ?? -1;
1155
+ const lateral = side * (run.width / 2 + poles.curbSetback);
1156
+ const clear = (at) => stations.every((station) => Math.abs(station.u - at) >= poles.minGap);
1157
+ for (const piece of piecesOf(run)) {
1158
+ const [low, high] = [piece.from + poles.crossingClearance, piece.to - poles.crossingClearance];
1159
+ if (u < piece.from || u > piece.to || high < low) continue;
1160
+ for (let step = 0; step <= poles.slide / poles.slideStep; step++) {
1161
+ for (const offset of step === 0 ? [0] : [step * poles.slideStep, -step * poles.slideStep]) {
1162
+ const at = Math.min(Math.max(u + offset, low), high);
1163
+ const [x, z] = run.along === "x" ? [at, run.axis + lateral] : [run.axis + lateral, at];
1164
+ if (params.isFree(x, z) && clear(at)) return { id: "", run, side, u: at, x, z, role: "line" };
1165
+ }
1166
+ }
1167
+ }
1168
+ return void 0;
1169
+ }
1170
+ function chainTo({ from, anchor, params }) {
1171
+ const { poles } = params.rules;
1172
+ const gap = distance(from, anchor);
1173
+ const count = Math.max(0, Math.ceil(gap / poles.spacing[1]) - 1, Math.ceil(gap / (params.reach - 1)) - 1);
1174
+ const out = [];
1175
+ for (let index = 0; index < count; index++) {
1176
+ const even = (index + 1) * gap / (count + 1);
1177
+ const offsets = [0, ...Array.from({ length: Math.floor(poles.slide / poles.slideStep) }, (_, step) => [(step + 1) * poles.slideStep, -(step + 1) * poles.slideStep]).flat()];
1178
+ const spot = offsets.map((offset) => Math.min(Math.max(even + offset, 1), gap - 1) / gap).map((share) => ({ x: from.x + (anchor.at[0] - from.x) * share, z: from.z + (anchor.at[2] - from.z) * share })).find((point) => params.isFree(point.x, point.z) && params.canServe({ ...point, lot: anchor.lot }));
1179
+ if (spot === void 0) {
1180
+ params.warn({ code: "lot_out_of_reach", id: anchor.lot, detail: `${gap.toFixed(1)} m` });
1181
+ return void 0;
1182
+ }
1183
+ out.push({ ...from, id: `pole:${from.run.id}:lot:${anchor.lot}:${ordinal(index)}`, x: spot.x, z: spot.z, role: "service" });
1184
+ }
1185
+ return out;
1186
+ }
1187
+ function feedsAnchor({ station, anchor, params }) {
1188
+ if (Math.hypot(station.x - anchor.at[0], station.z - anchor.at[2]) > params.reach - 1e-6) return false;
1189
+ const frontage = params.frontages.get(anchor.lot);
1190
+ if (!frontage) return true;
1191
+ if (dropMisfitOf({ frontage, pole: station, anchor: anchor.at, rules: params.power }) !== void 0) return false;
1192
+ return lotUnderDrop({ from: [station.x, station.z], to: [anchor.at[0], anchor.at[2]], lot: anchor.lot, frontages: [...params.frontages.values()] }) === void 0;
1193
+ }
1194
+ function reachLots(params) {
1195
+ const runs = params.runs.map((stations) => [...stations]);
1196
+ const chains = [];
1197
+ const feeds = /* @__PURE__ */ new Map();
1198
+ const load = /* @__PURE__ */ new Map();
1199
+ const all = () => [...runs.flat(), ...chains.flat()];
1200
+ const take = (anchor, station) => {
1201
+ feeds.set(feedKey(anchor), station);
1202
+ if (anchor.network === "power") load.set(station, (load.get(station) ?? 0) + 1);
1203
+ };
1204
+ const free = (station) => (load.get(station) ?? 0) < params.power.dropsPerPole;
1205
+ const anchors = [...params.anchors].sort((a, b) => (a.network === "power" ? 0 : 1) - (b.network === "power" ? 0 : 1));
1206
+ for (const anchor of anchors) {
1207
+ const isPower = anchor.network === "power";
1208
+ const fits = (station) => feedsAnchor({ station, anchor, params }) && (!isPower || free(station));
1209
+ const power = feeds.get(`${anchor.lot}:power`);
1210
+ const nearest = power !== void 0 && !isPower && fits(power) ? power : all().filter(fits).sort((a, b) => distance(a, anchor) - distance(b, anchor))[0];
1211
+ if (nearest) {
1212
+ take(anchor, nearest);
1213
+ continue;
1214
+ }
1215
+ const served = params.served.get(anchor.lot);
1216
+ const stations = runs.find((entry) => entry[0]?.run.id === served?.run.id);
1217
+ if (served === void 0 || stations === void 0) continue;
1218
+ const added = inLine({ run: served.run, stations, anchor, params });
1219
+ if (added !== void 0) stations.push(added);
1220
+ stations.sort((a, b) => a.u - b.u);
1221
+ const from = added ?? [...stations].sort((a, b) => distance(a, anchor) - distance(b, anchor))[0];
1222
+ if (from === void 0) continue;
1223
+ if (distance(from, anchor) <= params.reach - 1e-6) {
1224
+ if (!fits(from)) params.warn({ code: "drop_off_practice", id: anchor.lot, detail: "no pole in front of the lot or straight across the street" });
1225
+ take(anchor, from);
1226
+ continue;
1227
+ }
1228
+ const chain = chainTo({ from, anchor, params });
1229
+ if (chain === void 0) continue;
1230
+ chains.push([from, ...chain]);
1231
+ take(anchor, chain[chain.length - 1] ?? from);
1232
+ }
1233
+ const renumbered = runs.map((stations) => stations.map((station, index) => ({ ...station, id: `pole:${station.run.id}:${ordinal(index)}` })));
1234
+ return { runs: renumbered, chains, feeds: new Map([...feeds].map(([lot, station]) => [lot, { x: station.x, z: station.z }])) };
1235
+ }
1236
+
1237
+ // src/networks/runs.ts
1238
+ var isStreet = (line) => line.kind === "street" || line.kind === "avenue";
1239
+ function segmentsOf(line) {
1240
+ const out = [];
1241
+ for (let index = 1; index < line.points.length; index++) {
1242
+ const [a, b] = [line.points[index - 1], line.points[index]];
1243
+ if (a === void 0 || b === void 0) continue;
1244
+ if (Math.abs(a[1] - b[1]) < 1e-9) out.push({ line, along: "x", axis: a[1], from: Math.min(a[0], b[0]), to: Math.max(a[0], b[0]) });
1245
+ else if (Math.abs(a[0] - b[0]) < 1e-9) out.push({ line, along: "z", axis: a[0], from: Math.min(a[1], b[1]), to: Math.max(a[1], b[1]) });
1246
+ else throw new Error(`networks: the line "${line.id}" has a stretch that is not along x or z; the generator lays straight streets only`);
1247
+ }
1248
+ return out;
1249
+ }
1250
+ function riverCuts({ segment, rivers }) {
1251
+ const half = segment.line.width / 2;
1252
+ return rivers.flatMap((river) => {
1253
+ const riverHalf = river.line.width / 2;
1254
+ if (river.along === segment.along) return [];
1255
+ const across = river.axis;
1256
+ const reaches = segment.axis + half > river.from && segment.axis - half < river.to;
1257
+ return reaches && across + riverHalf > segment.from && across - riverHalf < segment.to ? [[across - riverHalf, across + riverHalf]] : [];
1258
+ });
1259
+ }
1260
+ function streetRunsOf({ plan, edgeReach }) {
1261
+ const lines = plan.lines ?? [];
1262
+ const [width, depth] = plan.size ?? [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
1263
+ const rivers = lines.filter((line) => line.kind === "river").flatMap(segmentsOf);
1264
+ const isEdge = (along, at) => Math.abs(at) >= (along === "x" ? width : depth) / 2 - edgeReach;
1265
+ const bare = lines.filter(isStreet).flatMap((line) => {
1266
+ const pieces = segmentsOf(line).flatMap((segment) => {
1267
+ const cuts = riverCuts({ segment, rivers }).sort((a, b) => a[0] - b[0]);
1268
+ const out = [];
1269
+ let start = segment.from;
1270
+ let startEnd = isEdge(segment.along, segment.from) ? "edge" : "line_end";
1271
+ for (const [cutFrom, cutTo] of cuts) {
1272
+ if (cutFrom > start) out.push({ line: line.id, along: segment.along, axis: segment.axis, width: line.width, from: start, to: cutFrom, ends: [startEnd, "river"] });
1273
+ start = Math.max(start, cutTo);
1274
+ startEnd = "river";
1275
+ }
1276
+ if (segment.to > start) out.push({ line: line.id, along: segment.along, axis: segment.axis, width: line.width, from: start, to: segment.to, ends: [startEnd, isEdge(segment.along, segment.to) ? "edge" : "line_end"] });
1277
+ return out;
1278
+ });
1279
+ return pieces.map((piece, index) => ({ ...piece, id: pieces.length > 1 ? `${line.id}_${index}` : line.id }));
1280
+ });
1281
+ return bare.map((run) => ({ ...run, crossings: crossingsOf({ run, runs: bare }) }));
1282
+ }
1283
+ function crossingsOf({ run, runs }) {
1284
+ return runs.filter((other) => other.along !== run.along && other.axis + other.width / 2 > run.from && other.axis - other.width / 2 < run.to).filter((other) => other.from <= run.axis + run.width / 2 && other.to >= run.axis - run.width / 2).map((other) => ({ run: other.id, at: other.axis, half: other.width / 2 })).sort((a, b) => a.at - b.at);
1285
+ }
1286
+ function servedBy({ lot, run }) {
1287
+ const [x0, z0, x1, z1] = lot.rect;
1288
+ const [ua, va] = frameOf({ frame: run, x: x0, z: z0 });
1289
+ const [ub, vb] = frameOf({ frame: run, x: x1, z: z1 });
1290
+ const [u0, u1, v0, v1] = [Math.min(ua, ub), Math.max(ua, ub), Math.min(va, vb), Math.max(va, vb)];
1291
+ const side = v0 + v1 >= 0 ? 1 : -1;
1292
+ const front = side > 0 ? Math.max(0, v0) : Math.max(0, -v1);
1293
+ const du = Math.max(0, run.from - u1, u0 - run.to);
1294
+ return { lot, run, side, span: [u0, u1], front, distance: Math.hypot(du, front) };
1295
+ }
1296
+ function servedLotsOf({ lots, runs }) {
1297
+ return lots.flatMap((lot) => {
1298
+ let best;
1299
+ for (const run of runs) {
1300
+ const candidate = servedBy({ lot, run });
1301
+ if (best === void 0 || candidate.distance < best.distance - 1e-9) best = candidate;
1302
+ }
1303
+ if (best === void 0) return [];
1304
+ const { distance: _distance, ...served } = best;
1305
+ return [served];
1306
+ });
1307
+ }
1308
+ function poleSidesOf({ runs, served }) {
1309
+ return new Map(
1310
+ runs.map((run) => {
1311
+ const own = served.filter((entry) => entry.run.id === run.id);
1312
+ const plus = own.filter((entry) => entry.side > 0).length;
1313
+ return [run.id, plus > own.length - plus ? 1 : -1];
1314
+ })
1315
+ );
1316
+ }
1317
+
1318
+ // src/networks/buried.ts
1319
+ var sideOf = ({ context, run }) => context.sides.get(run.id) ?? -1;
1320
+ var galleryOffset = (on) => sideOf(on) * on.context.rules.layout.storm.galleryOffset;
1321
+ function waterOffset(on) {
1322
+ const { sidewalk, water } = on.context.rules.layout;
1323
+ return -sideOf(on) * (on.run.width / 2 + sidewalk * water.sidewalkShare);
1324
+ }
1325
+ var reachOf = (context) => Math.max(0, ...context.runs.map((run) => run.width / 2)) + context.rules.layout.sidewalk;
1326
+ function topOf({ context, x, z, cover, diameter }) {
1327
+ return context.groundAt(x, z) - cover - context.rules.layout.coverMargin - diameter;
1328
+ }
1329
+ function pipesOf({ chains, diameter, slope }) {
1330
+ return chains.flatMap(
1331
+ (chain) => chain.slice(1).map((node, index) => {
1332
+ const from = chain[index];
1333
+ return { from: from.id, to: node.id, a: [from.x, from.z], b: [node.x, node.z], diameter, slope };
1334
+ })
1335
+ );
1336
+ }
1337
+ function laidOf({ edges, sink }) {
1338
+ const nodes = new Map(sink.nodes.map((node) => [node.id, node]));
1339
+ return edges.flatMap((edge) => {
1340
+ const [from, to] = [nodes.get(edge.from), nodes.get(edge.to)];
1341
+ const inverts = edge.inverts ?? (from?.invert !== void 0 && to?.invert !== void 0 ? [from.invert, to.invert] : void 0);
1342
+ return from === void 0 || to === void 0 || inverts === void 0 ? [] : [{ a: [from.at[0], from.at[2]], b: [to.at[0], to.at[2]], inverts }];
1343
+ });
1344
+ }
1345
+ function chainNodes(chains) {
1346
+ return [...new Map(chains.flat().map((node) => [node.id, node])).values()];
1347
+ }
1348
+
1349
+ // src/networks/chain.ts
1350
+ function chainsOf(params) {
1351
+ const joints = /* @__PURE__ */ new Map();
1352
+ const chains = params.line.segments.map((segment, index) => chainOf({ segment, index, params, joints }));
1353
+ return { chains, joints };
1354
+ }
1355
+ function chainOf({ segment, index, params, joints }) {
1356
+ const { run, ua, ub } = segment;
1357
+ const [low, high] = [Math.min(ua, ub), Math.max(ua, ub)];
1358
+ const place = (u) => worldOf({ frame: run, u, v: params.offset(run) });
1359
+ const vertex = (id) => {
1360
+ const found = params.line.vertices.get(id);
1361
+ return { id, x: found?.x ?? 0, z: found?.z ?? 0, role: "vertex" };
1362
+ };
1363
+ const points = [];
1364
+ for (const stop of params.stops) {
1365
+ if (stop.run.id !== run.id || stop.u < low - 1e-6 || stop.u > high + 1e-6 || joints.has(stop.key)) continue;
1366
+ if (Math.abs(stop.u - ua) < 0.05) joints.set(stop.key, segment.from);
1367
+ else if (Math.abs(stop.u - ub) < 0.05) joints.set(stop.key, segment.to);
1368
+ else {
1369
+ const [x, z] = place(stop.u);
1370
+ const id = `${params.prefix}:${stop.key}`;
1371
+ points.push({ u: stop.u, node: { id, x, z, role: "stop" } });
1372
+ joints.set(stop.key, id);
1373
+ }
1374
+ }
1375
+ if (params.spacing !== void 0) {
1376
+ const parts = Math.ceil((high - low) / params.spacing - 1e-9);
1377
+ for (let part = 1; part < parts; part++) {
1378
+ const u = low + (high - low) * part / parts;
1379
+ const [x, z] = place(u);
1380
+ points.push({ u, node: { id: `${params.prefix}:${run.id}:${ordinal(index)}:${ordinal(part - 1)}`, x, z, role: "spaced" } });
1381
+ }
1382
+ }
1383
+ const direction = ub >= ua ? 1 : -1;
1384
+ points.sort((a, b) => (a.u - b.u) * direction);
1385
+ return [vertex(segment.from), ...points.map((point) => point.node), vertex(segment.to)];
1386
+ }
1387
+
1388
+ // src/networks/interceptor.ts
1389
+ function riverOf({ rivers, x, z }) {
1390
+ let best;
1391
+ for (const river of rivers) {
1392
+ const last = river.points[river.points.length - 1];
1393
+ const before = river.points[river.points.length - 2];
1394
+ if (last === void 0 || before === void 0) continue;
1395
+ const along = Math.abs(last[0] - before[0]) < 1e-9 ? "z" : "x";
1396
+ const distance2 = along === "z" ? Math.abs(x - last[0]) : Math.abs(z - last[1]);
1397
+ if (best === void 0 || distance2 < best.distance) best = { along, end: along === "z" ? last[1] : last[0], distance: distance2 };
1398
+ }
1399
+ return best;
1400
+ }
1401
+ function interceptorsOf({ outlets, rivers, spacing, border }) {
1402
+ const lines = /* @__PURE__ */ new Map();
1403
+ for (const outlet of outlets) {
1404
+ const river = outlet.end === "river" ? riverOf({ rivers, x: outlet.x, z: outlet.z }) : void 0;
1405
+ if (river === void 0) {
1406
+ const way = outlet.outward ?? [1, 0];
1407
+ const along = way[0] !== 0 ? "x" : "z";
1408
+ const end = way[0] !== 0 ? Math.max(Math.abs(outlet.x) + 1, border[0]) * Math.sign(way[0]) : Math.max(Math.abs(outlet.z) + 1, border[1]) * Math.sign(way[1]);
1409
+ const at2 = along === "x" ? outlet.z : outlet.x;
1410
+ lines.set(`${along}:${at2.toFixed(3)}:${outlet.id}`, { along: along === "x" ? "x" : "z", at: at2, end, outlets: [outlet] });
1411
+ continue;
1412
+ }
1413
+ const at = river.along === "z" ? outlet.x : outlet.z;
1414
+ const key = `${river.along}:${at.toFixed(3)}`;
1415
+ const line = lines.get(key) ?? { along: river.along, at, end: river.end, outlets: [] };
1416
+ line.outlets.push(outlet);
1417
+ lines.set(key, line);
1418
+ }
1419
+ const nodes = [];
1420
+ const links = [];
1421
+ [...lines.values()].forEach((line, lineIndex) => {
1422
+ const station = (vertex) => line.along === "z" ? vertex.z : vertex.x;
1423
+ const downstream = (position) => -Math.abs(line.end - position);
1424
+ const ordered = [...line.outlets].sort((a, b) => downstream(station(a)) - downstream(station(b)));
1425
+ const treatment = `sewer:treatment:${ordinal(lineIndex)}`;
1426
+ const point = (position) => line.along === "z" ? { x: line.at, z: position } : { x: position, z: line.at };
1427
+ nodes.push({ id: treatment, ...point(line.end), kind: "treatment" });
1428
+ const stops = [...ordered.map((vertex) => ({ id: vertex.id, position: station(vertex) })), { id: treatment, position: line.end }];
1429
+ for (let index = 1; index < stops.length; index++) {
1430
+ const [from, to] = [stops[index - 1], stops[index]];
1431
+ const parts = Math.max(1, Math.ceil(Math.abs(to.position - from.position) / spacing - 1e-9));
1432
+ let previous = from.id;
1433
+ for (let part = 1; part < parts; part++) {
1434
+ const id = `sewer:interceptor:${ordinal(lineIndex)}:${ordinal(index - 1)}:${ordinal(part - 1)}`;
1435
+ nodes.push({ id, ...point(from.position + (to.position - from.position) * part / parts), kind: "manhole" });
1436
+ links.push({ from: previous, to: id });
1437
+ previous = id;
1438
+ }
1439
+ links.push({ from: previous, to: to.id });
1440
+ }
1441
+ });
1442
+ return { nodes, links };
1443
+ }
1444
+
1445
+ // src/networks/inverts.ts
1446
+ var length = (pipe) => Math.hypot(pipe.b[0] - pipe.a[0], pipe.b[1] - pipe.a[1]);
1447
+ function pass({ pipes, top, floor }) {
1448
+ const incoming = /* @__PURE__ */ new Map();
1449
+ const pending = /* @__PURE__ */ new Map();
1450
+ for (const pipe of pipes) {
1451
+ incoming.set(pipe.to, [...incoming.get(pipe.to) ?? [], pipe]);
1452
+ pending.set(pipe.to, (pending.get(pipe.to) ?? 0) + 1);
1453
+ if (!pending.has(pipe.from)) pending.set(pipe.from, 0);
1454
+ }
1455
+ const inverts = /* @__PURE__ */ new Map();
1456
+ const lifts = /* @__PURE__ */ new Map();
1457
+ const ready = [...pending.entries()].filter(([, count]) => count === 0).map(([id]) => id).sort();
1458
+ const outgoing = new Map(pipes.map((pipe) => [pipe.from, pipe]));
1459
+ while (ready.length > 0) {
1460
+ const id = ready.shift();
1461
+ const lowest = floor.get(id) ?? Number.NEGATIVE_INFINITY;
1462
+ const fromAbove = (incoming.get(id) ?? []).map((pipe) => {
1463
+ const reach = (lifts.get(pipe.from) ?? inverts.get(pipe.from) ?? 0) - pipe.slope * length(pipe);
1464
+ if (reach >= lowest - 1e-9 || lifts.has(pipe.from)) return reach;
1465
+ lifts.set(pipe.from, top.get(pipe.from) ?? 0);
1466
+ return (lifts.get(pipe.from) ?? 0) - pipe.slope * length(pipe);
1467
+ });
1468
+ inverts.set(id, Math.min(top.get(id) ?? Number.POSITIVE_INFINITY, ...fromAbove));
1469
+ const next = outgoing.get(id);
1470
+ if (next === void 0) continue;
1471
+ const left = (pending.get(next.to) ?? 1) - 1;
1472
+ pending.set(next.to, left);
1473
+ if (left === 0) ready.push(next.to);
1474
+ }
1475
+ return { inverts, lifts };
1476
+ }
1477
+ function crossingCandidates({ pipes, above }) {
1478
+ const size = 20;
1479
+ const cells = /* @__PURE__ */ new Map();
1480
+ const cellsOf = (a, b) => {
1481
+ const out = [];
1482
+ for (let i = Math.floor(Math.min(a[0], b[0]) / size); i <= Math.floor(Math.max(a[0], b[0]) / size); i++) {
1483
+ for (let k = Math.floor(Math.min(a[1], b[1]) / size); k <= Math.floor(Math.max(a[1], b[1]) / size); k++) out.push(`${i},${k}`);
1484
+ }
1485
+ return out;
1486
+ };
1487
+ for (const laid of above) for (const cell of cellsOf(laid.a, laid.b)) cells.set(cell, [...cells.get(cell) ?? [], laid]);
1488
+ return new Map(pipes.map((pipe) => [pipe, [...new Set(cellsOf(pipe.a, pipe.b).flatMap((cell) => cells.get(cell) ?? []))]]));
1489
+ }
1490
+ function solveDrainInverts({ pipes, top, floor = /* @__PURE__ */ new Map(), above = [], separation = 0 }) {
1491
+ const caps = new Map(top);
1492
+ const candidates = crossingCandidates({ pipes, above });
1493
+ let result = pass({ pipes, top: caps, floor });
1494
+ for (let round = 0; round < 16; round++) {
1495
+ let lowered = false;
1496
+ for (const pipe of pipes) {
1497
+ for (const laid of candidates.get(pipe) ?? []) {
1498
+ const crossing = segmentCrossing(pipe.a, pipe.b, laid.a, laid.b);
1499
+ if (crossing === void 0) continue;
1500
+ const need = laid.inverts[0] + (laid.inverts[1] - laid.inverts[0]) * crossing[1] - separation - pipe.diameter;
1501
+ const from = result.lifts.get(pipe.from) ?? result.inverts.get(pipe.from) ?? 0;
1502
+ const to = result.inverts.get(pipe.to) ?? 0;
1503
+ if (from + (to - from) * crossing[0] <= need + 1e-9) continue;
1504
+ caps.set(pipe.from, Math.min(caps.get(pipe.from) ?? Number.POSITIVE_INFINITY, need - 1e-3));
1505
+ lowered = true;
1506
+ }
1507
+ }
1508
+ if (!lowered) return result;
1509
+ result = pass({ pipes, top: caps, floor });
1510
+ }
1511
+ return result;
1512
+ }
1513
+
1514
+ // src/networks/line-network.ts
1515
+ function stationsOf({ run, params }) {
1516
+ const place = (u) => worldOf({ frame: run, u, v: params.offset(run) });
1517
+ const out = [];
1518
+ const position = run.axis + params.offset(run);
1519
+ for (const other of params.runs) {
1520
+ if (other.along === run.along) continue;
1521
+ const u = other.axis + params.offset(other);
1522
+ if (u < run.from - params.reach || u > run.to + params.reach || position < other.from - params.reach || position > other.to + params.reach) continue;
1523
+ const [x, z] = place(u);
1524
+ out.push({ u, vertex: { id: `${params.prefix}:x:${[run.id, other.id].sort().join(":")}`, x, z, role: "crossing" } });
1525
+ }
1526
+ const ends = [
1527
+ [run.ends[0] === "river" ? run.from + params.riverInset : run.from, run.ends[0], "start", -1],
1528
+ [run.ends[1] === "river" ? run.to - params.riverInset : run.to, run.ends[1], "end", 1]
1529
+ ];
1530
+ for (const [u, end, name, way] of ends) {
1531
+ if (out.some((station) => Math.abs(station.u - u) < 0.5)) continue;
1532
+ const [x, z] = place(u);
1533
+ const outward = run.along === "x" ? [way, 0] : [0, way];
1534
+ out.push({ u, vertex: { id: `${params.prefix}:${run.id}:${name}`, x, z, role: "end", end, outward } });
1535
+ }
1536
+ return out.sort((a, b) => a.u - b.u);
1537
+ }
1538
+ function lineNetworkOf(params) {
1539
+ const vertices = /* @__PURE__ */ new Map();
1540
+ const links = [];
1541
+ for (const run of params.runs) {
1542
+ const stations = stationsOf({ run, params });
1543
+ for (const station of stations) if (!vertices.has(station.vertex.id)) vertices.set(station.vertex.id, station.vertex);
1544
+ for (let index = 1; index < stations.length; index++) links.push({ run, a: stations[index - 1], b: stations[index] });
1545
+ }
1546
+ const roots = rootsOf({ vertices, links, flow: params.flow });
1547
+ const parent = shortestTree({ roots, links });
1548
+ const segments = [];
1549
+ let splits = 0;
1550
+ for (const link of links) {
1551
+ const [a, b] = [link.a.vertex.id, link.b.vertex.id];
1552
+ const toward = (from, to) => params.flow === "drain" ? { run: link.run, from: from.vertex.id, to: to.vertex.id, ua: from.u, ub: to.u } : { run: link.run, from: to.vertex.id, to: from.vertex.id, ua: to.u, ub: from.u };
1553
+ if (parent.get(a) === b) segments.push(toward(link.a, link.b));
1554
+ else if (parent.get(b) === a) segments.push(toward(link.b, link.a));
1555
+ else {
1556
+ const u = (link.a.u + link.b.u) / 2;
1557
+ const [x, z] = worldOf({ frame: link.run, u, v: params.offset(link.run) });
1558
+ const middle = { u, vertex: { id: `${params.prefix}:${link.run.id}:split:${ordinal(splits++)}`, x, z, role: "split" } };
1559
+ vertices.set(middle.vertex.id, middle.vertex);
1560
+ segments.push(toward(middle, link.a), toward(middle, link.b));
1561
+ }
1562
+ }
1563
+ return { vertices, segments, roots };
1564
+ }
1565
+ function componentsOf({ vertices, links }) {
1566
+ const near = /* @__PURE__ */ new Map();
1567
+ for (const link of links) {
1568
+ near.set(link.a.vertex.id, [...near.get(link.a.vertex.id) ?? [], link.b.vertex.id]);
1569
+ near.set(link.b.vertex.id, [...near.get(link.b.vertex.id) ?? [], link.a.vertex.id]);
1570
+ }
1571
+ const seen = /* @__PURE__ */ new Set();
1572
+ const out = [];
1573
+ for (const id of vertices.keys()) {
1574
+ if (seen.has(id)) continue;
1575
+ const group = [];
1576
+ const pending = [id];
1577
+ while (pending.length > 0) {
1578
+ const next = pending.pop();
1579
+ if (seen.has(next)) continue;
1580
+ seen.add(next);
1581
+ group.push(next);
1582
+ pending.push(...near.get(next) ?? []);
1583
+ }
1584
+ out.push(group);
1585
+ }
1586
+ return out;
1587
+ }
1588
+ function rootsOf({ vertices, links, flow }) {
1589
+ return componentsOf({ vertices, links }).flatMap((group) => {
1590
+ const ends = (end) => group.filter((id) => vertices.get(id)?.end === end);
1591
+ const river = flow === "drain" ? ends("river") : [];
1592
+ if (river.length > 0) return river;
1593
+ return [ends("edge")[0] ?? group[0]];
1594
+ });
1595
+ }
1596
+ function shortestTree({ roots, links }) {
1597
+ const near = /* @__PURE__ */ new Map();
1598
+ for (const link of links) {
1599
+ near.set(link.a.vertex.id, [...near.get(link.a.vertex.id) ?? [], [link.a, link.b]]);
1600
+ near.set(link.b.vertex.id, [...near.get(link.b.vertex.id) ?? [], [link.b, link.a]]);
1601
+ }
1602
+ const distance2 = new Map(roots.map((root) => [root, 0]));
1603
+ const parent = /* @__PURE__ */ new Map();
1604
+ const done = /* @__PURE__ */ new Set();
1605
+ for (; ; ) {
1606
+ const open = [...distance2.entries()].filter(([id2]) => !done.has(id2)).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1))[0];
1607
+ if (open === void 0) return parent;
1608
+ const [id, base] = open;
1609
+ done.add(id);
1610
+ for (const [here, there] of near.get(id) ?? []) {
1611
+ if (done.has(there.vertex.id)) continue;
1612
+ const length2 = base + Math.abs(there.u - here.u);
1613
+ if (length2 >= (distance2.get(there.vertex.id) ?? Number.POSITIVE_INFINITY)) continue;
1614
+ distance2.set(there.vertex.id, length2);
1615
+ parent.set(there.vertex.id, id);
1616
+ }
1617
+ }
1618
+ }
1619
+
1620
+ // src/networks/sewer.ts
1621
+ function lateralOf({ context, connection }) {
1622
+ const served = context.served.get(connection.lot);
1623
+ if (served === void 0 || connection.invert === void 0) return void 0;
1624
+ const { run, side } = served;
1625
+ const { sewer, slopeMargin, water, coverMargin } = context.rules.layout;
1626
+ const [u, v] = frameOf({ frame: run, x: connection.at[0], z: connection.at[2] });
1627
+ const length2 = Math.abs(v) - sewer.dropOffset;
1628
+ let fall = (context.rules.minSlope.sewer_lateral + slopeMargin) * length2;
1629
+ const main = waterOffset({ context, run });
1630
+ if (Math.sign(main) === side && Math.abs(main) < Math.abs(v) && Math.abs(main) > sewer.dropOffset) {
1631
+ const share = (Math.abs(v) - Math.abs(main)) / length2;
1632
+ const [x2, z2] = worldOf({ frame: run, u, v: main });
1633
+ const need = topOf({ context, x: x2, z: z2, cover: context.rules.cover.water_main.min, diameter: water.mainDiameter }) - context.rules.crossing.separation - sewer.lateralDiameter - coverMargin;
1634
+ fall = Math.max(fall, (connection.invert - need) / share);
1635
+ }
1636
+ const [x, z] = worldOf({ frame: run, u, v: side * sewer.dropOffset });
1637
+ const id = `sewer:drop:${connection.lot}`;
1638
+ return { connection, u, key: `saddle:${connection.lot}`, drop: { id, kind: "cleanout", at: [x, context.groundAt(x, z), z], invert: connection.invert - fall, carries: ["sewer"], spec: "drop" } };
1639
+ }
1640
+ function kindOf({ node, kinds }) {
1641
+ if (kinds.treatments.has(node.id)) return { kind: "treatment", spec: "treatment_plant" };
1642
+ if (kinds.lifts.has(node.id)) return { kind: "pumping_station", spec: "lift" };
1643
+ if (node.role === "stop") return { kind: "splice", spec: "saddle" };
1644
+ if (kinds.heads.has(node.id) && !kinds.roots.has(node.id)) return { kind: "cleanout", spec: "terminal" };
1645
+ return { kind: "manhole", spec: "pv_600" };
1646
+ }
1647
+ function mainsOf({ context, laterals }) {
1648
+ const { rules } = context;
1649
+ const { sewer, slopeMargin } = rules.layout;
1650
+ const line = lineNetworkOf({ prefix: "sewer", runs: context.runs, offset: () => 0, riverInset: sewer.interceptorOffset, reach: reachOf(context), flow: "drain" });
1651
+ const stops = laterals.flatMap((lateral) => {
1652
+ const served = context.served.get(lateral.connection.lot);
1653
+ return served === void 0 ? [] : [{ key: lateral.key, run: served.run, u: lateral.u }];
1654
+ });
1655
+ const { chains, joints } = chainsOf({ line, prefix: "sewer", offset: () => 0, stops, spacing: rules.sewer.manholeSpacing });
1656
+ const outlets = line.roots.flatMap((id) => [line.vertices.get(id)].filter((vertex) => vertex !== void 0));
1657
+ const interceptor = interceptorsOf({ outlets, rivers: context.rivers, spacing: rules.sewer.manholeSpacing, border: context.border });
1658
+ const slope = rules.minSlope.sewer_main + slopeMargin;
1659
+ const nodes = [...chainNodes(chains), ...interceptor.nodes.map((node) => ({ id: node.id, x: node.x, z: node.z, role: "vertex" }))];
1660
+ const where = new Map(nodes.map((node) => [node.id, node]));
1661
+ const pipes = [
1662
+ ...pipesOf({ chains, diameter: sewer.mainDiameter, slope }),
1663
+ ...interceptor.links.map((link) => {
1664
+ const [a, b] = [where.get(link.from), where.get(link.to)];
1665
+ return { from: link.from, to: link.to, a: [a?.x ?? 0, a?.z ?? 0], b: [b?.x ?? 0, b?.z ?? 0], diameter: sewer.mainDiameter, slope };
1666
+ })
1667
+ ];
1668
+ const treatments = new Set(interceptor.nodes.filter((node) => node.kind === "treatment").map((node) => node.id));
1669
+ return { line, nodes, where, pipes, joints, treatments };
1670
+ }
1671
+ function laySewer({ context, connections, above }) {
1672
+ const { rules, sink } = context;
1673
+ const { sewer, slopeMargin, coverMargin } = rules.layout;
1674
+ const laterals = connections.flatMap((connection) => lateralOf({ context, connection }) ?? []);
1675
+ const { line, nodes, where, pipes, joints, treatments } = mainsOf({ context, laterals });
1676
+ const top = new Map(nodes.map((node) => [node.id, topOf({ context, x: node.x, z: node.z, cover: rules.sewer.coverUnderGallery, diameter: sewer.mainDiameter })]));
1677
+ const floor = new Map(nodes.map((node) => [node.id, context.groundAt(node.x, node.z) - rules.sewer.maxDepth + coverMargin]));
1678
+ for (const lateral of laterals) {
1679
+ const joint = joints.get(lateral.key);
1680
+ const target = where.get(joint);
1681
+ const length2 = target === void 0 ? 0 : Math.hypot(target.x - lateral.drop.at[0], target.z - lateral.drop.at[2]);
1682
+ const highest = (lateral.drop.invert ?? 0) - (rules.minSlope.sewer_lateral + slopeMargin) * length2 - sewer.mainDiameter;
1683
+ top.set(joint, Math.min(top.get(joint) ?? Number.POSITIVE_INFINITY, highest));
1684
+ }
1685
+ const { inverts, lifts } = solveDrainInverts({ pipes, top, floor, above: laidOf({ edges: above, sink }), separation: rules.crossing.separation + coverMargin });
1686
+ const fed = new Set(pipes.map((pipe) => pipe.to));
1687
+ const heads = new Set(pipes.filter((pipe) => !fed.has(pipe.from)).map((pipe) => pipe.from));
1688
+ const kinds = { roots: new Set(line.roots), heads, lifts, treatments };
1689
+ for (const node of nodes) {
1690
+ const ground = context.groundAt(node.x, node.z);
1691
+ sink.nodes.push({ id: node.id, ...kindOf({ node, kinds }), at: [node.x, ground, node.z], invert: inverts.get(node.id) ?? ground, carries: ["sewer"] });
1692
+ }
1693
+ for (const pipe of pipes) {
1694
+ const lift = lifts.get(pipe.from);
1695
+ sink.edges.push({ id: `${pipe.from}>${pipe.to}`, kind: "sewer_main", from: pipe.from, to: pipe.to, diameter: sewer.mainDiameter, ...lift === void 0 ? {} : { inverts: [lift, inverts.get(pipe.to) ?? 0] } });
1696
+ }
1697
+ for (const lateral of laterals) {
1698
+ const { connection, drop } = lateral;
1699
+ const joint = joints.get(lateral.key);
1700
+ const lot = `lot:${connection.lot}:sewer`;
1701
+ sink.nodes.push({ id: lot, kind: "connection", at: connection.at, invert: connection.invert, carries: ["sewer"], lot: connection.lot }, drop);
1702
+ sink.edges.push({ id: `sewer:lateral:${connection.lot}`, kind: "sewer_lateral", from: lot, to: drop.id, diameter: sewer.lateralDiameter });
1703
+ sink.edges.push({ id: `${drop.id}>${joint}`, kind: "sewer_lateral", from: drop.id, to: joint, diameter: sewer.lateralDiameter, inverts: [drop.invert ?? 0, (inverts.get(joint) ?? 0) + sewer.mainDiameter] });
1704
+ }
1705
+ }
1706
+
1707
+ // src/networks/storm.ts
1708
+ function inletsOf(context) {
1709
+ const { storm, coverMargin } = context.rules.layout;
1710
+ const depth = context.rules.cover.storm_lateral.min + coverMargin + storm.lateralDiameter;
1711
+ return context.runs.flatMap(
1712
+ (run) => piecesOf(run).flatMap(
1713
+ (piece, pieceIndex) => [-1, 1].flatMap((curb) => {
1714
+ const [from, to] = [piece.from + storm.inletFromCorner, piece.to - storm.inletFromCorner];
1715
+ const gaps = Math.max(1, Math.ceil((to - from) / storm.inletSpacing - 1e-9));
1716
+ return Array.from({ length: gaps + 1 }, (_, index) => {
1717
+ const u = from + (to - from) * index / gaps;
1718
+ const [x, z] = worldOf({ frame: run, u, v: curb * (run.width / 2 - storm.inletSetback) });
1719
+ const key = `inlet:${run.id}:${curb > 0 ? "plus" : "minus"}:${ordinal(pieceIndex)}:${ordinal(index)}`;
1720
+ const ground = context.groundAt(x, z);
1721
+ return { id: `storm:${key}`, key, run, curb, u, node: { id: `storm:${key}`, kind: "inlet", at: [x, ground, z], invert: ground - depth, carries: ["storm"], spec: "grated_inlet" } };
1722
+ });
1723
+ })
1724
+ )
1725
+ );
1726
+ }
1727
+ function layStorm({ context, connections }) {
1728
+ const { rules, sink } = context;
1729
+ const { storm, slopeMargin, coverMargin } = rules.layout;
1730
+ const offset = (run) => galleryOffset({ context, run });
1731
+ const line = lineNetworkOf({ prefix: "storm", runs: context.runs, offset, riverInset: 0, reach: reachOf(context), flow: "drain" });
1732
+ const inlets = inletsOf(context);
1733
+ const stops = inlets.map((inlet) => ({ key: inlet.key, run: inlet.run, u: inlet.u }));
1734
+ const { chains, joints } = chainsOf({ line, prefix: "storm:gallery", offset, stops, spacing: rules.sewer.manholeSpacing });
1735
+ const nodes = chainNodes(chains);
1736
+ const where = new Map(nodes.map((node) => [node.id, node]));
1737
+ const top = new Map(nodes.map((node) => [node.id, topOf({ context, x: node.x, z: node.z, cover: rules.cover.storm_gallery.min, diameter: storm.galleryDiameter })]));
1738
+ const roots = new Set(line.roots);
1739
+ const sewerRun = (rules.minSlope.sewer_main + slopeMargin) * rules.sewer.manholeSpacing;
1740
+ const deepest = rules.sewer.maxDepth - rules.layout.sewer.mainDiameter - rules.crossing.separation - 3 * coverMargin - sewerRun;
1741
+ const floor = new Map(nodes.map((node) => [node.id, Math.max(context.groundAt(node.x, node.z) - deepest, roots.has(node.id) ? storm.riverLevel + coverMargin : Number.NEGATIVE_INFINITY)]));
1742
+ const laterals = inlets.map((inlet) => {
1743
+ const joint = joints.get(inlet.key);
1744
+ const target = where.get(joint);
1745
+ const length2 = target === void 0 ? 0 : Math.hypot(target.x - inlet.node.at[0], target.z - inlet.node.at[2]);
1746
+ const end = (inlet.node.invert ?? 0) - (rules.minSlope.storm_lateral + slopeMargin) * length2;
1747
+ top.set(joint, Math.min(top.get(joint) ?? Number.POSITIVE_INFINITY, end));
1748
+ return { inlet, joint, end };
1749
+ });
1750
+ const pipes = pipesOf({ chains, diameter: storm.galleryDiameter, slope: rules.minSlope.storm_gallery + slopeMargin });
1751
+ const { inverts, lifts } = solveDrainInverts({ pipes, top, floor });
1752
+ for (const node of nodes) {
1753
+ const ground = context.groundAt(node.x, node.z);
1754
+ const kind = roots.has(node.id) ? { kind: "outfall", spec: "headwall" } : lifts.has(node.id) ? { kind: "pumping_station", spec: "storm_lift" } : { kind: "manhole", spec: "gallery_box" };
1755
+ sink.nodes.push({ id: node.id, ...kind, at: [node.x, ground, node.z], invert: inverts.get(node.id) ?? ground, carries: ["storm"] });
1756
+ }
1757
+ const edges = pipes.map((pipe) => {
1758
+ const lift = lifts.get(pipe.from);
1759
+ return { id: `${pipe.from}>${pipe.to}`, kind: "storm_gallery", from: pipe.from, to: pipe.to, diameter: storm.galleryDiameter, ...lift === void 0 ? {} : { inverts: [lift, inverts.get(pipe.to) ?? 0] } };
1760
+ });
1761
+ for (const { inlet, joint, end } of laterals) {
1762
+ sink.nodes.push(inlet.node);
1763
+ edges.push({ id: `storm:lateral:${inlet.key}`, kind: "storm_lateral", from: inlet.id, to: joint, diameter: storm.lateralDiameter, inverts: [inlet.node.invert ?? 0, end] });
1764
+ }
1765
+ edges.push(...gutters({ context, connections, inlets }));
1766
+ sink.edges.push(...edges);
1767
+ return edges;
1768
+ }
1769
+ function gutters({ context, connections, inlets }) {
1770
+ const slope = context.rules.minSlope.storm_gutter + context.rules.layout.slopeMargin;
1771
+ return connections.flatMap((connection) => {
1772
+ const served = context.served.get(connection.lot);
1773
+ if (served === void 0) return [];
1774
+ const [u] = frameOf({ frame: served.run, x: connection.at[0], z: connection.at[2] });
1775
+ const own = inlets.filter((inlet2) => inlet2.run.id === served.run.id && inlet2.curb === served.side);
1776
+ const inlet = [...own].sort((a, b) => Math.abs(a.u - u) - Math.abs(b.u - u))[0];
1777
+ if (inlet === void 0) return [];
1778
+ const node = `lot:${connection.lot}:storm`;
1779
+ context.sink.nodes.push({ id: node, kind: "connection", at: connection.at, carries: ["storm"], lot: connection.lot });
1780
+ const length2 = Math.hypot(inlet.node.at[0] - connection.at[0], inlet.node.at[2] - connection.at[2]);
1781
+ return [{ id: `storm:gutter:${connection.lot}`, kind: "storm_gutter", from: node, to: inlet.id, diameter: 0, inverts: [connection.at[1], inlet.node.at[1] - slope * length2] }];
1782
+ });
1783
+ }
1784
+
1785
+ // src/networks/telecom.ts
1786
+ function cablesAt({ pole, rules, seed, isPeriphery }) {
1787
+ const { cables } = rules.layout.telecom;
1788
+ return countOf({ seed, id: `telecom:${pole.station.run.id}`, range: isPeriphery(pole.station.x, pole.station.z) ? cables.periphery : cables.clean });
1789
+ }
1790
+ function layTelecom(params) {
1791
+ const { tree, heights, rules, sink } = params;
1792
+ const { sag, telecom } = rules.layout;
1793
+ for (const system of tree.systems) {
1794
+ const feed = `feed:telecom:${system.root}`;
1795
+ sink.nodes.push({ id: feed, kind: "feed", at: [system.feed[0], heights.telecom, system.feed[1]], carries: ["telecom"] });
1796
+ for (const id of system.poles) {
1797
+ const pole = tree.poles.get(id);
1798
+ const up = system.parent.get(id);
1799
+ const conductors = cablesAt({ pole, rules, seed: params.seed, isPeriphery: params.isPeriphery });
1800
+ const depth = system.depth.get(id) ?? 0;
1801
+ if (up === void 0 || depth % telecom.spliceEvery !== 0) {
1802
+ sink.edges.push({ id: `telecom:${id}`, kind: "telecom_span", from: up ?? feed, to: id, sag: sag.telecom, heights: [heights.telecom, heights.telecom], conductors });
1803
+ continue;
1804
+ }
1805
+ const parent = tree.poles.get(up);
1806
+ const length2 = Math.hypot(parent.station.x - pole.station.x, parent.station.z - pole.station.z);
1807
+ const share = Math.min(0.5, 0.6 / Math.max(length2, 1e-9));
1808
+ const splice = `splice:${id}`;
1809
+ const at = [pole.station.x + (parent.station.x - pole.station.x) * share, heights.telecom, pole.station.z + (parent.station.z - pole.station.z) * share];
1810
+ sink.nodes.push({ id: splice, kind: "splice", at, carries: ["telecom"], spec: "splice_reserve" });
1811
+ sink.edges.push({ id: `telecom:${splice}`, kind: "telecom_span", from: up, to: splice, sag: sag.telecom, heights: [heights.telecom, heights.telecom], conductors });
1812
+ sink.edges.push({ id: `telecom:${id}`, kind: "telecom_span", from: splice, to: id, sag: 0, heights: [heights.telecom, heights.telecom], conductors });
1813
+ }
1814
+ }
1815
+ const find = poleFinder(tree);
1816
+ for (const connection of params.connections) {
1817
+ const pole = poleAt(tree, params.feeds.get(`${connection.lot}:telecom`)) ?? find({ x: connection.at[0], z: connection.at[2], radius: rules.telecom.dropMaxLength })[0];
1818
+ if (pole === void 0) continue;
1819
+ const node = `lot:${connection.lot}:telecom`;
1820
+ sink.nodes.push({ id: node, kind: "connection", at: connection.at, carries: ["telecom"], lot: connection.lot });
1821
+ sink.edges.push({ id: `telecom_drop:${connection.lot}`, kind: "telecom_drop", from: pole.id, to: node, sag: sag.telecomDrop, heights: [heights.telecom, connection.at[1]], conductors: 1 });
1822
+ }
1823
+ }
1824
+
1825
+ // src/networks/water.ts
1826
+ function kindOf2({ node, vertex, roots }) {
1827
+ if (roots.has(node.id)) return { kind: "reservoir", spec: "reservoir" };
1828
+ if (node.role === "stop") return { kind: "splice", spec: "tee" };
1829
+ return { kind: "valve", spec: vertex?.role === "crossing" ? "gate_valve" : "end_valve" };
1830
+ }
1831
+ function layWater({ context, connections }) {
1832
+ const { rules, sink } = context;
1833
+ const { water } = rules.layout;
1834
+ const offset = (run) => waterOffset({ context, run });
1835
+ const line = lineNetworkOf({ prefix: "water", runs: context.runs, offset, riverInset: 0, reach: reachOf(context), flow: "supply" });
1836
+ const stops = connections.flatMap((connection) => {
1837
+ const served = context.served.get(connection.lot);
1838
+ if (served === void 0) return [];
1839
+ return [{ key: `tee:${connection.lot}`, run: served.run, u: frameOf({ frame: served.run, x: connection.at[0], z: connection.at[2] })[0] }];
1840
+ });
1841
+ const { chains, joints } = chainsOf({ line, prefix: "water", offset, stops });
1842
+ const roots = new Set(line.roots);
1843
+ for (const node of chainNodes(chains)) {
1844
+ const ground = context.groundAt(node.x, node.z);
1845
+ sink.nodes.push({ id: node.id, ...kindOf2({ node, vertex: line.vertices.get(node.id), roots }), at: [node.x, ground, node.z], invert: topOf({ context, x: node.x, z: node.z, cover: rules.cover.water_main.min, diameter: water.mainDiameter }), carries: ["water"] });
1846
+ }
1847
+ for (const pipe of pipesOf({ chains, diameter: water.mainDiameter, slope: 0 })) sink.edges.push({ id: `${pipe.from}>${pipe.to}`, kind: "water_main", from: pipe.from, to: pipe.to, diameter: water.mainDiameter });
1848
+ for (const vertex of line.vertices.values()) if (vertex.role === "crossing") layHydrant({ context, vertex });
1849
+ for (const connection of connections) {
1850
+ const tee = joints.get(`tee:${connection.lot}`);
1851
+ if (tee === void 0) continue;
1852
+ const node = `lot:${connection.lot}:water`;
1853
+ const invert = topOf({ context, x: connection.at[0], z: connection.at[2], cover: rules.cover.water_service.min, diameter: water.serviceDiameter });
1854
+ sink.nodes.push({ id: node, kind: "connection", at: connection.at, invert, carries: ["water"], lot: connection.lot });
1855
+ sink.edges.push({ id: `water:service:${connection.lot}`, kind: "water_service", from: tee, to: node, diameter: water.serviceDiameter });
1856
+ }
1857
+ }
1858
+ function layHydrant({ context, vertex }) {
1859
+ const { water } = context.rules.layout;
1860
+ const run = context.runs.find((candidate) => {
1861
+ const [, v] = frameOf({ frame: candidate, x: vertex.x, z: vertex.z });
1862
+ return Math.abs(v - waterOffset({ context, run: candidate })) < 1e-6;
1863
+ });
1864
+ if (run === void 0) return;
1865
+ const cross = context.runs.find((candidate) => candidate.along !== run.along && Math.abs((run.along === "x" ? vertex.x : vertex.z) - candidate.axis - waterOffset({ context, run: candidate })) < 1e-6);
1866
+ const away = cross === void 0 ? 1 : Math.sign(waterOffset({ context, run: cross })) || 1;
1867
+ const [x, z] = run.along === "x" ? [vertex.x + away * water.hydrantOffset, vertex.z] : [vertex.x, vertex.z + away * water.hydrantOffset];
1868
+ const id = `water:hydrant:${vertex.id.slice("water:".length)}`;
1869
+ const ground = context.groundAt(x, z);
1870
+ context.sink.nodes.push({ id, kind: "hydrant", at: [x, ground, z], invert: topOf({ context, x, z, cover: context.rules.cover.water_main.min, diameter: water.mainDiameter }), carries: ["water"], spec: "pillar_hydrant" });
1871
+ context.sink.edges.push({ id: `${vertex.id}>${id}`, kind: "water_main", from: vertex.id, to: id, diameter: water.mainDiameter });
1872
+ }
1873
+
1874
+ // src/networks/generate.ts
1875
+ function surfaceOf({ runs, sidewalk }) {
1876
+ return (x, z) => {
1877
+ let surface = "lot";
1878
+ for (const run of runs) {
1879
+ const [u, v] = frameOf({ frame: run, x, z });
1880
+ if (u < run.from || u > run.to) continue;
1881
+ if (Math.abs(v) < run.width / 2) return "road";
1882
+ if (Math.abs(v) < run.width / 2 + sidewalk) surface = "sidewalk";
1883
+ }
1884
+ return surface;
1885
+ };
1886
+ }
1887
+ function peripheryOf({ plan, kinds }) {
1888
+ const districts = [...plan.districts ?? []].reverse();
1889
+ return (x, z) => {
1890
+ const holder = districts.find((district) => x >= district.rect[0] && x <= district.rect[2] && z >= district.rect[1] && z <= district.rect[3]);
1891
+ return holder !== void 0 && kinds.includes(holder.kind);
1892
+ };
1893
+ }
1894
+ function polesOf({ params, layout, sink }) {
1895
+ const { rules, runs, served, sides } = layout;
1896
+ const avoid = params.avoid ?? [];
1897
+ const warn = (warning) => void sink.warnings.push(warning);
1898
+ const stations = runs.map((run) => poleStationsOf({ run, side: sides.get(run.id) ?? -1, served, avoid, rules: rules.layout, warn }));
1899
+ const anchors = layout.connections.filter((connection) => connection.network === "power" || connection.network === "telecom");
1900
+ const isFree = (x, z) => !avoid.some((rect) => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]);
1901
+ const surface = surfaceOf({ runs, sidewalk: rules.layout.sidewalk });
1902
+ const inside3 = (x, z, rect) => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3];
1903
+ const canServe = ({ x, z, lot }) => surface(x, z) !== "road" && !params.lots.some((other) => other.id !== lot && inside3(x, z, other.rect));
1904
+ const reach = Math.min(rules.power.dropMaxLength, rules.telecom.dropMaxLength);
1905
+ const frontages = new Map(frontagesOf({ served, sidewalk: rules.layout.sidewalk }).map((frontage) => [frontage.lot, frontage]));
1906
+ const reached = reachLots({ runs: stations, anchors, served: new Map(served.map((entry) => [entry.lot.id, entry])), reach, rules: rules.layout, isFree, canServe, warn, frontages, power: rules.power });
1907
+ return { tree: poleTreeOf({ chains: [...reached.runs, ...reached.chains], sides, setback: rules.layout.poles.curbSetback }), feeds: reached.feeds };
1908
+ }
1909
+ function frontagesOf({ served, sidewalk }) {
1910
+ return served.map((entry) => ({ lot: entry.lot.id, rect: entry.lot.rect, frame: { along: entry.run.along, axis: entry.run.axis }, reach: entry.run.width / 2 + sidewalk, side: entry.side, span: entry.span }));
1911
+ }
1912
+ function generateNetworks(params) {
1913
+ const rules = resolveNetworkRules(params.rules);
1914
+ const groundAt2 = params.groundAt ?? (() => 0);
1915
+ const runs = streetRunsOf({ plan: params.plan, edgeReach: rules.layout.edgeReach });
1916
+ const served = servedLotsOf({ lots: params.lots, runs });
1917
+ const sides = poleSidesOf({ runs, served });
1918
+ const connections = lotConnectionsOf({ served, declared: params.connections ?? [], rules, groundAt: groundAt2 });
1919
+ const sink = { nodes: [], edges: [], warnings: [] };
1920
+ const { tree, feeds } = polesOf({ params, layout: { rules, runs, served, sides, connections }, sink });
1921
+ const pole = params.pole ?? { id: "concrete_distribution", spec: DISTRIBUTION };
1922
+ const heights = poleHeightsOf(pole.spec.slots);
1923
+ const isPeriphery = peripheryOf({ plan: params.plan, kinds: rules.layout.periphery.kinds });
1924
+ const unmetered = new Set(
1925
+ served.filter(({ lot }) => isPeriphery((lot.rect[0] + lot.rect[2]) / 2, (lot.rect[1] + lot.rect[3]) / 2) && hashOf({ seed: params.seed, id: `hookup:${lot.id}` }) < rules.layout.periphery.hookupShare).map((entry) => entry.lot.id)
1926
+ );
1927
+ layPower({ tree, connections: ofNetwork2({ connections, network: "power" }), rules, heights, pole: { id: pole.id, lampReach: pole.spec.lamp.reach }, unmetered, feeds, sink });
1928
+ layTelecom({ tree, connections: ofNetwork2({ connections, network: "telecom" }), rules, heights, seed: params.seed, isPeriphery, feeds, sink });
1929
+ const [width, depth] = params.plan.size ?? [0, 0];
1930
+ const rivers = (params.plan.lines ?? []).filter((line) => line.kind === "river");
1931
+ const context = { runs, sides, served: new Map(served.map((entry) => [entry.lot.id, entry])), rules, groundAt: groundAt2, rivers, border: [width / 2, depth / 2], sink };
1932
+ const storm = layStorm({ context, connections: ofNetwork2({ connections, network: "storm" }) });
1933
+ layWater({ context, connections: ofNetwork2({ connections, network: "water" }) });
1934
+ laySewer({ context, connections: ofNetwork2({ connections, network: "sewer" }), above: storm });
1935
+ const networks = { nodes: sink.nodes, edges: sink.edges, seed: params.seed, rules };
1936
+ return { networks, connections, surfaceAt: surfaceOf({ runs, sidewalk: rules.layout.sidewalk }), frontages: frontagesOf({ served, sidewalk: rules.layout.sidewalk }), warnings: sink.warnings };
1937
+ }
1938
+
1939
+ // src/lamps.ts
1940
+ var UINT322 = 2 ** 32;
1941
+ var PHASE_SALT = 1597463007;
1942
+ var SEED_BITS = new DataView(new ArrayBuffer(8));
1943
+ var hashLamp = (seed, x, z) => {
1944
+ SEED_BITS.setFloat64(0, seed);
1945
+ let h = 2166136261;
1946
+ for (const value of [SEED_BITS.getUint32(0), SEED_BITS.getUint32(4), Math.round(x * 100), Math.round(z * 100)]) {
1947
+ h ^= value & 65535;
1948
+ h = Math.imul(h, 16777619);
1949
+ h ^= value >>> 16 & 65535;
1950
+ h = Math.imul(h, 16777619);
1951
+ }
1952
+ return (h >>> 0) / UINT322;
1953
+ };
1954
+ var flickerPhaseOf = (x, z) => hashLamp(PHASE_SALT, x, z) * 2 * Math.PI;
1955
+ function assertLampShares(shares) {
1956
+ const { lit, flicker } = shares;
1957
+ if (!(lit >= 0 && lit <= 1)) throw new RangeError(`lamp shares: lit must be in [0, 1], got ${lit}`);
1958
+ if (!(flicker >= 0 && flicker <= lit)) throw new RangeError(`lamp shares: flicker must be in [0, lit], got ${flicker}`);
1959
+ }
1960
+ function lampStateOf({ seed, x, z, shares }) {
1961
+ assertLampShares(shares);
1962
+ const roll = hashLamp(seed, x, z);
1963
+ if (roll >= shares.lit) return { on: false, flicker: false };
1964
+ return { on: true, flicker: roll >= shares.lit - shares.flicker };
1965
+ }
1966
+
1967
+ // src/networks/lamps.ts
1968
+ function networkLampsOf({ networks, shares, isNight }) {
1969
+ const feeds = new Map(networks.edges.filter((edge) => edge.kind === "light_feed").map((edge) => [edge.to, edge.from]));
1970
+ return networks.nodes.filter((node) => node.kind === "light").map((node) => {
1971
+ const [x, , z] = node.at;
1972
+ const state = isNight ? lampStateOf({ seed: networks.seed, x, z, shares }) : { on: false, flicker: false };
1973
+ return { id: node.id, pole: feeds.get(node.id) ?? "", at: node.at, ...state, ...state.flicker ? { flickerPhase: flickerPhaseOf(x, z) } : {} };
1974
+ });
1975
+ }
1976
+
1977
+ // src/pole-hardware.ts
1978
+ var GAP = 2e-3;
1979
+ function mediumVoltage(spec) {
1980
+ const { crossarm, insulators, slots } = spec;
1981
+ const [bottom, top] = slots.bands.mv;
1982
+ const pin = top - bottom - crossarm.height - GAP;
1983
+ const boxes = [{ role: "crossarm", x: crossarm.reach, y: bottom, z: 0, width: crossarm.width, height: crossarm.height, depth: crossarm.depth, color: crossarm.color }];
1984
+ for (const x of insulators.at) boxes.push({ role: "insulator", x, y: bottom + crossarm.height + GAP, z: 0, width: insulators.radius * 2, height: pin, depth: insulators.radius * 2, color: insulators.color });
1985
+ return { boxes, mv: insulators.at.map((x) => [x, top, 0]) };
1986
+ }
1987
+ function transformerOf(spec) {
1988
+ const t = spec.transformer;
1989
+ const x = -t.offset;
1990
+ const tank = { role: "tank", x, y: t.y, z: 0, radius: t.radius, height: t.height, color: t.color, segments: t.segments };
1991
+ const { bushings } = spec;
1992
+ const lid = t.y + t.height + GAP;
1993
+ const zs = [-bushings.spread, 0, bushings.spread];
1994
+ const boxes = [
1995
+ { role: "bracket", x: x / 2, y: t.y + t.height * 0.6, z: 0, width: t.offset, height: 0.08, depth: 0.1, color: spec.lowVoltage.color },
1996
+ ...zs.map((z) => ({ role: "bushing", x, y: lid, z, width: bushings.radius * 2, height: bushings.height, depth: bushings.radius * 2, color: bushings.color }))
1997
+ ];
1998
+ return { boxes, tank, points: { mv: zs.map((z) => [x, lid + bushings.height, z]), lv: [x + t.radius, t.y + t.height * 0.3, 0] } };
1999
+ }
2000
+ function lampOf2(spec) {
2001
+ const { arm, lamp } = spec;
2002
+ const lensHeight = 0.03;
2003
+ return {
2004
+ boxes: [
2005
+ { role: "arm", x: arm.reach, y: arm.y, z: 0, width: arm.width, height: arm.height, depth: arm.depth, color: arm.color },
2006
+ { role: "lamp", x: lamp.reach, y: lamp.y, z: 0, width: lamp.width, height: lamp.height, depth: lamp.depth, color: arm.color }
2007
+ ],
2008
+ lens: { role: "lamp", x: lamp.reach, y: lamp.y - lensHeight - GAP, z: 0, width: lamp.width * 0.8, height: lensHeight, depth: lamp.depth * 0.8, color: spec.lens.unlit }
2009
+ };
2010
+ }
2011
+ function distributionHardwareOf(spec, o) {
2012
+ const heights = poleHeightsOf(spec.slots);
2013
+ const boxes = [];
2014
+ const cylinders = [];
2015
+ const mv = mediumVoltage(spec);
2016
+ if (o.mv || o.transformer) boxes.push(...mv.boxes);
2017
+ const lvAt = [-spec.lowVoltage.out, heights.lv, 0];
2018
+ boxes.push({ role: "lv_clamp", x: -spec.lowVoltage.out / 2 - spec.mast.radiusTop / 2, y: heights.lv - 0.06, z: 0, width: spec.lowVoltage.out - spec.mast.radiusTop + 0.06, height: 0.12, depth: 0.08, color: spec.lowVoltage.color });
2019
+ const { telecom } = spec;
2020
+ const cables = Math.max(o.cables, 0);
2021
+ const telecomAt = Array.from({ length: cables }, (_, index) => [-telecom.out, heights.telecom - index * o.cableGap, 0]);
2022
+ if (cables > 0) {
2023
+ const bottom = heights.telecom - (cables - 1) * o.cableGap - 0.05;
2024
+ boxes.push({ role: "telecom_clamp", x: -telecom.out / 2 - spec.mast.radiusTop / 2, y: bottom, z: 0, width: telecom.out - spec.mast.radiusTop + 0.04, height: heights.telecom + 0.05 - bottom, depth: 0.06, color: telecom.color });
2025
+ }
2026
+ const transformer = o.transformer ? transformerOf(spec) : void 0;
2027
+ if (transformer) {
2028
+ boxes.push(...transformer.boxes);
2029
+ cylinders.push(transformer.tank);
2030
+ }
2031
+ const lamp = o.lamp ? lampOf2(spec) : void 0;
2032
+ if (lamp) boxes.push(...lamp.boxes);
2033
+ const attachments = { mv: mv.mv, lv: lvAt, telecom: telecomAt, guy: [0, spec.slots.bands.mv[0] - 0.15, 0], ...transformer ? { transformer: transformer.points } : {} };
2034
+ return { boxes, cylinders, ...lamp ? { lens: lamp.lens } : {}, attachments };
2035
+ }
2036
+ export {
2037
+ CONNECTION_NETWORK,
2038
+ DEFAULT_NETWORK_LAYOUT,
2039
+ DEFAULT_NETWORK_RULES,
2040
+ DEFAULT_POLE_SLOTS,
2041
+ DISTRIBUTION,
2042
+ EDGE_CLASS,
2043
+ EDGE_NETWORK,
2044
+ NETWORK_ENDS,
2045
+ NETWORK_FLOW,
2046
+ NETWORK_VIOLATION,
2047
+ POLE_SLOT_GAPS,
2048
+ POLE_SLOT_ORDER,
2049
+ buildNetworkGraph,
2050
+ checkPoleSlots,
2051
+ circuitOf,
2052
+ connectedNodes,
2053
+ defaultConnectionsOf,
2054
+ distributionHardwareOf,
2055
+ diversifiedDemand,
2056
+ dropMisfitOf,
2057
+ edgeLength,
2058
+ frontagesOf,
2059
+ generateNetworks,
2060
+ isAerialEdgeKind,
2061
+ lotUnderDrop,
2062
+ networkLampsOf,
2063
+ pickTransformer,
2064
+ poleHeightsOf,
2065
+ resolveNetworkRules,
2066
+ slotsOfPole,
2067
+ surfaceOf,
2068
+ validateNetworks
2069
+ };
2070
+ //# sourceMappingURL=index.js.map