Files
maptool/public/vendor/maplibre-gl-lanes/maplibre-gl-lanes.mjs
T
randy 0a1fc266b7
CI / check (pull_request) Successful in 18s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
Update dependency maplibre-gl-lanes to v1.6.0
2026-11-15 09:08:19 +00:00

3687 lines
260 KiB
JavaScript

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
// src/core/graph.ts
var ONEWAY_VALUES = /* @__PURE__ */ new Set(["yes", "true", "1", "-1", !0, 1, -1]);
function lngLatToMercator(lng, lat) {
let x = (lng + 180) / 360, s = Math.sin(lat * Math.PI / 180), y = 0.5 - 0.25 * Math.log((1 + s) / (1 - s)) / Math.PI;
return [x, y];
}
function mercatorToLngLat(x, y) {
let lng = x * 360 - 180, lat = Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI;
return [lng, lat];
}
function buildLineGraph(features, opts = {}) {
let routeProp = opts.routeProperty ?? "route", colorProp = opts.colorProperty ?? "color", nameProp = opts.nameProperty ?? "name", snap = opts.snapDegrees ?? 1e-7, onewayProp = opts.onewayProperty, uniform = onewayProp && !(opts.uniformProperties ?? []).includes(onewayProp) ? [...opts.uniformProperties ?? [], onewayProp] : opts.uniformProperties ?? [], routes = /* @__PURE__ */ new Map(), vertexPos = /* @__PURE__ */ new Map(), elem = /* @__PURE__ */ new Map(), adjacency = /* @__PURE__ */ new Map(), keyOf = (lng, lat) => {
let kx = Math.round(lng / snap), ky = Math.round(lat / snap);
return `${kx},${ky}`;
};
for (let f of features) {
if (!f.geometry) continue;
let props = f.properties ?? {}, rid = props[routeProp];
if (rid == null) continue;
let routeId = String(rid);
if (!routes.has(routeId)) {
let override = opts.routes?.[routeId] ?? {};
routes.set(routeId, {
id: routeId,
color: override.color ?? props[colorProp] ?? "#888888",
name: override.name ?? props[nameProp] ?? void 0,
dash: override.dash,
dashColor: override.dashColor,
dashCap: override.dashCap,
casing: override.casing
});
}
let lines = f.geometry.type === "LineString" ? [f.geometry.coordinates] : f.geometry.type === "MultiLineString" ? f.geometry.coordinates : [], uniformProps = uniform.length ? Object.fromEntries(uniform.map((k) => [k, props[k]])) : null;
for (let line of lines) {
let prevKey = null;
for (let c of line) {
let k = keyOf(c[0], c[1]);
if (vertexPos.has(k) || vertexPos.set(k, lngLatToMercator(c[0], c[1])), prevKey !== null && prevKey !== k) {
let forward = prevKey < k, ek = forward ? `${prevKey}|${k}` : `${k}|${prevKey}`, e = elem.get(ek);
if (!e) {
e = { u: forward ? prevKey : k, v: forward ? k : prevKey, routes: /* @__PURE__ */ new Map(), props: uniformProps, sig: null }, elem.set(ek, e);
for (let vk of [prevKey, k]) {
let s = adjacency.get(vk);
s || adjacency.set(vk, s = /* @__PURE__ */ new Set()), s.add(ek);
}
}
let dir = forward ? 1 : -1, prev = e.routes.get(routeId);
e.routes.set(routeId, prev === void 0 || prev === dir ? dir : 0);
}
prevKey = k;
}
}
}
let sigOf = (e) => {
if (e.sig === null) {
let routeSig = [...e.routes.keys()].sort().join("\0");
e.sig = routeSig + "" + (e.props ? JSON.stringify(uniform.map((k) => e.props[k] ?? null)) : "");
}
return e.sig;
}, junction = /* @__PURE__ */ new Map(), isJunction = (vk) => {
let is = junction.get(vk);
if (is === void 0) {
let inc = adjacency.get(vk);
if (inc.size !== 2)
is = !0;
else {
let [k1, k2] = inc;
is = sigOf(elem.get(k1)) !== sigOf(elem.get(k2));
}
junction.set(vk, is);
}
return is;
}, nodeIndex = /* @__PURE__ */ new Map(), nodes = [], nodeFor = (vk) => {
let id = nodeIndex.get(vk);
if (id === void 0) {
let [x, y] = vertexPos.get(vk);
id = nodes.length, nodeIndex.set(vk, id), nodes.push({ id, x, y, ports: [], transitions: [] });
}
return id;
}, edges = [], visited = /* @__PURE__ */ new Set(), walk = (startVk, firstEk) => {
let coordsKeys = [startVk], elemKeys = [], vk = startVk, ek = firstEk;
for (; ; ) {
visited.add(ek), elemKeys.push(ek);
let e = elem.get(ek), next = e.u === vk ? e.v : e.u;
if (coordsKeys.push(next), vk = next, isJunction(vk) || vk === startVk) break;
let inc = [...adjacency.get(vk)], nk = inc[0] === ek ? inc[1] : inc[0];
if (visited.has(nk)) break;
ek = nk;
}
let first = elem.get(elemKeys[0]), a = nodeFor(coordsKeys[0]), b = nodeFor(coordsKeys[coordsKeys.length - 1]), coords = [];
for (let k of coordsKeys) {
let p = vertexPos.get(k);
coords.push(p[0], p[1]);
}
let id = edges.length, direction = /* @__PURE__ */ new Map();
for (let [r, d] of first.routes) {
let walkForward = first.u === coordsKeys[0];
direction.set(r, d === 0 ? 0 : walkForward ? d : -d);
}
let edge = { id, a, b, coords, routes: [...first.routes.keys()].sort(), direction, order: [] };
if (first.props)
if (onewayProp && ONEWAY_VALUES.has(first.props[onewayProp]) && (edge.oneway = !0), onewayProp && !opts.uniformProperties?.includes(onewayProp)) {
let { [onewayProp]: _, ...rest } = first.props;
Object.keys(rest).length && (edge.properties = rest);
} else
edge.properties = first.props;
edges.push(edge), nodes[a].ports.push({ edge: id, end: "a" }), nodes[b].ports.push({ edge: id, end: "b" });
};
for (let vk of adjacency.keys())
if (isJunction(vk))
for (let ek of adjacency.get(vk))
visited.has(ek) || walk(vk, ek);
for (let ek of elem.keys())
visited.has(ek) || walk(elem.get(ek).u, ek);
let chains = deriveChains(nodes, edges, routes);
return { nodes, edges, routes, chains };
}
function deriveChains(nodes, edges, routes) {
for (let n of nodes) n.transitions = [];
let chains = /* @__PURE__ */ new Map(), portIndex = (node, edge, end) => node.ports.findIndex((p) => p.edge === edge && p.end === end), outDir = (edge, end) => {
let c = edges[edge].coords, dx, dy;
if (end === "a")
dx = c[2] - c[0], dy = c[3] - c[1];
else {
let n = c.length;
dx = c[n - 4] - c[n - 2], dy = c[n - 3] - c[n - 1];
}
let l = Math.hypot(dx, dy) || 1;
return [dx / l, dy / l];
}, flowAt = (rid, edge, end) => {
let e = edges[edge];
if (!e.oneway) return 0;
let d = e.direction.get(rid) ?? 0;
return d ? end === "b" == d > 0 ? 1 : -1 : 0;
}, clash = (a, b) => a !== 0 && a === b;
for (let rid of routes.keys()) {
let routeEdges = edges.filter((e) => e.routes.includes(rid));
if (!routeEdges.length) {
chains.set(rid, []);
continue;
}
let unused = new Set(routeEdges.map((e) => e.id)), degree = /* @__PURE__ */ new Map();
for (let e of routeEdges)
degree.set(e.a, (degree.get(e.a) ?? 0) + 1), degree.set(e.b, (degree.get(e.b) ?? 0) + 1);
let out = [], chainEndPorts = [];
for (; unused.size; ) {
let startEdge = null, startNode = -1;
for (let id of unused) {
let e = edges[id];
if (degree.get(e.a) % 2 === 1 && (startEdge === null || startNode !== e.a && startNode !== e.b)) {
startEdge = e, startNode = e.a;
break;
}
if (degree.get(e.b) % 2 === 1) {
startEdge = e, startNode = e.b;
break;
}
}
if (!startEdge) {
let id = Math.min(...unused);
startEdge = edges[id], startNode = startEdge.a;
}
let steps = [], node = startNode, arriving = null, nextEdge = startEdge;
for (; nextEdge; ) {
let forward = nextEdge.a === node;
steps.push({ edge: nextEdge.id, forward }), unused.delete(nextEdge.id);
let far = forward ? nextEdge.b : nextEdge.a, farEnd = forward ? "b" : "a", d = outDir(nextEdge.id, farEnd);
arriving = [-d[0], -d[1]], node = far;
let best = null, bestDot = -1 / 0, arrFlow = flowAt(rid, nextEdge.id, farEnd), arrEdge = nextEdge.id, hasAgreeing = arrFlow !== 0 && nodes[node].ports.some((p) => p.edge !== arrEdge && edges[p.edge].routes.includes(rid) && flowAt(rid, p.edge, p.end) === -arrFlow);
for (let p of nodes[node].ports) {
if (!unused.has(p.edge) || hasAgreeing && clash(arrFlow, flowAt(rid, p.edge, p.end))) continue;
let o = outDir(p.edge, p.end), dot = o[0] * arriving[0] + o[1] * arriving[1];
(dot > bestDot + 1e-9 || Math.abs(dot - bestDot) <= 1e-9 && best && p.edge < best.id) && (bestDot = dot, best = edges[p.edge]);
}
nextEdge = best;
}
let first = steps[0], last = steps[steps.length - 1], firstNode = first.forward ? edges[first.edge].a : edges[first.edge].b, lastNode = last.forward ? edges[last.edge].b : edges[last.edge].a, closed = steps.length > 1 && firstNode === lastNode, chain = { steps, closed };
out.push(chain);
let stepEnd = (s) => ({ node: s.forward ? edges[s.edge].b : edges[s.edge].a, end: s.forward ? "b" : "a" }), stepStart = (s) => ({ node: s.forward ? edges[s.edge].a : edges[s.edge].b, end: s.forward ? "a" : "b" }), pairs = steps.length - (closed ? 0 : 1);
for (let i = 0; i < pairs; i++) {
let s = steps[i], t = steps[(i + 1) % steps.length], n = nodes[stepEnd(s).node];
n.transitions.push({ route: rid, from: portIndex(n, s.edge, stepEnd(s).end), to: portIndex(n, t.edge, stepStart(t).end) });
}
closed || (chainEndPorts.push({ node: firstNode, port: portIndex(nodes[firstNode], first.edge, stepStart(first).end), chain, end: "start" }), chainEndPorts.push({ node: lastNode, port: portIndex(nodes[lastNode], last.edge, stepEnd(last).end), chain, end: "end" }));
}
let seen = /* @__PURE__ */ new Set();
for (let ce of chainEndPorts) {
let n = nodes[ce.node], own = n.ports[ce.port], arriveDir = outDir(own.edge, own.end).map((v) => -v), best = -1, bestDot = -1 / 0;
if (n.ports.forEach((p, i) => {
if (i === ce.port || !edges[p.edge].routes.includes(rid)) return;
let o = outDir(p.edge, p.end), dot = o[0] * arriveDir[0] + o[1] * arriveDir[1];
clash(flowAt(rid, own.edge, own.end), flowAt(rid, p.edge, p.end)) && (dot -= 4), dot > bestDot && (bestDot = dot, best = i);
}), best < 0) continue;
let key = `${ce.node}:${Math.min(ce.port, best)}:${Math.max(ce.port, best)}`;
seen.has(key) || (seen.add(key), n.transitions.push({ route: rid, from: ce.port, to: best }), ce.end === "start" ? ce.chain.mergeStart = n.ports[best].edge : ce.chain.mergeEnd = n.ports[best].edge);
}
chains.set(rid, out);
}
return chains;
}
function filterGraph(g, visible) {
let keepEdge = /* @__PURE__ */ new Map(), edges = [];
for (let e of g.edges) {
let routes2 = e.routes.filter(visible);
routes2.length && (keepEdge.set(e.id, edges.length), edges.push({ ...e, id: edges.length, routes: routes2, order: [], baseline: void 0, direction: new Map([...e.direction].filter(([r]) => visible(r))) }));
}
let nodes = g.nodes.map((n) => ({
...n,
transitions: [],
ports: n.ports.filter((p) => keepEdge.has(p.edge)).map((p) => ({ edge: keepEdge.get(p.edge), end: p.end }))
})), routes = new Map([...g.routes].filter(([r]) => visible(r))), chains = deriveChains(nodes, edges, routes);
return { nodes, edges, routes, chains };
}
// src/core/geometry.ts
function polylineLength(p) {
let len = 0;
for (let i = 2; i < p.length; i += 2)
len += Math.hypot(p[i] - p[i - 2], p[i + 1] - p[i - 1]);
return len;
}
function reversed(p) {
let out = new Array(p.length);
for (let i = 0, j = p.length - 2; i < p.length; i += 2, j -= 2)
out[i] = p[j], out[i + 1] = p[j + 1];
return out;
}
function startDirection(p) {
for (let i = 2; i < p.length; i += 2) {
let dx = p[i] - p[0], dy = p[i + 1] - p[1], l = Math.hypot(dx, dy);
if (l > 0) return [dx / l, dy / l];
}
return [0, 0];
}
function endDirection(p) {
let n = p.length;
for (let i = n - 4; i >= 0; i -= 2) {
let dx = p[n - 2] - p[i], dy = p[n - 1] - p[i + 1], l = Math.hypot(dx, dy);
if (l > 0) return [dx / l, dy / l];
}
return [0, 0];
}
function startDirectionOver(p, window) {
let at = pointAlong(p, window), dx = at[0] - p[0], dy = at[1] - p[1], l = Math.hypot(dx, dy);
return l > 0 ? [dx / l, dy / l] : startDirection(p);
}
function endDirectionOver(p, window) {
let n = p.length, at = pointAlong(reversed(p), window), dx = p[n - 2] - at[0], dy = p[n - 1] - at[1], l = Math.hypot(dx, dy);
return l > 0 ? [dx / l, dy / l] : endDirection(p);
}
function pointAlong(p, dist) {
let acc = 0;
for (let i = 2; i < p.length; i += 2) {
let seg = Math.hypot(p[i] - p[i - 2], p[i + 1] - p[i - 1]);
if (acc + seg >= dist) {
let t = seg > 0 ? (dist - acc) / seg : 0;
return [p[i - 2] + (p[i] - p[i - 2]) * t, p[i - 1] + (p[i + 1] - p[i - 1]) * t];
}
acc += seg;
}
return [p[p.length - 2], p[p.length - 1]];
}
function trimPolyline(p, fromStart, fromEnd, keepFraction = 0.2) {
let n = p.length / 2, seg = new Float64Array(Math.max(0, n - 1)), total = 0;
for (let i = 0; i < n - 1; i++)
seg[i] = Math.hypot(p[i * 2 + 2] - p[i * 2], p[i * 2 + 3] - p[i * 2 + 1]), total += seg[i];
if (total <= 0) return p.slice();
let maxCut = total * (1 - keepFraction);
if (fromStart + fromEnd > maxCut) {
let s = maxCut / (fromStart + fromEnd);
fromStart *= s, fromEnd *= s;
}
let startPt = pointAlongSegments(p, seg, fromStart), endPt = pointAlongSegments(p, seg, total - fromEnd), out = [startPt.x, startPt.y], acc = 0;
for (let i = 0; i < n - 1; i++)
acc += seg[i], acc > fromStart && acc < total - fromEnd && out.push(p[i * 2 + 2], p[i * 2 + 3]);
return out.push(endPt.x, endPt.y), out;
}
function pointAlongSegments(p, seg, dist) {
if (dist <= 0) return { x: p[0], y: p[1] };
let acc = 0;
for (let i = 0; i < seg.length; i++) {
let s = seg[i];
if (acc + s >= dist) {
let t = s > 0 ? (dist - acc) / s : 0;
return { x: p[i * 2] + (p[i * 2 + 2] - p[i * 2]) * t, y: p[i * 2 + 1] + (p[i * 2 + 3] - p[i * 2 + 1]) * t };
}
acc += s;
}
return { x: p[p.length - 2], y: p[p.length - 1] };
}
function simplify(p, tolerance) {
let n = p.length / 2;
if (n <= 2 || tolerance <= 0) return p.slice();
let keep = new Uint8Array(n);
keep[0] = 1, keep[n - 1] = 1;
let tol2 = tolerance * tolerance, stack = [0, n - 1];
for (; stack.length; ) {
let last = stack.pop(), first = stack.pop(), maxD = 0, idx = -1, ax = p[first * 2], ay = p[first * 2 + 1], bx = p[last * 2], by = p[last * 2 + 1];
for (let i = first + 1; i < last; i++) {
let d = segmentDistanceSq(p[i * 2], p[i * 2 + 1], ax, ay, bx, by);
d > maxD && (maxD = d, idx = i);
}
maxD > tol2 && idx > 0 && (keep[idx] = 1, stack.push(first, idx, idx, last));
}
let out = [];
for (let i = 0; i < n; i++) keep[i] && out.push(p[i * 2], p[i * 2 + 1]);
return out;
}
function simplifyRank(p) {
let n = p.length / 2, rank = new Float64Array(n);
if (n === 0 || (rank[0] = 1 / 0, rank[n - 1] = 1 / 0, n <= 2)) return rank;
let stack = [0, n - 1], cap = [1 / 0];
for (; stack.length; ) {
let last = stack.pop(), first = stack.pop(), above = cap.pop(), maxD = 0, idx = -1, ax = p[first * 2], ay = p[first * 2 + 1], bx = p[last * 2], by = p[last * 2 + 1];
for (let i = first + 1; i < last; i++) {
let d = segmentDistanceSq(p[i * 2], p[i * 2 + 1], ax, ay, bx, by);
d > maxD && (maxD = d, idx = i);
}
if (maxD > 0 && idx > 0) {
let r = maxD < above ? maxD : above;
rank[idx] = r, stack.push(first, idx, idx, last), cap.push(r, r);
}
}
return rank;
}
function simplifyRanked(p, rank, tolerance) {
let n = p.length / 2;
if (n <= 2 || tolerance <= 0) return p.slice();
let tol2 = tolerance * tolerance, out = [];
for (let i = 0; i < n; i++) rank[i] > tol2 && out.push(p[i * 2], p[i * 2 + 1]);
return out;
}
function segmentDistanceSq(px, py, ax, ay, bx, by) {
let dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
if (l2 > 0) {
let t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / l2));
dx = ax + dx * t, dy = ay + dy * t;
} else
dx = ax, dy = ay;
return (px - dx) * (px - dx) + (py - dy) * (py - dy);
}
function dedupe(p, eps = 1e-9) {
let out = [];
for (let i = 0; i < p.length; i += 2) {
let n = out.length;
n >= 2 && Math.abs(out[n - 2] - p[i]) < eps && Math.abs(out[n - 1] - p[i + 1]) < eps || out.push(p[i], p[i + 1]);
}
return out;
}
var LOOP_WINDOW_OFFSETS = 12, INSIDE_MITER_LIMIT = 8;
function offsetPolyline(p, d, arcStepRad = Math.PI / 9) {
return offsetPolylineAnchored(p, d, arcStepRad).points;
}
function offsetPolylineAnchored(p, d, arcStepRad = Math.PI / 9) {
let src = dedupe(p), n = src.length / 2;
if (n < 2 || d === 0) return { points: src.slice(), anchors: src.slice() };
let segs = new Float64Array((n - 1) * 4);
for (let i = 0; i < n - 1; i++) {
let ax = src[i * 2], ay = src[i * 2 + 1], bx = src[i * 2 + 2], by = src[i * 2 + 3], dx = bx - ax, dy = by - ay, l = Math.hypot(dx, dy), nx = dy / l, ny = -dx / l;
segs[i * 4] = ax + nx * d, segs[i * 4 + 1] = ay + ny * d, segs[i * 4 + 2] = bx + nx * d, segs[i * 4 + 3] = by + ny * d;
}
let out = [segs[0], segs[1]], anchors = [src[0], src[1]];
for (let i = 1; i < n - 1; i++) {
let o0 = (i - 1) * 4, o1 = i * 4, s0x = segs[o0], s0y = segs[o0 + 1], s0X = segs[o0 + 2], s0Y = segs[o0 + 3], s1x = segs[o1], s1y = segs[o1 + 1], s1X = segs[o1 + 2], s1Y = segs[o1 + 3], vx = src[i * 2], vy = src[i * 2 + 1], cross = (s0X - s0x) * (s1Y - s1y) - (s0Y - s0y) * (s1X - s1x), dot = (s0X - s0x) * (s1X - s1x) + (s0Y - s0y) * (s1Y - s1y), outside = d > 0 == cross > 0;
if (Math.abs(cross) < 1e-9 * Math.max(1, Math.abs(dot))) {
out.push(s1x, s1y), anchors.push(vx, vy);
continue;
}
if (!outside) {
let ix = intersectLines(s0x, s0y, s0X, s0Y, s1x, s1y, s1X, s1Y);
ix && Math.hypot(ix[0] - vx, ix[1] - vy) <= INSIDE_MITER_LIMIT * Math.abs(d) ? (out.push(ix[0], ix[1]), anchors.push(vx, vy)) : (out.push(s0X, s0Y, s1x, s1y), anchors.push(vx, vy, vx, vy));
continue;
}
let a0 = Math.atan2(s0Y - vy, s0X - vx), da = Math.atan2(s1y - vy, s1x - vx) - a0;
for (; da > Math.PI; ) da -= 2 * Math.PI;
for (; da < -Math.PI; ) da += 2 * Math.PI;
let steps = Math.max(1, Math.ceil(Math.abs(da) / arcStepRad)), r = Math.abs(d);
out.push(s0X, s0Y), anchors.push(vx, vy);
for (let k = 1; k < steps; k++) {
let a = a0 + da * k / steps;
out.push(vx + Math.cos(a) * r, vy + Math.sin(a) * r), anchors.push(vx, vy);
}
out.push(s1x, s1y), anchors.push(vx, vy);
}
out.push(segs[segs.length - 2], segs[segs.length - 1]), anchors.push(src[src.length - 2], src[src.length - 1]);
let open = removeLoopsAnchored(out, anchors, Math.abs(d) * LOOP_WINDOW_OFFSETS);
return dropEndHook(open, src[2] - src[0], src[3] - src[1], 0, 2 * Math.abs(d)), dropEndHook(open, src[src.length - 2] - src[src.length - 4], src[src.length - 1] - src[src.length - 3], 1, 2 * Math.abs(d)), open;
}
function dropEndHook(line, dx, dy, end, reach) {
let { points, anchors } = line, e = end ? points.length - 2 : 0, step = end ? -2 : 2, hook = 0;
for (let v = e + step; v >= 0 && v < points.length; v += step) {
let ex = points[e] - points[v], ey = points[e + 1] - points[v + 1];
if (Math.hypot(ex, ey) > reach || (end ? 1 : -1) * (ex * dx + ey * dy) > 0) break;
hook++;
}
if (hook = Math.min(hook, points.length / 2 - 2), hook <= 0) return;
let from = end ? e - 2 * hook : 2;
points.splice(from, 2 * hook), anchors.splice(from, 2 * hook);
}
function offsetPolylineSlidingAnchored(p, d0, d1, stepPx = 4, via = []) {
let src = dedupe(p), n = src.length / 2;
if (n < 2) return { points: src.slice(), anchors: src.slice() };
let dense = [src[0], src[1]];
for (let i = 1; i < n; i++) {
let ax = src[i * 2 - 2], ay = src[i * 2 - 1], bx = src[i * 2], by = src[i * 2 + 1], l = Math.hypot(bx - ax, by - ay), k = Math.max(1, Math.ceil(l / stepPx));
for (let j = 1; j <= k; j++) dense.push(ax + (bx - ax) * j / k, ay + (by - ay) * j / k);
}
let m = dense.length / 2, total = polylineLength(dense), out = new Array(dense.length), s = 0;
for (let i = 0; i < m; i++) {
let x = dense[i * 2], y = dense[i * 2 + 1];
i > 0 && (s += Math.hypot(x - dense[i * 2 - 2], y - dense[i * 2 - 1]));
let d = d0;
if (total > 0) {
let s0 = 0, o0 = d0, s1 = total, o1 = d1;
for (let k = 0; k < via.length; k += 2) {
let at = via[k] * total;
if (at <= s)
s0 = at, o0 = via[k + 1];
else {
s1 = at, o1 = via[k + 1];
break;
}
}
d = s1 > s0 ? o0 + (o1 - o0) * (s - s0) / (s1 - s0) : o1;
}
let t0x = 0, t0y = 0, t1x = 0, t1y = 0;
if (i > 0) {
t0x = x - dense[i * 2 - 2], t0y = y - dense[i * 2 - 1];
let l = Math.hypot(t0x, t0y) || 1;
t0x /= l, t0y /= l;
}
if (i < m - 1) {
t1x = dense[i * 2 + 2] - x, t1y = dense[i * 2 + 3] - y;
let l = Math.hypot(t1x, t1y) || 1;
t1x /= l, t1y /= l;
}
i === 0 && ([t0x, t0y] = [t1x, t1y]), i === m - 1 && ([t1x, t1y] = [t0x, t0y]);
let n0x = t0y, n0y = -t0x, n1x = t1y, n1y = -t1x, mx = n0x + n1x, my = n0y + n1y, ml = Math.hypot(mx, my);
if (ml < 1e-9)
mx = n0x, my = n0y;
else {
let cosHalf = Math.min(1, Math.max(0.5, ml / 2));
mx = mx / ml / cosHalf, my = my / ml / cosHalf;
}
out[i * 2] = x + mx * d, out[i * 2 + 1] = y + my * d;
}
let widest = Math.max(Math.abs(d0), Math.abs(d1), 1);
for (let k = 1; k < via.length; k += 2) widest = Math.max(widest, Math.abs(via[k]));
return removeLoopsAnchored(out, dense, widest * LOOP_WINDOW_OFFSETS);
}
function selfIntersects(p) {
let n = p.length / 2;
for (let i = 0; i + 1 < n; i++)
for (let j = i + 2; j + 1 < n; j++)
if (intersectSegments(p[i * 2], p[i * 2 + 1], p[i * 2 + 2], p[i * 2 + 3], p[j * 2], p[j * 2 + 1], p[j * 2 + 2], p[j * 2 + 3])) return !0;
return !1;
}
function intersectLines(ax, ay, bx, by, cx, cy, dx, dy) {
let r = [bx - ax, by - ay], s = [dx - cx, dy - cy], denom = r[0] * s[1] - r[1] * s[0];
if (Math.abs(denom) < 1e-12) return null;
let t = ((cx - ax) * s[1] - (cy - ay) * s[0]) / denom;
return [ax + r[0] * t, ay + r[1] * t];
}
function intersectSegments(ax, ay, bx, by, cx, cy, dx, dy) {
let rX = bx - ax, rY = by - ay, sX = dx - cx, sY = dy - cy, denom = rX * sY - rY * sX;
if (Math.abs(denom) < 1e-12) return null;
let qpX = cx - ax, qpY = cy - ay, t = (qpX * sY - qpY * sX) / denom, u = (qpX * rY - qpY * rX) / denom;
return t <= 0 || t >= 1 || u <= 0 || u >= 1 ? null : { x: ax + rX * t, y: ay + rY * t, t, u };
}
var OWN_LOOP_AREA_SHARE = 0.1;
function removeLoopsAnchored(p, anchors, window) {
let pts = p, anc = anchors, along = new Array(p.length / 2);
along[0] = 0;
for (let k = 1; k < along.length; k++)
along[k] = along[k - 1] + Math.hypot(p[k * 2] - p[k * 2 - 2], p[k * 2 + 1] - p[k * 2 - 1]);
let guard = 0;
for (; !(guard++ > 1e3); ) {
let n = pts.length / 2, found = null;
outer: for (let i = 0; i < n - 1 && !found; i++) {
let ax = pts[i * 2], ay = pts[i * 2 + 1], bx = pts[i * 2 + 2], by = pts[i * 2 + 3], minX = ax < bx ? ax : bx, maxX = ax < bx ? bx : ax, minY = ay < by ? ay : by, maxY = ay < by ? by : ay;
for (let j = i + 2; j < n - 1 && !(along[j] - along[i + 1] > window); j++) {
let cx = pts[j * 2], cy = pts[j * 2 + 1], dx = pts[j * 2 + 2], dy = pts[j * 2 + 3];
if (cx < minX && dx < minX || cx > maxX && dx > maxX || cy < minY && dy < minY || cy > maxY && dy > maxY) continue;
let hit = intersectSegments(ax, ay, bx, by, cx, cy, dx, dy);
if (hit && !ownLoop(pts, anc, i, j, hit)) {
found = { i, j, x: hit.x, y: hit.y, t: hit.t, u: hit.u };
break outer;
}
}
}
if (!found) break;
let cut = (found.i + 1) * 2, keep = (found.j + 1) * 2;
pts = pts.slice(0, cut).concat([found.x, found.y], pts.slice(keep));
let ai = found.i * 2, t = found.t;
anc = anc.slice(0, cut).concat([anc[ai] + (anc[ai + 2] - anc[ai]) * t, anc[ai + 1] + (anc[ai + 3] - anc[ai + 1]) * t], anc.slice(keep));
let alongCut = along[found.i] + (along[found.i + 1] - along[found.i]) * t;
along = along.slice(0, found.i + 1).concat([alongCut], along.slice(found.j + 1));
}
return { points: pts, anchors: anc };
}
function ownLoop(pts, anc, i, j, hit) {
let ring = (x0, y0, xs, k0, k1, x1, y1) => {
let a = 0, px = x0, py = y0;
for (let k = k0; k <= k1; k++) {
let x = xs[k * 2], y = xs[k * 2 + 1];
a += px * y - x * py, px = x, py = y;
}
return a + px * y1 - x1 * py + x1 * y0 - x0 * y1;
}, offset = ring(hit.x, hit.y, pts, i + 1, j, hit.x, hit.y), ground = ring(
anc[i * 2] + (anc[i * 2 + 2] - anc[i * 2]) * hit.t,
anc[i * 2 + 1] + (anc[i * 2 + 3] - anc[i * 2 + 1]) * hit.t,
anc,
i + 1,
j,
anc[j * 2] + (anc[j * 2 + 2] - anc[j * 2]) * hit.u,
anc[j * 2 + 1] + (anc[j * 2 + 3] - anc[j * 2 + 1]) * hit.u
);
return offset * ground > 0 && Math.abs(ground) >= OWN_LOOP_AREA_SHARE * Math.abs(offset);
}
function sampleCubicBezier(p0, p1, p2, p3, n) {
let out = [];
for (let i = 0; i <= n; i++) {
let t = i / n, mt = 1 - t, a = mt * mt * mt, b = 3 * mt * mt * t, c = 3 * mt * t * t, d = t * t * t;
out.push(a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]);
}
return out;
}
function connectorCurve(P, tp, Q, tq, samples, handleScale = 1) {
let K = 0.5523 * handleScale, chord = Math.hypot(Q[0] - P[0], Q[1] - P[1]), h = K * chord, I = intersectLines(P[0], P[1], P[0] + tp[0], P[1] + tp[1], Q[0], Q[1], Q[0] + tq[0], Q[1] + tq[1]);
if (I) {
let t = (I[0] - P[0]) * tp[0] + (I[1] - P[1]) * tp[1], u = (I[0] - Q[0]) * tq[0] + (I[1] - Q[1]) * tq[1];
if (t > 0 && u > 0) {
let delta = (Math.hypot(I[0] - P[0], I[1] - P[1]) + Math.hypot(I[0] - Q[0], I[1] - Q[1])) / 2;
h = K * Math.min(delta, chord * 1.5);
}
}
let c1 = [P[0] + tp[0] * h, P[1] + tp[1] * h], c2 = [Q[0] + tq[0] * h, Q[1] + tq[1] * h];
return sampleCubicBezier(P, c1, c2, Q, samples);
}
function ccwAngle(a, b) {
let d = -(Math.atan2(b[1], b[0]) - Math.atan2(a[1], a[0]));
for (; d < 0; ) d += 2 * Math.PI;
for (; d >= 2 * Math.PI; ) d -= 2 * Math.PI;
return d;
}
function roundBends(p, deviationPx, minBendDeg = 3, cornerBendDeg = 180, cornerPx = 0) {
let n = p.length / 2;
if (n < 3) return p.slice();
if (cornerBendDeg < 180) {
let cosCorner = Math.cos(cornerBendDeg * Math.PI / 180), corners = null;
for (let i = 1; i < n - 1; i++) bendAt(p, i) < cosCorner && (corners ?? (corners = [])).push(i);
if (corners) {
let out2 = [], from = 0;
for (let c of [...corners, n - 1]) {
let run = roundBends(p.slice(from * 2, (c + 1) * 2), deviationPx, minBendDeg);
for (let k = out2.length ? 2 : 0; k < run.length; k += 2) out2.push(run[k], run[k + 1]);
from = c;
}
return cornerPx > 0 ? roundCorners(out2, p, corners, cornerPx) : out2;
}
}
let cosMin = Math.cos(minBendDeg * Math.PI / 180), bends = [], reach = [];
for (let i = 1; i < n - 1; i++) {
let c = bendAt(p, i);
c >= cosMin || (bends.push(i), reach.push(4 * deviationPx / Math.sqrt(Math.max(0, 1 - c * c))));
}
if (!bends.length) return p.slice();
let cum = new Float64Array(n);
for (let i = 1; i < n; i++)
cum[i] = cum[i - 1] + Math.hypot(p[i * 2] - p[i * 2 - 2], p[i * 2 + 1] - p[i * 2 - 1]);
let out = [p[0], p[1]], done = 0;
for (let bi = 0; bi < bends.length; bi++) {
let c = bends[bi], prev = bi > 0 ? bends[bi - 1] : 0, next = bi + 1 < bends.length ? bends[bi + 1] : n - 1, cx = p[c * 2], cy = p[c * 2 + 1], ax = p[c * 2 - 2] - cx, ay = p[c * 2 - 1] - cy, la = Math.hypot(ax, ay), bx = p[c * 2 + 2] - cx, by = p[c * 2 + 3] - cy, lb = Math.hypot(bx, by), r = Math.min(reach[bi], 0.4 * (cum[c] - cum[prev]), 0.4 * (cum[next] - cum[c]), la, lb);
for (let i = done + 1; i < c; i++) out.push(p[i * 2], p[i * 2 + 1]);
if (done = c, r < 0.05) {
out.push(cx, cy);
continue;
}
let sx = cx + ax / la * r, sy = cy + ay / la * r, ex = cx + bx / lb * r, ey = cy + by / lb * r, steps = Math.max(4, Math.min(12, Math.round(r / 2))), first = Math.abs(out[out.length - 2] - sx) < 1e-9 && Math.abs(out[out.length - 1] - sy) < 1e-9 ? 1 : 0;
for (let i = first; i <= steps; i++) {
let t = i / steps, m = 1 - t;
out.push(m * m * sx + 2 * m * t * cx + t * t * ex, m * m * sy + 2 * m * t * cy + t * t * ey);
}
r >= lb && (done = c + 1);
}
for (let i = done + 1; i < n; i++) out.push(p[i * 2], p[i * 2 + 1]);
return out;
}
function roundCorners(out, src, corners, radiusPx) {
let n = src.length / 2, cum = new Float64Array(n);
for (let i = 1; i < n; i++)
cum[i] = cum[i - 1] + Math.hypot(src[i * 2] - src[i * 2 - 2], src[i * 2 + 1] - src[i * 2 - 1]);
let consumed = new Uint8Array(out.length), arcs = /* @__PURE__ */ new Map(), lastFwd = null;
for (let ci = 0; ci < corners.length; ci++) {
let c = corners[ci], prev = ci > 0 ? corners[ci - 1] : 0, next = ci + 1 < corners.length ? corners[ci + 1] : n - 1, r = Math.min(radiusPx, 0.4 * (cum[c] - cum[prev]), 0.4 * (cum[next] - cum[c]));
if (r < 0.05) continue;
let cx = src[c * 2], cy = src[c * 2 + 1], at = -1;
for (let i = 0; i < out.length; i += 2)
if (!consumed[i] && Math.abs(out[i] - cx) < 1e-6 && Math.abs(out[i + 1] - cy) < 1e-6) {
at = i;
break;
}
if (at <= 0 || at >= out.length - 2) continue;
let back = walkAlong(out, at, -2, r, lastFwd), fwd = walkAlong(out, at, 2, r, null);
if (r = Math.min(r, back.got, fwd.got), r < 0.05) continue;
let steps = Math.max(4, Math.min(12, Math.round(r / 2))), arc = [];
for (let i = 0; i <= steps; i++) {
let t = i / steps, m = 1 - t;
arc.push(m * m * back.x + 2 * m * t * cx + t * t * fwd.x, m * m * back.y + 2 * m * t * cy + t * t * fwd.y);
}
for (let i = back.idx + 2; i < fwd.idx; i += 2) consumed[i] = 1;
arcs.set(back.idx + 2, arc), lastFwd = { idx: fwd.idx, x: fwd.x, y: fwd.y };
}
if (!arcs.size) return out;
let done = [];
for (let i = 0; i < out.length; i += 2) {
let arc = arcs.get(i);
if (arc) for (let k = 0; k < arc.length; k++) done.push(arc[k]);
consumed[i] || done.push(out[i], out[i + 1]);
}
return done;
}
function walkAlong(p, at, step, dist, spliced) {
let acc = 0, i = at;
for (; ; ) {
let j = i + step;
if (j < 0 || j + 1 >= p.length) return { x: p[i], y: p[i + 1], idx: i, got: acc };
let stand = spliced !== null && step < 0 && i === spliced.idx, jx = stand ? spliced.x : p[j], jy = stand ? spliced.y : p[j + 1], seg = Math.hypot(jx - p[i], jy - p[i + 1]);
if (acc + seg >= dist) {
let t = seg > 1e-12 ? (dist - acc) / seg : 0;
return { x: p[i] + (jx - p[i]) * t, y: p[i + 1] + (jy - p[i + 1]) * t, idx: j, got: dist };
}
acc += seg, i = j;
}
}
function bendAt(p, k) {
let ax = p[k * 2] - p[k * 2 - 2], ay = p[k * 2 + 1] - p[k * 2 - 1], bx = p[k * 2 + 2] - p[k * 2], by = p[k * 2 + 3] - p[k * 2 + 1];
return (ax * bx + ay * by) / ((Math.hypot(ax, ay) || 1) * (Math.hypot(bx, by) || 1));
}
function polylineBounds(p) {
let minX = 1 / 0, minY = 1 / 0, maxX = -1 / 0, maxY = -1 / 0;
for (let i = 0; i < p.length; i += 2)
p[i] < minX && (minX = p[i]), p[i] > maxX && (maxX = p[i]), p[i + 1] < minY && (minY = p[i + 1]), p[i + 1] > maxY && (maxY = p[i + 1]);
return { minX, minY, maxX, maxY };
}
function boundsIntersect(a, b) {
return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;
}
// src/core/order.ts
function mulberry32(seed) {
let a = seed >>> 0;
return () => {
a = a + 1831565813 >>> 0;
let t = a;
return t = Math.imul(t ^ t >>> 15, t | 1), t ^= t + Math.imul(t ^ t >>> 7, t | 61), ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
var SAME_NEXT = 0, DIFF_NEXT = 1, PERIPHERY = 2, ONE_WAY_SHARE = 0.3, ONE_WAY_STOP = 0.15, SECOND_PASS_STABILITY = 0.25, ALIGN_STABILITY = 0.1, ALIGN_DEPTHS = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 1 / 0], permTables = [];
function permTable(k) {
let t = permTables[k];
if (t) return t;
t = [];
let rec = (rest, m) => {
if (!rest.length) {
t.push(m);
return;
}
for (let i = 0; i < rest.length; i++) rec(rest.slice(0, i).concat(rest.slice(i + 1)), m.concat(rest[i]));
};
return rec(Array.from({ length: k }, (_, i) => i), []), permTables[k] = t, t;
}
var LaneOrderer = class {
constructor(g, opts = {}) {
__publicField(this, "g");
__publicField(this, "w");
__publicField(this, "opts");
/** Route indices follow sorted ids, so comparing indices breaks ties as ids would. */
__publicField(this, "routeIds");
__publicField(this, "routeIndex");
/**
* Every edge's lanes and lane positions live in two flat arrays, `lanes[e]` and `pos[e]` being
* views into them, so the cost evaluation can index by edge and route without a pointer chase.
*/
__publicField(this, "laneBuf");
__publicField(this, "laneStart");
__publicField(this, "laneCount");
__publicField(this, "posBuf");
__publicField(this, "lanes");
__publicField(this, "pos");
/** Port index of edge e at its a node (2e) and b node (2e + 1). */
__publicField(this, "portAt");
/** Per node and port, per route index: the ports the route continues to. */
__publicField(this, "next");
/**
* The same continuations flat, for the swap walk: the ports of node n start at `portBase[n]`,
* a port's edge is `portEdge`, and the ports route r continues to from port q are
* `nextList[nextStart[q * R + r] .. nextStart[q * R + r + 1])`, in the order `next` lists them.
*/
__publicField(this, "portBase");
__publicField(this, "portEdge");
__publicField(this, "nextStart");
__publicField(this, "nextList");
__publicField(this, "terms");
/** Per seeded edge: lane position of each route index in the initial order (-1 when unseeded). */
__publicField(this, "seedPos", []);
__publicField(this, "stability", 0);
__publicField(this, "stack", []);
__publicField(this, "edgeStamp", new Uint32Array(0));
__publicField(this, "nodeStamp", new Uint32Array(0));
__publicField(this, "stamp", 0);
__publicField(this, "nodeCache", new Float64Array(0));
__publicField(this, "nodeFresh", new Float64Array(0));
/** Timing of the last solve, ms, both passes together, for diagnostics. */
__publicField(this, "timings", { greedy: 0, anneal: 0, descend: 0 });
this.g = g, this.opts = opts, this.w = {
sameSegmentCrossing: opts.sameSegmentCrossing ?? 4,
diffSegmentCrossing: opts.diffSegmentCrossing ?? 1,
separation: opts.separation ?? 3,
periphery: opts.periphery ?? 0.5
};
let ids = /* @__PURE__ */ new Set();
for (let e of g.edges) for (let r of e.routes) ids.add(r);
this.routeIds = [...ids].sort(), this.routeIndex = new Map(this.routeIds.map((r, i) => [r, i]));
let R = this.routeIds.length, E = g.edges.length;
this.laneStart = new Int32Array(E + 1), this.laneCount = new Int32Array(E);
for (let e = 0; e < E; e++)
this.laneCount[e] = g.edges[e].routes.length, this.laneStart[e + 1] = this.laneStart[e] + this.laneCount[e];
this.laneBuf = new Int32Array(this.laneStart[E]), this.posBuf = new Int32Array(E * R).fill(-1), this.lanes = g.edges.map((e) => this.laneBuf.subarray(this.laneStart[e.id], this.laneStart[e.id + 1])), this.pos = g.edges.map((e) => e.routes.length > 1 ? this.posBuf.subarray(e.id * R, (e.id + 1) * R) : null), this.portAt = new Int32Array(2 * g.edges.length).fill(-1);
for (let n of g.nodes) n.ports.forEach((p, i) => this.portAt[2 * p.edge + (p.end === "a" ? 0 : 1)] = i);
this.next = g.nodes.map((node) => {
let next = node.ports.map(() => []);
for (let t of node.transitions) {
if (t.from < 0 || t.to < 0 || t.from === t.to) continue;
let r = this.routeIndex.get(t.route);
if (r !== void 0)
for (let [a, b] of [[t.from, t.to], [t.to, t.from]]) {
let l = next[a][r] ?? (next[a][r] = []);
l.includes(b) || l.push(b);
}
}
return next;
}), this.portBase = new Int32Array(g.nodes.length + 1);
for (let n = 0; n < g.nodes.length; n++) this.portBase[n + 1] = this.portBase[n] + g.nodes[n].ports.length;
let P = this.portBase[g.nodes.length];
this.portEdge = new Int32Array(P), this.nextStart = new Int32Array(P * R + 1);
let list = [];
for (let n = 0; n < g.nodes.length; n++)
for (let pi = 0; pi < g.nodes[n].ports.length; pi++) {
let q = this.portBase[n] + pi;
this.portEdge[q] = g.nodes[n].ports[pi].edge;
for (let r = 0; r < R; r++) {
let l = this.next[n][pi][r];
if (l) for (let p of l) list.push(p);
this.nextStart[q * R + r + 1] = list.length;
}
}
this.nextList = Int32Array.from(list), this.terms = this.buildTerms(), this.load();
}
buildTerms() {
let g = this.g, buf = { kind: [], edge: [], out: [], a: [], b: [], next: [], nextOut: [], aLeft: [] }, start = new Int32Array(g.nodes.length + 1);
g.nodes.forEach((node, n) => {
start[n] = buf.kind.length;
let np = node.ports.length, dirs = node.ports.map((p) => {
let e = g.edges[p.edge];
return p.end === "a" ? startDirection(e.coords) : endDirection(e.coords).map((v) => -v);
}), ccw = new Float64Array(np * np);
for (let i = 0; i < np; i++) for (let j = 0; j < np; j++) ccw[i * np + j] = ccwAngle(dirs[i], dirs[j]);
for (let pi = 0; pi < np; pi++) {
let port = node.ports[pi], e = g.edges[port.edge], k = e.routes.length;
if (k < 2) continue;
let out = port.end === "a" ? 1 : 0, nextOf = this.next[n][pi], routes = e.routes.map((r) => this.routeIndex.get(r));
for (let i = 0; i < k; i++) {
let a = routes[i], aNexts = nextOf[a];
if (!aNexts || !aNexts.length) {
push(buf, PERIPHERY, e.id, out, a, -1, -1, 0, 0);
continue;
}
for (let j = i + 1; j < k; j++) {
let b = routes[j], bNexts = nextOf[b];
if (!(!bNexts || !bNexts.length))
for (let aNext of aNexts)
for (let bNext of bNexts)
if (aNext === bNext) {
if (aNext < pi) continue;
let f = node.ports[aNext];
push(buf, SAME_NEXT, e.id, out, a, b, f.edge, f.end === "a" ? 1 : 0, 0);
} else {
let aLeft = ccw[pi * np + aNext] < ccw[pi * np + bNext] ? 1 : 0;
push(buf, DIFF_NEXT, e.id, out, a, b, -1, 0, aLeft);
}
}
}
}
}), start[g.nodes.length] = buf.kind.length;
let R = this.routeIds.length, T = buf.kind.length, posA = new Int32Array(T), posB = new Int32Array(T), nextA = new Int32Array(T), nextB = new Int32Array(T);
for (let i = 0; i < T; i++)
posA[i] = buf.edge[i] * R + buf.a[i], posB[i] = buf.edge[i] * R + Math.max(0, buf.b[i]), nextA[i] = Math.max(0, buf.next[i]) * R + buf.a[i], nextB[i] = Math.max(0, buf.next[i]) * R + Math.max(0, buf.b[i]);
return {
start,
kind: Uint8Array.from(buf.kind),
edge: Int32Array.from(buf.edge),
out: Uint8Array.from(buf.out),
a: Int32Array.from(buf.a),
b: Int32Array.from(buf.b),
next: Int32Array.from(buf.next),
nextOut: Uint8Array.from(buf.nextOut),
aLeft: Uint8Array.from(buf.aLeft),
posA,
posB,
nextA,
nextB
};
}
/** Read every edge's `order` into the solver state (sorted route ids where it is unusable). */
load() {
this.g.edges.forEach((e, i) => {
let order = e.order.length === e.routes.length && sameSet(e.order, e.routes) ? e.order : e.routes.slice().sort();
this.setLanes(i, order.map((r) => this.routeIndex.get(r)));
});
}
store() {
this.g.edges.forEach((e, i) => e.order = Array.from(this.lanes[i], (r) => this.routeIds[r]));
}
setLanes(e, routes) {
let lanes = this.lanes[e];
lanes.set(routes);
let pos = this.pos[e];
if (pos) for (let i = 0; i < lanes.length; i++) pos[lanes[i]] = i;
}
/** Cost contributed by one node under the current edge orders. */
nodeCost(nodeId) {
return this.load(), this.evalNode(nodeId);
}
totalCost() {
return this.load(), this.evalAll();
}
evalAll() {
let c = 0;
for (let i = 0; i < this.g.nodes.length; i++) c += this.evalNode(i);
return c;
}
evalNode(n) {
let t = this.terms, tEdge = t.edge, tOut = t.out, tKind = t.kind, tNext = t.next, tNextOut = t.nextOut, tALeft = t.aLeft, tPosA = t.posA, tPosB = t.posB, tNextA = t.nextA, tNextB = t.nextB, pos = this.posBuf, count = this.laneCount, wPeriphery = this.w.periphery, wDiff = this.w.diffSegmentCrossing, wSame = this.w.sameSegmentCrossing, wSep = this.w.separation, cost = 0;
for (let i = t.start[n], end = t.start[n + 1]; i < end; i++) {
let k = count[tEdge[i]], pa = pos[tPosA[i]];
tOut[i] || (pa = k - 1 - pa);
let kind = tKind[i];
if (kind === PERIPHERY) {
pa !== 0 && pa !== k - 1 && (cost += wPeriphery);
continue;
}
let pb = pos[tPosB[i]];
tOut[i] || (pb = k - 1 - pb);
let aLeft = pa < pb;
if (kind === DIFF_NEXT) {
tALeft[i] === 1 !== aLeft && (cost += wDiff);
continue;
}
let fa = pos[tNextA[i]], fb = pos[tNextB[i]];
if (!tNextOut[i]) {
let kf = count[tNext[i]];
fa = kf - 1 - fa, fb = kf - 1 - fb;
}
fa < fb === aLeft ? cost += wSame : Math.abs(pa - pb) === 1 && Math.abs(fa - fb) !== 1 && (cost += wSep);
}
return cost;
}
edgeLocalCost(e) {
let edge = this.g.edges[e];
return (edge.a === edge.b ? this.evalNode(edge.a) : this.evalNode(edge.a) + this.evalNode(edge.b)) + this.edgePenalty(e);
}
edgePenalty(e) {
let sp = this.seedPos[e];
if (!sp) return 0;
let lanes = this.lanes[e], inversions = 0;
for (let i = 0; i < lanes.length; i++) {
let sa = sp[lanes[i]];
if (!(sa < 0))
for (let j = i + 1; j < lanes.length; j++) {
let sb = sp[lanes[j]];
sb >= 0 && sb < sa && inversions++;
}
}
return inversions * this.stability;
}
/** Try every permutation (k <= 6) or pairwise swaps (larger k) of one edge; keep the best. */
optimizeEdge(e) {
let lanes = this.lanes[e], k = lanes.length;
if (k < 2) return !1;
let startCost = this.edgeLocalCost(e), best = lanes.slice(), bestCost = startCost;
if (k <= 6) {
let base = lanes.slice(), scratch = new Int32Array(k);
for (let p of permTable(k)) {
for (let i = 0; i < k; i++) scratch[i] = base[p[i]];
this.setLanes(e, scratch);
let c = this.edgeLocalCost(e);
(c < bestCost - 1e-9 || Math.abs(c - bestCost) < 1e-9 && lexLess(scratch, best)) && (bestCost = c, best = scratch.slice());
}
} else {
let improved = !0;
for (; improved; ) {
improved = !1;
for (let i = 0; i < k; i++)
for (let j = i + 1; j < k; j++) {
let p = best.slice(), tmp = p[i];
p[i] = p[j], p[j] = tmp, this.setLanes(e, p);
let c = this.edgeLocalCost(e);
c < bestCost - 1e-9 && (bestCost = c, best = p, improved = !0);
}
}
}
return this.setLanes(e, best), bestCost < startCost - 1e-9;
}
descend(comp) {
let changed = !0, rounds = 0;
for (; changed && rounds++ < 100; ) {
changed = !1;
for (let e of comp.edges) this.optimizeEdge(e) && (changed = !0);
}
return this.componentCost(comp);
}
componentCost(comp) {
let c = 0;
for (let n of comp.nodes) c += this.evalNode(n);
if (this.seedPos.length) for (let e of comp.edges) c += this.edgePenalty(e);
return c;
}
/**
* Swap along every connected edge where the pair stays adjacent, so a crossing moves as a whole.
* That alone cannot remove a pair's crossing between two edges it shares, because both sides of
* it flip together. A one-way swap (`end` 0 or 1) leaves the start edge through that end only,
* and with `stop` may halt at any further edge, so such a crossing slides along the pair's run
* until it leaves it or reaches a junction where it costs less.
*/
swapAlong(e, i, touched, stamp, end = -1, stop = null) {
let g = this.g, a = this.lanes[e][i], b = this.lanes[e][i + 1], stack = this.stack, edgeStamp = this.edgeStamp, { portBase, portEdge, nextStart, nextList } = this, R = this.routeIds.length;
for (stack.length = 0, stack.push(e); stack.length; ) {
let cur = stack.pop(), pos = this.pos[cur];
if (!pos || edgeStamp[cur] === stamp) continue;
edgeStamp[cur] = stamp;
let ia = pos[a], ib = pos[b];
if (ia < 0 || ib < 0 || Math.abs(ia - ib) !== 1) continue;
touched.push(cur), this.swapPair(cur, a, b);
let edge = g.edges[cur];
for (let side = 0; side < 2; side++) {
if (cur === e && end >= 0 && side !== end || cur !== e && stop && stop() < ONE_WAY_STOP) continue;
let nodeId = side === 0 ? edge.a : edge.b, pi = this.portAt[2 * cur + side];
if (pi < 0) continue;
let q = portBase[nodeId] + pi, a0 = nextStart[q * R + a], a1 = nextStart[q * R + a + 1], b0 = nextStart[q * R + b], b1 = nextStart[q * R + b + 1];
if (!(a0 === a1 || b0 === b1))
for (let x = a0; x < a1; x++) {
let p = nextList[x];
for (let y = b0; y < b1; y++)
if (nextList[y] === p) {
stack.push(portEdge[portBase[nodeId] + p]);
break;
}
}
}
}
}
/**
* Make edge `to` agree with edge `from` across `node`, so that no pair swaps sides between
* them, and carry that along `to`'s run for `depth` further edges. The routes keep the places
* they hold as a group, so the lanes around them do not move.
*/
alignRun(from, to, node, depth, touched, saved, stamp) {
let g = this.g, edgeStamp = this.edgeStamp;
edgeStamp[from] = stamp;
let frontier = [[to, from, node]];
for (let d = 0; frontier.length; d++) {
let next = [];
for (let [h, x, n] of frontier) {
let posX = this.pos[x], posH = this.pos[h];
if (edgeStamp[h] === stamp || !posX || !posH || g.edges[h].a === g.edges[h].b || g.edges[x].a === g.edges[x].b) continue;
edgeStamp[h] = stamp;
let xOut = g.edges[x].a === n, hOut = g.edges[h].a === n, portH = this.portAt[2 * h + (hOut ? 0 : 1)], nextOf = this.next[n][this.portAt[2 * x + (xOut ? 0 : 1)]], lx = this.lanes[x], lh = this.lanes[h], group = [];
for (let i = 0; i < lx.length; i++) {
let r = lx[xOut ? i : lx.length - 1 - i];
posH[r] >= 0 && nextOf[r]?.includes(portH) && group.push(r);
}
if (group.length < 2) continue;
group.reverse();
let slots = [];
for (let i = 0; i < lh.length; i++) {
let at = hOut ? i : lh.length - 1 - i;
group.includes(lh[at]) && slots.push(at);
}
if (slots.every((at, i) => lh[at] === group[i])) continue;
touched.push(h), saved.push(lh.slice());
let aligned = lh.slice();
if (slots.forEach((at, i) => aligned[at] = group[i]), this.setLanes(h, aligned), d >= depth) continue;
let far = hOut ? g.edges[h].b : g.edges[h].a;
for (let p of g.nodes[far].ports) p.edge !== h && edgeStamp[p.edge] !== stamp && next.push([p.edge, h, far]);
}
frontier = next;
}
}
/**
* Go to each node where a pair swaps sides between two edges it shares, and align one side's
* run to the other wherever that lowers the cost, best first. A search by random swaps finds
* the same orders and takes as long again as the first pass.
*/
alignSwaps(comp, changed) {
let g = this.g, t = this.terms, cache2 = this.nodeCache, nodeStamp = this.nodeStamp;
for (let n of comp.nodes) cache2[n] = this.evalNode(n);
let touched = [], saved = [], nodes = [], costs = [], attempt = (from, to, node, depth, keep) => {
let stamp = ++this.stamp;
if (touched.length = 0, saved.length = 0, this.alignRun(from, to, node, depth, touched, saved, stamp), !touched.length) return 0;
nodes.length = 0, costs.length = 0;
for (let e of touched)
for (let n of [g.edges[e].a, g.edges[e].b])
nodeStamp[n] !== stamp && (nodeStamp[n] = stamp, nodes.push(n));
let delta = 0;
for (let n of nodes) {
let c = this.evalNode(n);
costs.push(c), delta += c - cache2[n];
}
if (this.stability > 0) {
let aligned = touched.map((e) => this.lanes[e].slice());
for (let e of touched) delta += this.edgePenalty(e);
touched.forEach((e, i) => this.setLanes(e, saved[i]));
for (let e of touched) delta -= this.edgePenalty(e);
touched.forEach((e, i) => this.setLanes(e, aligned[i]));
}
return keep ? nodes.forEach((n, i) => cache2[n] = costs[i]) : touched.forEach((e, i) => this.setLanes(e, saved[i])), delta;
};
for (let round = 0; round < 400; round++) {
let best = -1e-9, move = null, tried = /* @__PURE__ */ new Set();
for (let n of comp.nodes)
for (let k = t.start[n]; k < t.start[n + 1]; k++) {
if (t.kind[k] !== SAME_NEXT) continue;
let e = t.edge[k], f = t.next[k], key = `${n}:${e}:${f}`;
if (tried.has(key)) continue;
let pe = this.pos[e], pf = this.pos[f], left = pe[t.a[k]] < pe[t.b[k]] == (t.out[k] === 1), leftNext = pf[t.a[k]] < pf[t.b[k]] == (t.nextOut[k] === 1);
if (left === leftNext) {
tried.add(key);
for (let [from, to] of [[e, f], [f, e]]) {
let reach = -1;
for (let depth of ALIGN_DEPTHS) {
let delta = attempt(from, to, n, depth, !1);
if (touched.length === reach) break;
reach = touched.length, delta < best && (best = delta, move = [from, to, n, depth]);
}
}
}
}
if (!move) return;
attempt(move[0], move[1], move[2], move[3], !0);
for (let e of touched) changed.push(e);
}
}
/** Apply one swap and return what it changes the cost by; `touched` and `nodes` say where. */
swapDelta(e, i, end, stop, touched, nodes) {
let g = this.g, a = this.lanes[e][i], b = this.lanes[e][i + 1], stamp = ++this.stamp, nodeStamp = this.nodeStamp;
touched.length = 0, this.swapAlong(e, i, touched, stamp, end, stop), nodes.length = 0;
for (let t of touched) {
let edge = g.edges[t];
nodeStamp[edge.a] !== stamp && (nodeStamp[edge.a] = stamp, nodes.push(edge.a)), nodeStamp[edge.b] !== stamp && (nodeStamp[edge.b] = stamp, nodes.push(edge.b));
}
let delta = 0;
for (let n of nodes)
this.nodeFresh[n] = this.evalNode(n), delta += this.nodeFresh[n] - this.nodeCache[n];
if (this.stability > 0)
for (let t of touched) {
let sp = this.seedPos[t];
if (!sp || sp[a] < 0 || sp[b] < 0) continue;
let pos = this.pos[t];
delta += pos[a] < pos[b] == sp[a] < sp[b] ? -this.stability : this.stability;
}
return delta;
}
swapPair(e, a, b) {
let pos = this.pos[e], lanes = this.lanes[e], ia = pos[a], ib = pos[b];
lanes[ia] = b, lanes[ib] = a, pos[a] = ib, pos[b] = ia;
}
/**
* `oneWay` adds the one-way swaps, and keeps the best order the walk passes through rather
* than the one it ends on. The first pass of an unseeded solve runs without it.
*/
anneal(comp, moves, rand, oneWay) {
let candidates = comp.edges;
if (moves <= 0) return;
let T0 = 5, decay = Math.pow(0.3 / T0, 1 / moves), cache2 = this.nodeCache, fresh = this.nodeFresh;
for (let n of comp.nodes) cache2[n] = this.evalNode(n);
let touched = [], touchedNodes = [], running = 0, lowest = 0, kept = null, T = T0;
for (let m = 0; m < moves; m++, T *= decay) {
let e = candidates[Math.floor(rand() * candidates.length)], i = Math.floor(rand() * (this.lanes[e].length - 1)), a = this.lanes[e][i], b = this.lanes[e][i + 1], end = oneWay && rand() < ONE_WAY_SHARE ? rand() < 0.5 ? 0 : 1 : -1, delta = this.swapDelta(e, i, end, end >= 0 ? rand : null, touched, touchedNodes);
if (delta <= 0 || rand() < Math.exp(-delta / T)) {
for (let n of touchedNodes) cache2[n] = fresh[n];
if (running += delta, oneWay && running < lowest - 1e-9)
if (lowest = running, !kept) kept = candidates.map((c) => this.lanes[c].slice());
else for (let c = 0; c < candidates.length; c++) kept[c].set(this.lanes[candidates[c]]);
} else
for (let t of touched) this.swapPair(t, a, b);
}
kept && lowest < running - 1e-9 && candidates.forEach((c, k) => this.setLanes(c, kept[k]));
}
/**
* One scan of a hill climb on the annealing's own swaps, over every edge or over those marked
* in `only`. The edges it changes are added to `changed`.
*/
descendSwaps(comp, only, changed) {
let cache2 = this.nodeCache, fresh = this.nodeFresh;
for (let n of comp.nodes) cache2[n] = this.evalNode(n);
let touched = [], touchedNodes = [];
for (let e of comp.edges)
if (!(only && !only[e]))
for (let i = 0; i + 1 < this.lanes[e].length; i++)
for (let end = -1; end < 2; end++) {
let a = this.lanes[e][i], b = this.lanes[e][i + 1];
if (this.swapDelta(e, i, end, null, touched, touchedNodes) < -1e-9) {
for (let n of touchedNodes) cache2[n] = fresh[n];
for (let t of touched) changed.push(t);
} else
for (let t of touched) this.swapPair(t, a, b);
}
}
/**
* Both descents, each over the edges that share a node with one that just changed, until
* nothing changes. A change can only open a gain next to itself, so scanning the whole group
* again after each one costs several times as much and finds the same order. The first scan
* of swaps covers the whole group when `wholeFirst`, since no pass before it tried them.
*/
polish(comp, from, wholeFirst) {
let near = from ? this.beside(from) : null, whole = wholeFirst;
for (let round = 0; round < 200; round++) {
let changed = [];
for (let e of comp.edges) (!near || near[e]) && this.optimizeEdge(e) && changed.push(e);
if (this.descendSwaps(comp, whole ? null : near, changed), whole = !1, !changed.length) return;
near = this.beside(changed);
}
}
/** Marks the edges that share a node with any of `edges`, themselves included. */
beside(edges) {
let g = this.g, mark = new Uint8Array(g.edges.length);
for (let e of edges)
for (let n of [g.edges[e].a, g.edges[e].b]) for (let p of g.nodes[n].ports) mark[p.edge] = 1;
return mark;
}
/** Multi-route edges in groups that share no node, each an independent problem; sorted for determinism. */
components() {
let g = this.g, E = g.edges.length, parent = new Int32Array(E);
for (let e = 0; e < E; e++) parent[e] = e;
let find = (x) => {
for (; parent[x] !== x; ) x = parent[x] = parent[parent[x]];
return x;
};
for (let node of g.nodes) {
let first = -1;
for (let p of node.ports)
this.lanes[p.edge].length < 2 || (first < 0 ? first = p.edge : parent[find(p.edge)] = find(first));
}
let byRoot = /* @__PURE__ */ new Map();
for (let e = 0; e < E; e++) {
if (this.lanes[e].length < 2) continue;
let r = find(e), c = byRoot.get(r);
c || byRoot.set(r, c = { edges: [], nodes: [] }), c.edges.push(e);
}
let comps = [...byRoot.values()];
for (let c of comps) {
let nodes = /* @__PURE__ */ new Set();
for (let e of c.edges)
nodes.add(g.edges[e].a), nodes.add(g.edges[e].b);
c.nodes = [...nodes].sort((x, y) => x - y);
}
return comps.sort((x, y) => y.edges.length - x.edges.length || x.edges[0] - y.edges[0]);
}
/**
* Assign orders on all edges. Returns the final cost.
*
* An unseeded solve runs two passes. The first is greedy propagation and annealing with whole
* swaps. The second starts from the first's order and does no annealing: it aligns the runs
* across every pair the first left swapping sides, then descends, and charges each pair that
* leaves the first pass's order. A seeded solve is one pass from the caller's seed, annealed
* with the one-way swaps as well, at the caller's `stability`.
*/
solve() {
this.timings = { greedy: 0, anneal: 0, descend: 0 };
let seed = this.opts.initial;
if (seed && seed.size > 0) return this.pass(seed, this.opts.stability ?? 1, "seeded");
this.pass(null, 0, "first");
let first = /* @__PURE__ */ new Map();
for (let e of this.g.edges) e.routes.length > 1 && first.set(e.id, e.order.slice());
return this.pass(first, SECOND_PASS_STABILITY, "second");
}
pass(initial, stability, kind) {
let tStart = performance.now(), g = this.g, rand = mulberry32(this.opts.seed ?? 42), seeded = !!initial;
this.seedPos = g.edges.map(() => null), this.stability = seeded ? stability : 0;
for (let e of g.edges) {
let init = initial?.get(e.id)?.filter((r) => e.routes.includes(r));
if (!init || !init.length) {
e.order = e.routes.slice().sort();
continue;
}
if (e.order = init.concat(e.routes.filter((r) => !init.includes(r)).sort()), e.routes.length > 1) {
let sp = new Int32Array(this.routeIds.length).fill(-1);
init.forEach((r, i) => sp[this.routeIndex.get(r)] = i), this.seedPos[e.id] = sp;
}
}
this.load(), this.edgeStamp = new Uint32Array(g.edges.length), this.nodeStamp = new Uint32Array(g.nodes.length), this.nodeCache = new Float64Array(g.nodes.length), this.nodeFresh = new Float64Array(g.nodes.length), this.stamp = 0;
let seen = new Set(seeded ? g.edges.map((e) => e.id) : []), queue = g.edges.slice().sort((x, y) => y.routes.length - x.routes.length || x.id - y.id), frontier = [];
for (let start of queue)
if (!seen.has(start.id))
for (frontier.push(start.id); frontier.length; ) {
let id = frontier.shift();
if (seen.has(id)) continue;
seen.add(id), this.optimizeEdge(id);
let e = g.edges[id];
for (let n of [e.a, e.b]) for (let p of g.nodes[n].ports) seen.has(p.edge) || frontier.push(p.edge);
}
let timings = this.timings;
timings.greedy += performance.now() - tStart;
let comps = this.components(), candidates = comps.reduce((s, c) => s + c.edges.length, 0), totalMoves = this.opts.annealMoves ?? Math.max(1e4, 400 * candidates);
for (let comp of comps) {
let t = performance.now(), bestCost = 1 / 0, best = [];
seeded && (bestCost = kind === "second" ? this.componentCost(comp) : this.descend(comp), best = comp.edges.map((e) => this.lanes[e].slice())), timings.descend += performance.now() - t, t = performance.now();
let aligned = [];
kind === "second" ? (this.stability = ALIGN_STABILITY, this.alignSwaps(comp, aligned), this.stability = stability) : bestCost > 0 && this.anneal(comp, Math.ceil(totalMoves * comp.edges.length / candidates), rand, kind === "seeded"), timings.anneal += performance.now() - t, t = performance.now(), kind === "second" ? this.polish(comp, aligned, !0) : kind === "seeded" && this.polish(comp, null, !0);
let c = kind === "second" ? this.componentCost(comp) : this.descend(comp);
c < bestCost - 1e-9 ? (bestCost = c, best = comp.edges.map((e) => this.lanes[e].slice())) : best.forEach((l, i) => this.setLanes(comp.edges[i], l)), timings.descend += performance.now() - t;
}
return this.store(), this.evalAll();
}
};
function push(buf, kind, edge, out, a, b, next, nextOut, aLeft) {
buf.kind.push(kind), buf.edge.push(edge), buf.out.push(out), buf.a.push(a), buf.b.push(b), buf.next.push(next), buf.nextOut.push(nextOut), buf.aLeft.push(aLeft);
}
function sameSet(a, b) {
if (a.length !== b.length) return !1;
let s = new Set(a);
return b.every((x) => s.has(x));
}
function lexLess(a, b) {
for (let i = 0; i < a.length; i++) {
if (a[i] < b[i]) return !0;
if (a[i] > b[i]) return !1;
}
return !1;
}
function orderLanes(g, opts) {
return new LaneOrderer(g, opts).solve();
}
function snapshotKey(e) {
let c = e.coords, n = c.length / 2, cmp = (i, j) => c[2 * i] - c[2 * j] || c[2 * i + 1] - c[2 * j + 1], flipped = (cmp(0, n - 1) || (n > 2 ? cmp(1, n - 2) : 0)) > 0, v = (i) => {
let k = flipped ? n - 1 - i : i;
return `${c[2 * k].toFixed(9)},${c[2 * k + 1].toFixed(9)}`;
};
return { key: `${v(0)}|${v(Math.floor(n / 2))}|${v(n - 1)}`, flipped };
}
function snapshotLaneOrders(g) {
let edges = {};
for (let e of g.edges) {
let { key, flipped } = snapshotKey(e), baseline = e.baseline === void 0 ? void 0 : flipped ? -e.baseline : e.baseline;
edges[key] = { order: flipped ? e.order.slice().reverse() : e.order.slice(), baseline };
}
return { version: 3, edges };
}
function snapshotEntry(snap, e) {
let edges = snap?.version === 3 ? snap.edges : null;
if (!edges || typeof edges != "object") return null;
let { key, flipped } = snapshotKey(e), hit = Object.hasOwn(edges, key) ? edges[key] : null, order = hit?.order;
if (!Array.isArray(order) || !order.every((r) => typeof r == "string") || new Set(order).size !== order.length) return null;
let b = hit.baseline, baseline = typeof b == "number" && Number.isFinite(b) ? flipped ? -b : b : void 0;
return { order: flipped ? order.slice().reverse() : order, baseline };
}
function applyLaneOrders(g, snap) {
let n = 0;
for (let e of g.edges) {
let hit = snapshotEntry(snap, e), kept = hit ? hit.order.filter((r) => e.routes.includes(r)) : [];
e.order = kept.concat(e.routes.filter((r) => !kept.includes(r)).sort());
let exact = kept.length === e.routes.length && kept.length === hit?.order.length;
e.baseline = exact ? hit.baseline : void 0, exact && n++;
}
return n;
}
function seedFromSnapshot(g, snap) {
let initial = /* @__PURE__ */ new Map();
for (let e of g.edges) {
let hit = snapshotEntry(snap, e);
if (!hit) continue;
let kept = hit.order.filter((r) => e.routes.includes(r));
kept.length && initial.set(e.id, kept);
}
return initial;
}
// src/core/baselines.ts
function centeredPos(order, r) {
return (order.length - 1) / 2 - order.indexOf(r);
}
function stabilizeLanes(g, opts = {}) {
let maxDrift = opts.maxDrift ?? 0.5, driftWeight = opts.driftWeight ?? 1e-3, iterations = opts.iterations ?? 60, E = g.edges.length, b = new Float64Array(E), terms = g.edges.map(() => []);
for (let node of g.nodes)
for (let t of node.transitions) {
if (t.from < 0 || t.to < 0) continue;
let pu = node.ports[t.from], pv = node.ports[t.to], u = g.edges[pu.edge], v = g.edges[pv.edge];
if (u === v) continue;
let su = pu.end === "b" ? 1 : -1, sv = pv.end === "a" ? 1 : -1, posU = centeredPos(u.order, t.route), posV = centeredPos(v.order, t.route);
terms[u.id].push({ other: v.id, coef: sv / su, constant: (sv * posV - su * posU) / su }), terms[v.id].push({ other: u.id, coef: su / sv, constant: (su * posU - sv * posV) / sv });
}
let clamp = (x) => Math.max(-maxDrift, Math.min(maxDrift, x));
for (let it = 0; it < iterations; it++) {
let moved = 0;
for (let e = 0; e < E; e++) {
let ts = terms[e];
if (!ts.length) {
b[e] = 0;
continue;
}
let targets = ts.map((t) => ({ v: t.coef * b[t.other] + t.constant, w: 1 }));
targets.push({ v: 0, w: driftWeight }), targets.sort((x, y) => x.v - y.v);
let total = targets.reduce((s, t) => s + t.w, 0), acc = 0, median = 0;
for (let t of targets)
if (acc += t.w, acc >= total / 2) {
median = t.v;
break;
}
let next = clamp(median);
moved += Math.abs(next - b[e]), b[e] = next;
}
if (moved < 1e-9) break;
}
g.edges.forEach((e, i) => e.baseline = b[i]);
}
// src/core/serialize.ts
function toTransfer(g) {
return {
nodes: g.nodes.map((n) => ({ id: n.id, x: n.x, y: n.y, ports: n.ports, transitions: n.transitions })),
edges: g.edges.map((e) => ({ id: e.id, a: e.a, b: e.b, coords: e.coords, routes: e.routes, order: e.order, direction: [...e.direction], baseline: e.baseline })),
routeIds: [...g.routes.keys()],
routes: [...g.routes.values()],
chains: [...g.chains]
};
}
function unpackPaths(t) {
let n = t.route.length, paths = new Array(n);
for (let i = 0; i < n; i++) {
let from = t.offsets[i], to = t.offsets[i + 1], coords = new Array(to - from), anchors = new Array(to - from);
for (let k = from; k < to; k++)
coords[k - from] = t.coords[k], anchors[k - from] = t.anchors[k];
paths[i] = {
route: t.routeIds[t.route[i]],
look: t.looks[t.look[i]],
coords,
anchors,
kind: t.kind[i] === 0 ? "lane" : "connector",
travel: t.travel[i],
startDistance: t.startDistance[i],
edge: t.edge[i],
node: t.node[i] >= 0 ? t.node[i] : void 0,
between: t.betweenU[i] >= 0 ? [t.betweenU[i], t.betweenV[i]] : void 0
};
}
return paths;
}
// src/core/worker-client.ts
var workers = { order: null, layout: null }, failed = { order: !1, layout: !1 }, blobUrl = null, nextId = 1, pending = /* @__PURE__ */ new Map(), kindOf = (req) => req.kind === "layout" || req.kind === "dispose" ? "layout" : "order";
function settle(p, error) {
let { req } = p;
if (req.kind === "layout") {
let base = { kind: "layout", id: req.id, session: req.session };
p.resolve(error === null ? { ...base, needGraph: !0 } : { ...base, error });
} else if (req.kind === "dispose")
p.resolve({ kind: "dispose", id: req.id });
else {
let base = { kind: "order", id: req.id };
p.resolve(error === null ? { ...base, disposed: !0 } : { ...base, error });
}
}
function settleAll(kind, error) {
for (let [id, p] of pending)
kind !== null && p.worker !== kind || (pending.delete(id), settle(p, error));
}
function getWorker(kind) {
let have = workers[kind];
if (have) return have;
if (failed[kind] || typeof Worker > "u") return null;
let worker;
try {
blobUrl || (blobUrl = URL.createObjectURL(new Blob(['"use strict";(()=>{var _n=Object.defineProperty;var Vn=(e,n,t)=>n in e?_n(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var D=(e,n,t)=>Vn(e,typeof n!="symbol"?n+"":n,t);function Ie(e){let n=e.edges.map(o=>({...o,direction:new Map(o.direction??[]),order:o.order.slice()})),t=e.routes?new Map(e.routes.map(o=>[o.id,o])):new Map(e.routeIds.map(o=>[o,{id:o,color:"#000"}]));return{nodes:e.nodes,edges:n,routes:t,chains:new Map(e.chains)}}function Ce(e){let n=e.length,t=new Uint32Array(n+1),o=0;for(let l=0;l<n;l++)o+=e[l].coords.length,t[l+1]=o;let i={coords:new Float64Array(o),anchors:new Float64Array(o),offsets:t,routeIds:[],route:new Uint32Array(n),looks:[],look:new Uint32Array(n),kind:new Uint8Array(n),travel:new Int8Array(n),startDistance:new Float64Array(n),edge:new Int32Array(n),node:new Int32Array(n),betweenU:new Int32Array(n),betweenV:new Int32Array(n)},r=new Map,u=new Map;for(let l=0;l<n;l++){let s=e[l],a=t[l];for(let g=0;g<s.coords.length;g++)i.coords[a+g]=s.coords[g],i.anchors[a+g]=s.anchors[g];let c=r.get(s.route);c===void 0&&(c=i.routeIds.push(s.route)-1,r.set(s.route,c));let d=u.get(s.look);d===void 0&&(d=i.looks.push(s.look)-1,u.set(s.look,d)),i.route[l]=c,i.look[l]=d,i.kind[l]=s.kind==="lane"?0:1,i.travel[l]=s.travel,i.startDistance[l]=s.startDistance,i.edge[l]=s.edge,i.node[l]=s.node??-1,i.betweenU[l]=s.between?s.between[0]:-1,i.betweenV[l]=s.between?s.between[1]:-1}return i}function De(e){return[e.coords.buffer,e.anchors.buffer,e.offsets.buffer,e.route.buffer,e.look.buffer,e.kind.buffer,e.travel.buffer,e.startDistance.buffer,e.edge.buffer,e.node.buffer,e.betweenU.buffer,e.betweenV.buffer]}function H(e){let n=0;for(let t=2;t<e.length;t+=2)n+=Math.hypot(e[t]-e[t-2],e[t+1]-e[t-1]);return n}function W(e){let n=new Array(e.length);for(let t=0,o=e.length-2;t<e.length;t+=2,o-=2)n[t]=e[o],n[t+1]=e[o+1];return n}function ne(e){for(let n=2;n<e.length;n+=2){let t=e[n]-e[0],o=e[n+1]-e[1],i=Math.hypot(t,o);if(i>0)return[t/i,o/i]}return[0,0]}function te(e){let n=e.length;for(let t=n-4;t>=0;t-=2){let o=e[n-2]-e[t],i=e[n-1]-e[t+1],r=Math.hypot(o,i);if(r>0)return[o/r,i/r]}return[0,0]}function Oe(e,n){let t=Xe(e,n),o=t[0]-e[0],i=t[1]-e[1],r=Math.hypot(o,i);return r>0?[o/r,i/r]:ne(e)}function me(e,n){let t=e.length,o=Xe(W(e),n),i=e[t-2]-o[0],r=e[t-1]-o[1],u=Math.hypot(i,r);return u>0?[i/u,r/u]:te(e)}function Xe(e,n){let t=0;for(let o=2;o<e.length;o+=2){let i=Math.hypot(e[o]-e[o-2],e[o+1]-e[o-1]);if(t+i>=n){let r=i>0?(n-t)/i:0;return[e[o-2]+(e[o]-e[o-2])*r,e[o-1]+(e[o+1]-e[o-1])*r]}t+=i}return[e[e.length-2],e[e.length-1]]}function ue(e,n,t,o=.2){let i=e.length/2,r=new Float64Array(Math.max(0,i-1)),u=0;for(let g=0;g<i-1;g++)r[g]=Math.hypot(e[g*2+2]-e[g*2],e[g*2+3]-e[g*2+1]),u+=r[g];if(u<=0)return e.slice();let l=u*(1-o);if(n+t>l){let g=l/(n+t);n*=g,t*=g}let s=ze(e,r,n),a=ze(e,r,u-t),c=[s.x,s.y],d=0;for(let g=0;g<i-1;g++)d+=r[g],d>n&&d<u-t&&c.push(e[g*2+2],e[g*2+3]);return c.push(a.x,a.y),c}function ze(e,n,t){if(t<=0)return{x:e[0],y:e[1]};let o=0;for(let i=0;i<n.length;i++){let r=n[i];if(o+r>=t){let u=r>0?(t-o)/r:0;return{x:e[i*2]+(e[i*2+2]-e[i*2])*u,y:e[i*2+1]+(e[i*2+3]-e[i*2+1])*u}}o+=r}return{x:e[e.length-2],y:e[e.length-1]}}function pe(e,n){let t=e.length/2;if(t<=2||n<=0)return e.slice();let o=new Uint8Array(t);o[0]=1,o[t-1]=1;let i=n*n,r=[0,t-1];for(;r.length;){let l=r.pop(),s=r.pop(),a=0,c=-1,d=e[s*2],g=e[s*2+1],p=e[l*2],h=e[l*2+1];for(let f=s+1;f<l;f++){let b=Ye(e[f*2],e[f*2+1],d,g,p,h);b>a&&(a=b,c=f)}a>i&&c>0&&(o[c]=1,r.push(s,c,c,l))}let u=[];for(let l=0;l<t;l++)o[l]&&u.push(e[l*2],e[l*2+1]);return u}function Ze(e){let n=e.length/2,t=new Float64Array(n);if(n===0||(t[0]=1/0,t[n-1]=1/0,n<=2))return t;let o=[0,n-1],i=[1/0];for(;o.length;){let r=o.pop(),u=o.pop(),l=i.pop(),s=0,a=-1,c=e[u*2],d=e[u*2+1],g=e[r*2],p=e[r*2+1];for(let h=u+1;h<r;h++){let f=Ye(e[h*2],e[h*2+1],c,d,g,p);f>s&&(s=f,a=h)}if(s>0&&a>0){let h=s<l?s:l;t[a]=h,o.push(u,a,a,r),i.push(h,h)}}return t}function Je(e,n,t){let o=e.length/2;if(o<=2||t<=0)return e.slice();let i=t*t,r=[];for(let u=0;u<o;u++)n[u]>i&&r.push(e[u*2],e[u*2+1]);return r}function Ye(e,n,t,o,i,r){let u=i-t,l=r-o,s=u*u+l*l;if(s>0){let a=Math.max(0,Math.min(1,((e-t)*u+(n-o)*l)/s));u=t+u*a,l=o+l*a}else u=t,l=o;return(e-u)*(e-u)+(n-l)*(n-l)}function He(e,n=1e-9){let t=[];for(let o=0;o<e.length;o+=2){let i=t.length;i>=2&&Math.abs(t[i-2]-e[o])<n&&Math.abs(t[i-1]-e[o+1])<n||t.push(e[o],e[o+1])}return t}var Ke=12,Bn=8;function qe(e,n,t=Math.PI/9){return K(e,n,t).points}function K(e,n,t=Math.PI/9){let o=He(e),i=o.length/2;if(i<2||n===0)return{points:o.slice(),anchors:o.slice()};let r=new Float64Array((i-1)*4);for(let a=0;a<i-1;a++){let c=o[a*2],d=o[a*2+1],g=o[a*2+2],p=o[a*2+3],h=g-c,f=p-d,b=Math.hypot(h,f),m=f/b,k=-h/b;r[a*4]=c+m*n,r[a*4+1]=d+k*n,r[a*4+2]=g+m*n,r[a*4+3]=p+k*n}let u=[r[0],r[1]],l=[o[0],o[1]];for(let a=1;a<i-1;a++){let c=(a-1)*4,d=a*4,g=r[c],p=r[c+1],h=r[c+2],f=r[c+3],b=r[d],m=r[d+1],k=r[d+2],y=r[d+3],M=o[a*2],P=o[a*2+1],x=(h-g)*(y-m)-(f-p)*(k-b),w=(h-g)*(k-b)+(f-p)*(y-m),v=n>0==x>0;if(Math.abs(x)<1e-9*Math.max(1,Math.abs(w))){u.push(b,m),l.push(M,P);continue}if(!v){let U=be(g,p,h,f,b,m,k,y);U&&Math.hypot(U[0]-M,U[1]-P)<=Bn*Math.abs(n)?(u.push(U[0],U[1]),l.push(M,P)):(u.push(h,f,b,m),l.push(M,P,M,P));continue}let A=Math.atan2(f-P,h-M),I=Math.atan2(m-P,b-M)-A;for(;I>Math.PI;)I-=2*Math.PI;for(;I<-Math.PI;)I+=2*Math.PI;let R=Math.max(1,Math.ceil(Math.abs(I)/t)),N=Math.abs(n);u.push(h,f),l.push(M,P);for(let U=1;U<R;U++){let V=A+I*U/R;u.push(M+Math.cos(V)*N,P+Math.sin(V)*N),l.push(M,P)}u.push(b,m),l.push(M,P)}u.push(r[r.length-2],r[r.length-1]),l.push(o[o.length-2],o[o.length-1]);let s=de(u,l,Math.abs(n)*Ke);return je(s,o[2]-o[0],o[3]-o[1],0,2*Math.abs(n)),je(s,o[o.length-2]-o[o.length-4],o[o.length-1]-o[o.length-3],1,2*Math.abs(n)),s}function je(e,n,t,o,i){let{points:r,anchors:u}=e,l=o?r.length-2:0,s=o?-2:2,a=0;for(let d=l+s;d>=0&&d<r.length;d+=s){let g=r[l]-r[d],p=r[l+1]-r[d+1];if(Math.hypot(g,p)>i||(o?1:-1)*(g*n+p*t)>0)break;a++}if(a=Math.min(a,r.length/2-2),a<=0)return;let c=o?l-2*a:2;r.splice(c,2*a),u.splice(c,2*a)}function ae(e,n,t,o=4,i=[]){let r=He(e),u=r.length/2;if(u<2)return{points:r.slice(),anchors:r.slice()};let l=[r[0],r[1]];for(let p=1;p<u;p++){let h=r[p*2-2],f=r[p*2-1],b=r[p*2],m=r[p*2+1],k=Math.hypot(b-h,m-f),y=Math.max(1,Math.ceil(k/o));for(let M=1;M<=y;M++)l.push(h+(b-h)*M/y,f+(m-f)*M/y)}let s=l.length/2,a=H(l),c=new Array(l.length),d=0;for(let p=0;p<s;p++){let h=l[p*2],f=l[p*2+1];p>0&&(d+=Math.hypot(h-l[p*2-2],f-l[p*2-1]));let b=n;if(a>0){let I=0,R=n,N=a,U=t;for(let V=0;V<i.length;V+=2){let S=i[V]*a;if(S<=d)I=S,R=i[V+1];else{N=S,U=i[V+1];break}}b=N>I?R+(U-R)*(d-I)/(N-I):U}let m=0,k=0,y=0,M=0;if(p>0){m=h-l[p*2-2],k=f-l[p*2-1];let I=Math.hypot(m,k)||1;m/=I,k/=I}if(p<s-1){y=l[p*2+2]-h,M=l[p*2+3]-f;let I=Math.hypot(y,M)||1;y/=I,M/=I}p===0&&([m,k]=[y,M]),p===s-1&&([y,M]=[m,k]);let P=k,x=-m,w=M,v=-y,O=P+w,A=x+v,F=Math.hypot(O,A);if(F<1e-9)O=P,A=x;else{let I=Math.min(1,Math.max(.5,F/2));O=O/F/I,A=A/F/I}c[p*2]=h+O*b,c[p*2+1]=f+A*b}let g=Math.max(Math.abs(n),Math.abs(t),1);for(let p=1;p<i.length;p+=2)g=Math.max(g,Math.abs(i[p]));return de(c,l,g*Ke)}function Qe(e){let n=e.length/2;for(let t=0;t+1<n;t++)for(let o=t+2;o+1<n;o++)if(en(e[t*2],e[t*2+1],e[t*2+2],e[t*2+3],e[o*2],e[o*2+1],e[o*2+2],e[o*2+3]))return!0;return!1}function be(e,n,t,o,i,r,u,l){let s=[t-e,o-n],a=[u-i,l-r],c=s[0]*a[1]-s[1]*a[0];if(Math.abs(c)<1e-12)return null;let d=((i-e)*a[1]-(r-n)*a[0])/c;return[e+s[0]*d,n+s[1]*d]}function en(e,n,t,o,i,r,u,l){let s=t-e,a=o-n,c=u-i,d=l-r,g=s*d-a*c;if(Math.abs(g)<1e-12)return null;let p=i-e,h=r-n,f=(p*d-h*c)/g,b=(p*a-h*s)/g;return f<=0||f>=1||b<=0||b>=1?null:{x:e+s*f,y:n+a*f,t:f,u:b}}var Gn=.1;function de(e,n,t){let o=e,i=n,r=new Array(e.length/2);r[0]=0;for(let l=1;l<r.length;l++)r[l]=r[l-1]+Math.hypot(e[l*2]-e[l*2-2],e[l*2+1]-e[l*2-1]);let u=0;for(;!(u++>1e3);){let l=o.length/2,s=null;e:for(let h=0;h<l-1&&!s;h++){let f=o[h*2],b=o[h*2+1],m=o[h*2+2],k=o[h*2+3],y=f<m?f:m,M=f<m?m:f,P=b<k?b:k,x=b<k?k:b;for(let w=h+2;w<l-1&&!(r[w]-r[h+1]>t);w++){let v=o[w*2],O=o[w*2+1],A=o[w*2+2],F=o[w*2+3];if(v<y&&A<y||v>M&&A>M||O<P&&F<P||O>x&&F>x)continue;let I=en(f,b,m,k,v,O,A,F);if(I&&!Dn(o,i,h,w,I)){s={i:h,j:w,x:I.x,y:I.y,t:I.t,u:I.u};break e}}}if(!s)break;let a=(s.i+1)*2,c=(s.j+1)*2;o=o.slice(0,a).concat([s.x,s.y],o.slice(c));let d=s.i*2,g=s.t;i=i.slice(0,a).concat([i[d]+(i[d+2]-i[d])*g,i[d+1]+(i[d+3]-i[d+1])*g],i.slice(c));let p=r[s.i]+(r[s.i+1]-r[s.i])*g;r=r.slice(0,s.i+1).concat([p],r.slice(s.j+1))}return{points:o,anchors:i}}function Dn(e,n,t,o,i){let r=(s,a,c,d,g,p,h)=>{let f=0,b=s,m=a;for(let k=d;k<=g;k++){let y=c[k*2],M=c[k*2+1];f+=b*M-y*m,b=y,m=M}return f+b*h-p*m+p*a-s*h},u=r(i.x,i.y,e,t+1,o,i.x,i.y),l=r(n[t*2]+(n[t*2+2]-n[t*2])*i.t,n[t*2+1]+(n[t*2+3]-n[t*2+1])*i.t,n,t+1,o,n[o*2]+(n[o*2+2]-n[o*2])*i.u,n[o*2+1]+(n[o*2+3]-n[o*2+1])*i.u);return u*l>0&&Math.abs(l)>=Gn*Math.abs(u)}function zn(e,n,t,o,i){let r=[];for(let u=0;u<=i;u++){let l=u/i,s=1-l,a=s*s*s,c=3*s*s*l,d=3*s*l*l,g=l*l*l;r.push(a*e[0]+c*n[0]+d*t[0]+g*o[0],a*e[1]+c*n[1]+d*t[1]+g*o[1])}return r}function Ee(e,n,t,o,i,r=1){let u=.5523*r,l=Math.hypot(t[0]-e[0],t[1]-e[1]),s=u*l,a=be(e[0],e[1],e[0]+n[0],e[1]+n[1],t[0],t[1],t[0]+o[0],t[1]+o[1]);if(a){let g=(a[0]-e[0])*n[0]+(a[1]-e[1])*n[1],p=(a[0]-t[0])*o[0]+(a[1]-t[1])*o[1];if(g>0&&p>0){let h=(Math.hypot(a[0]-e[0],a[1]-e[1])+Math.hypot(a[0]-t[0],a[1]-t[1]))/2;s=u*Math.min(h,l*1.5)}}let c=[e[0]+n[0]*s,e[1]+n[1]*s],d=[t[0]+o[0]*s,t[1]+o[1]*s];return zn(e,c,d,t,i)}function ye(e,n){let t=-(Math.atan2(n[1],n[0])-Math.atan2(e[1],e[0]));for(;t<0;)t+=2*Math.PI;for(;t>=2*Math.PI;)t-=2*Math.PI;return t}function Fe(e,n,t=3,o=180,i=0){let r=e.length/2;if(r<3)return e.slice();if(o<180){let g=Math.cos(o*Math.PI/180),p=null;for(let h=1;h<r-1;h++)We(e,h)<g&&(p??(p=[])).push(h);if(p){let h=[],f=0;for(let b of[...p,r-1]){let m=Fe(e.slice(f*2,(b+1)*2),n,t);for(let k=h.length?2:0;k<m.length;k+=2)h.push(m[k],m[k+1]);f=b}return i>0?jn(h,e,p,i):h}}let u=Math.cos(t*Math.PI/180),l=[],s=[];for(let g=1;g<r-1;g++){let p=We(e,g);p>=u||(l.push(g),s.push(4*n/Math.sqrt(Math.max(0,1-p*p))))}if(!l.length)return e.slice();let a=new Float64Array(r);for(let g=1;g<r;g++)a[g]=a[g-1]+Math.hypot(e[g*2]-e[g*2-2],e[g*2+1]-e[g*2-1]);let c=[e[0],e[1]],d=0;for(let g=0;g<l.length;g++){let p=l[g],h=g>0?l[g-1]:0,f=g+1<l.length?l[g+1]:r-1,b=e[p*2],m=e[p*2+1],k=e[p*2-2]-b,y=e[p*2-1]-m,M=Math.hypot(k,y),P=e[p*2+2]-b,x=e[p*2+3]-m,w=Math.hypot(P,x),v=Math.min(s[g],.4*(a[p]-a[h]),.4*(a[f]-a[p]),M,w);for(let U=d+1;U<p;U++)c.push(e[U*2],e[U*2+1]);if(d=p,v<.05){c.push(b,m);continue}let O=b+k/M*v,A=m+y/M*v,F=b+P/w*v,I=m+x/w*v,R=Math.max(4,Math.min(12,Math.round(v/2))),N=Math.abs(c[c.length-2]-O)<1e-9&&Math.abs(c[c.length-1]-A)<1e-9?1:0;for(let U=N;U<=R;U++){let V=U/R,S=1-V;c.push(S*S*O+2*S*V*b+V*V*F,S*S*A+2*S*V*m+V*V*I)}v>=w&&(d=p+1)}for(let g=d+1;g<r;g++)c.push(e[g*2],e[g*2+1]);return c}function jn(e,n,t,o){let i=n.length/2,r=new Float64Array(i);for(let c=1;c<i;c++)r[c]=r[c-1]+Math.hypot(n[c*2]-n[c*2-2],n[c*2+1]-n[c*2-1]);let u=new Uint8Array(e.length),l=new Map,s=null;for(let c=0;c<t.length;c++){let d=t[c],g=c>0?t[c-1]:0,p=c+1<t.length?t[c+1]:i-1,h=Math.min(o,.4*(r[d]-r[g]),.4*(r[p]-r[d]));if(h<.05)continue;let f=n[d*2],b=n[d*2+1],m=-1;for(let x=0;x<e.length;x+=2)if(!u[x]&&Math.abs(e[x]-f)<1e-6&&Math.abs(e[x+1]-b)<1e-6){m=x;break}if(m<=0||m>=e.length-2)continue;let k=$e(e,m,-2,h,s),y=$e(e,m,2,h,null);if(h=Math.min(h,k.got,y.got),h<.05)continue;let M=Math.max(4,Math.min(12,Math.round(h/2))),P=[];for(let x=0;x<=M;x++){let w=x/M,v=1-w;P.push(v*v*k.x+2*v*w*f+w*w*y.x,v*v*k.y+2*v*w*b+w*w*y.y)}for(let x=k.idx+2;x<y.idx;x+=2)u[x]=1;l.set(k.idx+2,P),s={idx:y.idx,x:y.x,y:y.y}}if(!l.size)return e;let a=[];for(let c=0;c<e.length;c+=2){let d=l.get(c);if(d)for(let g=0;g<d.length;g++)a.push(d[g]);u[c]||a.push(e[c],e[c+1])}return a}function $e(e,n,t,o,i){let r=0,u=n;for(;;){let l=u+t;if(l<0||l+1>=e.length)return{x:e[u],y:e[u+1],idx:u,got:r};let s=i!==null&&t<0&&u===i.idx,a=s?i.x:e[l],c=s?i.y:e[l+1],d=Math.hypot(a-e[u],c-e[u+1]);if(r+d>=o){let g=d>1e-12?(o-r)/d:0;return{x:e[u]+(a-e[u])*g,y:e[u+1]+(c-e[u+1])*g,idx:l,got:o}}r+=d,u=l}}function We(e,n){let t=e[n*2]-e[n*2-2],o=e[n*2+1]-e[n*2-1],i=e[n*2+2]-e[n*2],r=e[n*2+3]-e[n*2+1];return(t*i+o*r)/((Math.hypot(t,o)||1)*(Math.hypot(i,r)||1))}function nn(e){let n=1/0,t=1/0,o=-1/0,i=-1/0;for(let r=0;r<e.length;r+=2)e[r]<n&&(n=e[r]),e[r]>o&&(o=e[r]),e[r+1]<t&&(t=e[r+1]),e[r+1]>i&&(i=e[r+1]);return{minX:n,minY:t,maxX:o,maxY:i}}function tn(e,n){return e.minX<=n.maxX&&e.maxX>=n.minX&&e.minY<=n.maxY&&e.maxY>=n.minY}function $n(e){let n=e>>>0;return()=>{n=n+1831565813>>>0;let t=n;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}var on=0,sn=1,rn=2,Wn=.3,Xn=.15,Zn=.25,Jn=.1,Yn=[0,1,2,3,4,6,8,12,16,24,1/0],an=[];function Hn(e){let n=an[e];if(n)return n;n=[];let t=(o,i)=>{if(!o.length){n.push(i);return}for(let r=0;r<o.length;r++)t(o.slice(0,r).concat(o.slice(r+1)),i.concat(o[r]))};return t(Array.from({length:e},(o,i)=>i),[]),an[e]=n,n}var Me=class{constructor(n,t={}){D(this,"g");D(this,"w");D(this,"opts");D(this,"routeIds");D(this,"routeIndex");D(this,"laneBuf");D(this,"laneStart");D(this,"laneCount");D(this,"posBuf");D(this,"lanes");D(this,"pos");D(this,"portAt");D(this,"next");D(this,"portBase");D(this,"portEdge");D(this,"nextStart");D(this,"nextList");D(this,"terms");D(this,"seedPos",[]);D(this,"stability",0);D(this,"stack",[]);D(this,"edgeStamp",new Uint32Array(0));D(this,"nodeStamp",new Uint32Array(0));D(this,"stamp",0);D(this,"nodeCache",new Float64Array(0));D(this,"nodeFresh",new Float64Array(0));D(this,"timings",{greedy:0,anneal:0,descend:0});this.g=n,this.opts=t,this.w={sameSegmentCrossing:t.sameSegmentCrossing??4,diffSegmentCrossing:t.diffSegmentCrossing??1,separation:t.separation??3,periphery:t.periphery??.5};let o=new Set;for(let s of n.edges)for(let a of s.routes)o.add(a);this.routeIds=[...o].sort(),this.routeIndex=new Map(this.routeIds.map((s,a)=>[s,a]));let i=this.routeIds.length,r=n.edges.length;this.laneStart=new Int32Array(r+1),this.laneCount=new Int32Array(r);for(let s=0;s<r;s++)this.laneCount[s]=n.edges[s].routes.length,this.laneStart[s+1]=this.laneStart[s]+this.laneCount[s];this.laneBuf=new Int32Array(this.laneStart[r]),this.posBuf=new Int32Array(r*i).fill(-1),this.lanes=n.edges.map(s=>this.laneBuf.subarray(this.laneStart[s.id],this.laneStart[s.id+1])),this.pos=n.edges.map(s=>s.routes.length>1?this.posBuf.subarray(s.id*i,(s.id+1)*i):null),this.portAt=new Int32Array(2*n.edges.length).fill(-1);for(let s of n.nodes)s.ports.forEach((a,c)=>this.portAt[2*a.edge+(a.end==="a"?0:1)]=c);this.next=n.nodes.map(s=>{let a=s.ports.map(()=>[]);for(let c of s.transitions){if(c.from<0||c.to<0||c.from===c.to)continue;let d=this.routeIndex.get(c.route);if(d!==void 0)for(let[g,p]of[[c.from,c.to],[c.to,c.from]]){let h=a[g][d]??(a[g][d]=[]);h.includes(p)||h.push(p)}}return a}),this.portBase=new Int32Array(n.nodes.length+1);for(let s=0;s<n.nodes.length;s++)this.portBase[s+1]=this.portBase[s]+n.nodes[s].ports.length;let u=this.portBase[n.nodes.length];this.portEdge=new Int32Array(u),this.nextStart=new Int32Array(u*i+1);let l=[];for(let s=0;s<n.nodes.length;s++)for(let a=0;a<n.nodes[s].ports.length;a++){let c=this.portBase[s]+a;this.portEdge[c]=n.nodes[s].ports[a].edge;for(let d=0;d<i;d++){let g=this.next[s][a][d];if(g)for(let p of g)l.push(p);this.nextStart[c*i+d+1]=l.length}}this.nextList=Int32Array.from(l),this.terms=this.buildTerms(),this.load()}buildTerms(){let n=this.g,t={kind:[],edge:[],out:[],a:[],b:[],next:[],nextOut:[],aLeft:[]},o=new Int32Array(n.nodes.length+1);n.nodes.forEach((c,d)=>{o[d]=t.kind.length;let g=c.ports.length,p=c.ports.map(f=>{let b=n.edges[f.edge];return f.end==="a"?ne(b.coords):te(b.coords).map(m=>-m)}),h=new Float64Array(g*g);for(let f=0;f<g;f++)for(let b=0;b<g;b++)h[f*g+b]=ye(p[f],p[b]);for(let f=0;f<g;f++){let b=c.ports[f],m=n.edges[b.edge],k=m.routes.length;if(k<2)continue;let y=b.end==="a"?1:0,M=this.next[d][f],P=m.routes.map(x=>this.routeIndex.get(x));for(let x=0;x<k;x++){let w=P[x],v=M[w];if(!v||!v.length){Re(t,rn,m.id,y,w,-1,-1,0,0);continue}for(let O=x+1;O<k;O++){let A=P[O],F=M[A];if(!(!F||!F.length))for(let I of v)for(let R of F)if(I===R){if(I<f)continue;let N=c.ports[I];Re(t,on,m.id,y,w,A,N.edge,N.end==="a"?1:0,0)}else{let N=h[f*g+I]<h[f*g+R]?1:0;Re(t,sn,m.id,y,w,A,-1,0,N)}}}}}),o[n.nodes.length]=t.kind.length;let i=this.routeIds.length,r=t.kind.length,u=new Int32Array(r),l=new Int32Array(r),s=new Int32Array(r),a=new Int32Array(r);for(let c=0;c<r;c++)u[c]=t.edge[c]*i+t.a[c],l[c]=t.edge[c]*i+Math.max(0,t.b[c]),s[c]=Math.max(0,t.next[c])*i+t.a[c],a[c]=Math.max(0,t.next[c])*i+Math.max(0,t.b[c]);return{start:o,kind:Uint8Array.from(t.kind),edge:Int32Array.from(t.edge),out:Uint8Array.from(t.out),a:Int32Array.from(t.a),b:Int32Array.from(t.b),next:Int32Array.from(t.next),nextOut:Uint8Array.from(t.nextOut),aLeft:Uint8Array.from(t.aLeft),posA:u,posB:l,nextA:s,nextB:a}}load(){this.g.edges.forEach((n,t)=>{let o=n.order.length===n.routes.length&&Kn(n.order,n.routes)?n.order:n.routes.slice().sort();this.setLanes(t,o.map(i=>this.routeIndex.get(i)))})}store(){this.g.edges.forEach((n,t)=>n.order=Array.from(this.lanes[t],o=>this.routeIds[o]))}setLanes(n,t){let o=this.lanes[n];o.set(t);let i=this.pos[n];if(i)for(let r=0;r<o.length;r++)i[o[r]]=r}nodeCost(n){return this.load(),this.evalNode(n)}totalCost(){return this.load(),this.evalAll()}evalAll(){let n=0;for(let t=0;t<this.g.nodes.length;t++)n+=this.evalNode(t);return n}evalNode(n){let t=this.terms,o=t.edge,i=t.out,r=t.kind,u=t.next,l=t.nextOut,s=t.aLeft,a=t.posA,c=t.posB,d=t.nextA,g=t.nextB,p=this.posBuf,h=this.laneCount,f=this.w.periphery,b=this.w.diffSegmentCrossing,m=this.w.sameSegmentCrossing,k=this.w.separation,y=0;for(let M=t.start[n],P=t.start[n+1];M<P;M++){let x=h[o[M]],w=p[a[M]];i[M]||(w=x-1-w);let v=r[M];if(v===rn){w!==0&&w!==x-1&&(y+=f);continue}let O=p[c[M]];i[M]||(O=x-1-O);let A=w<O;if(v===sn){s[M]===1!==A&&(y+=b);continue}let F=p[d[M]],I=p[g[M]];if(!l[M]){let R=h[u[M]];F=R-1-F,I=R-1-I}F<I===A?y+=m:Math.abs(w-O)===1&&Math.abs(F-I)!==1&&(y+=k)}return y}edgeLocalCost(n){let t=this.g.edges[n];return(t.a===t.b?this.evalNode(t.a):this.evalNode(t.a)+this.evalNode(t.b))+this.edgePenalty(n)}edgePenalty(n){let t=this.seedPos[n];if(!t)return 0;let o=this.lanes[n],i=0;for(let r=0;r<o.length;r++){let u=t[o[r]];if(!(u<0))for(let l=r+1;l<o.length;l++){let s=t[o[l]];s>=0&&s<u&&i++}}return i*this.stability}optimizeEdge(n){let t=this.lanes[n],o=t.length;if(o<2)return!1;let i=this.edgeLocalCost(n),r=t.slice(),u=i;if(o<=6){let l=t.slice(),s=new Int32Array(o);for(let a of Hn(o)){for(let d=0;d<o;d++)s[d]=l[a[d]];this.setLanes(n,s);let c=this.edgeLocalCost(n);(c<u-1e-9||Math.abs(c-u)<1e-9&&qn(s,r))&&(u=c,r=s.slice())}}else{let l=!0;for(;l;){l=!1;for(let s=0;s<o;s++)for(let a=s+1;a<o;a++){let c=r.slice(),d=c[s];c[s]=c[a],c[a]=d,this.setLanes(n,c);let g=this.edgeLocalCost(n);g<u-1e-9&&(u=g,r=c,l=!0)}}}return this.setLanes(n,r),u<i-1e-9}descend(n){let t=!0,o=0;for(;t&&o++<100;){t=!1;for(let i of n.edges)this.optimizeEdge(i)&&(t=!0)}return this.componentCost(n)}componentCost(n){let t=0;for(let o of n.nodes)t+=this.evalNode(o);if(this.seedPos.length)for(let o of n.edges)t+=this.edgePenalty(o);return t}swapAlong(n,t,o,i,r=-1,u=null){let l=this.g,s=this.lanes[n][t],a=this.lanes[n][t+1],c=this.stack,d=this.edgeStamp,{portBase:g,portEdge:p,nextStart:h,nextList:f}=this,b=this.routeIds.length;for(c.length=0,c.push(n);c.length;){let m=c.pop(),k=this.pos[m];if(!k||d[m]===i)continue;d[m]=i;let y=k[s],M=k[a];if(y<0||M<0||Math.abs(y-M)!==1)continue;o.push(m),this.swapPair(m,s,a);let P=l.edges[m];for(let x=0;x<2;x++){if(m===n&&r>=0&&x!==r||m!==n&&u&&u()<Xn)continue;let w=x===0?P.a:P.b,v=this.portAt[2*m+x];if(v<0)continue;let O=g[w]+v,A=h[O*b+s],F=h[O*b+s+1],I=h[O*b+a],R=h[O*b+a+1];if(!(A===F||I===R))for(let N=A;N<F;N++){let U=f[N];for(let V=I;V<R;V++)if(f[V]===U){c.push(p[g[w]+U]);break}}}}}alignRun(n,t,o,i,r,u,l){let s=this.g,a=this.edgeStamp;a[n]=l;let c=[[t,n,o]];for(let d=0;c.length;d++){let g=[];for(let[p,h,f]of c){let b=this.pos[h],m=this.pos[p];if(a[p]===l||!b||!m||s.edges[p].a===s.edges[p].b||s.edges[h].a===s.edges[h].b)continue;a[p]=l;let k=s.edges[h].a===f,y=s.edges[p].a===f,M=this.portAt[2*p+(y?0:1)],P=this.next[f][this.portAt[2*h+(k?0:1)]],x=this.lanes[h],w=this.lanes[p],v=[];for(let I=0;I<x.length;I++){let R=x[k?I:x.length-1-I];m[R]>=0&&P[R]?.includes(M)&&v.push(R)}if(v.length<2)continue;v.reverse();let O=[];for(let I=0;I<w.length;I++){let R=y?I:w.length-1-I;v.includes(w[R])&&O.push(R)}if(O.every((I,R)=>w[I]===v[R]))continue;r.push(p),u.push(w.slice());let A=w.slice();if(O.forEach((I,R)=>A[I]=v[R]),this.setLanes(p,A),d>=i)continue;let F=y?s.edges[p].b:s.edges[p].a;for(let I of s.nodes[F].ports)I.edge!==p&&a[I.edge]!==l&&g.push([I.edge,p,F])}c=g}}alignSwaps(n,t){let o=this.g,i=this.terms,r=this.nodeCache,u=this.nodeStamp;for(let g of n.nodes)r[g]=this.evalNode(g);let l=[],s=[],a=[],c=[],d=(g,p,h,f,b)=>{let m=++this.stamp;if(l.length=0,s.length=0,this.alignRun(g,p,h,f,l,s,m),!l.length)return 0;a.length=0,c.length=0;for(let y of l)for(let M of[o.edges[y].a,o.edges[y].b])u[M]!==m&&(u[M]=m,a.push(M));let k=0;for(let y of a){let M=this.evalNode(y);c.push(M),k+=M-r[y]}if(this.stability>0){let y=l.map(M=>this.lanes[M].slice());for(let M of l)k+=this.edgePenalty(M);l.forEach((M,P)=>this.setLanes(M,s[P]));for(let M of l)k-=this.edgePenalty(M);l.forEach((M,P)=>this.setLanes(M,y[P]))}return b?a.forEach((y,M)=>r[y]=c[M]):l.forEach((y,M)=>this.setLanes(y,s[M])),k};for(let g=0;g<400;g++){let p=-1e-9,h=null,f=new Set;for(let b of n.nodes)for(let m=i.start[b];m<i.start[b+1];m++){if(i.kind[m]!==on)continue;let k=i.edge[m],y=i.next[m],M=`${b}:${k}:${y}`;if(f.has(M))continue;let P=this.pos[k],x=this.pos[y],w=P[i.a[m]]<P[i.b[m]]==(i.out[m]===1),v=x[i.a[m]]<x[i.b[m]]==(i.nextOut[m]===1);if(w===v){f.add(M);for(let[O,A]of[[k,y],[y,k]]){let F=-1;for(let I of Yn){let R=d(O,A,b,I,!1);if(l.length===F)break;F=l.length,R<p&&(p=R,h=[O,A,b,I])}}}}if(!h)return;d(h[0],h[1],h[2],h[3],!0);for(let b of l)t.push(b)}}swapDelta(n,t,o,i,r,u){let l=this.g,s=this.lanes[n][t],a=this.lanes[n][t+1],c=++this.stamp,d=this.nodeStamp;r.length=0,this.swapAlong(n,t,r,c,o,i),u.length=0;for(let p of r){let h=l.edges[p];d[h.a]!==c&&(d[h.a]=c,u.push(h.a)),d[h.b]!==c&&(d[h.b]=c,u.push(h.b))}let g=0;for(let p of u)this.nodeFresh[p]=this.evalNode(p),g+=this.nodeFresh[p]-this.nodeCache[p];if(this.stability>0)for(let p of r){let h=this.seedPos[p];if(!h||h[s]<0||h[a]<0)continue;let f=this.pos[p];g+=f[s]<f[a]==h[s]<h[a]?-this.stability:this.stability}return g}swapPair(n,t,o){let i=this.pos[n],r=this.lanes[n],u=i[t],l=i[o];r[u]=o,r[l]=t,i[t]=l,i[o]=u}anneal(n,t,o,i){let r=n.edges;if(t<=0)return;let u=5,s=Math.pow(.3/u,1/t),a=this.nodeCache,c=this.nodeFresh;for(let m of n.nodes)a[m]=this.evalNode(m);let d=[],g=[],p=0,h=0,f=null,b=u;for(let m=0;m<t;m++,b*=s){let k=r[Math.floor(o()*r.length)],y=Math.floor(o()*(this.lanes[k].length-1)),M=this.lanes[k][y],P=this.lanes[k][y+1],x=i&&o()<Wn?o()<.5?0:1:-1,w=this.swapDelta(k,y,x,x>=0?o:null,d,g);if(w<=0||o()<Math.exp(-w/b)){for(let v of g)a[v]=c[v];if(p+=w,i&&p<h-1e-9)if(h=p,!f)f=r.map(v=>this.lanes[v].slice());else for(let v=0;v<r.length;v++)f[v].set(this.lanes[r[v]])}else for(let v of d)this.swapPair(v,M,P)}f&&h<p-1e-9&&r.forEach((m,k)=>this.setLanes(m,f[k]))}descendSwaps(n,t,o){let i=this.nodeCache,r=this.nodeFresh;for(let s of n.nodes)i[s]=this.evalNode(s);let u=[],l=[];for(let s of n.edges)if(!(t&&!t[s]))for(let a=0;a+1<this.lanes[s].length;a++)for(let c=-1;c<2;c++){let d=this.lanes[s][a],g=this.lanes[s][a+1];if(this.swapDelta(s,a,c,null,u,l)<-1e-9){for(let h of l)i[h]=r[h];for(let h of u)o.push(h)}else for(let h of u)this.swapPair(h,d,g)}}polish(n,t,o){let i=t?this.beside(t):null,r=o;for(let u=0;u<200;u++){let l=[];for(let s of n.edges)(!i||i[s])&&this.optimizeEdge(s)&&l.push(s);if(this.descendSwaps(n,r?null:i,l),r=!1,!l.length)return;i=this.beside(l)}}beside(n){let t=this.g,o=new Uint8Array(t.edges.length);for(let i of n)for(let r of[t.edges[i].a,t.edges[i].b])for(let u of t.nodes[r].ports)o[u.edge]=1;return o}components(){let n=this.g,t=n.edges.length,o=new Int32Array(t);for(let l=0;l<t;l++)o[l]=l;let i=l=>{for(;o[l]!==l;)l=o[l]=o[o[l]];return l};for(let l of n.nodes){let s=-1;for(let a of l.ports)this.lanes[a.edge].length<2||(s<0?s=a.edge:o[i(a.edge)]=i(s))}let r=new Map;for(let l=0;l<t;l++){if(this.lanes[l].length<2)continue;let s=i(l),a=r.get(s);a||r.set(s,a={edges:[],nodes:[]}),a.edges.push(l)}let u=[...r.values()];for(let l of u){let s=new Set;for(let a of l.edges)s.add(n.edges[a].a),s.add(n.edges[a].b);l.nodes=[...s].sort((a,c)=>a-c)}return u.sort((l,s)=>s.edges.length-l.edges.length||l.edges[0]-s.edges[0])}solve(){this.timings={greedy:0,anneal:0,descend:0};let n=this.opts.initial;if(n&&n.size>0)return this.pass(n,this.opts.stability??1,"seeded");this.pass(null,0,"first");let t=new Map;for(let o of this.g.edges)o.routes.length>1&&t.set(o.id,o.order.slice());return this.pass(t,Zn,"second")}pass(n,t,o){let i=performance.now(),r=this.g,u=$n(this.opts.seed??42),l=!!n;this.seedPos=r.edges.map(()=>null),this.stability=l?t:0;for(let f of r.edges){let b=n?.get(f.id)?.filter(m=>f.routes.includes(m));if(!b||!b.length){f.order=f.routes.slice().sort();continue}if(f.order=b.concat(f.routes.filter(m=>!b.includes(m)).sort()),f.routes.length>1){let m=new Int32Array(this.routeIds.length).fill(-1);b.forEach((k,y)=>m[this.routeIndex.get(k)]=y),this.seedPos[f.id]=m}}this.load(),this.edgeStamp=new Uint32Array(r.edges.length),this.nodeStamp=new Uint32Array(r.nodes.length),this.nodeCache=new Float64Array(r.nodes.length),this.nodeFresh=new Float64Array(r.nodes.length),this.stamp=0;let s=new Set(l?r.edges.map(f=>f.id):[]),a=r.edges.slice().sort((f,b)=>b.routes.length-f.routes.length||f.id-b.id),c=[];for(let f of a)if(!s.has(f.id))for(c.push(f.id);c.length;){let b=c.shift();if(s.has(b))continue;s.add(b),this.optimizeEdge(b);let m=r.edges[b];for(let k of[m.a,m.b])for(let y of r.nodes[k].ports)s.has(y.edge)||c.push(y.edge)}let d=this.timings;d.greedy+=performance.now()-i;let g=this.components(),p=g.reduce((f,b)=>f+b.edges.length,0),h=this.opts.annealMoves??Math.max(1e4,400*p);for(let f of g){let b=performance.now(),m=1/0,k=[];l&&(m=o==="second"?this.componentCost(f):this.descend(f),k=f.edges.map(P=>this.lanes[P].slice())),d.descend+=performance.now()-b,b=performance.now();let y=[];o==="second"?(this.stability=Jn,this.alignSwaps(f,y),this.stability=t):m>0&&this.anneal(f,Math.ceil(h*f.edges.length/p),u,o==="seeded"),d.anneal+=performance.now()-b,b=performance.now(),o==="second"?this.polish(f,y,!0):o==="seeded"&&this.polish(f,null,!0);let M=o==="second"?this.componentCost(f):this.descend(f);M<m-1e-9?(m=M,k=f.edges.map(P=>this.lanes[P].slice())):k.forEach((P,x)=>this.setLanes(f.edges[x],P)),d.descend+=performance.now()-b}return this.store(),this.evalAll()}};function Re(e,n,t,o,i,r,u,l,s){e.kind.push(n),e.edge.push(t),e.out.push(o),e.a.push(i),e.b.push(r),e.next.push(u),e.nextOut.push(l),e.aLeft.push(s)}function Kn(e,n){if(e.length!==n.length)return!1;let t=new Set(e);return n.every(o=>t.has(o))}function qn(e,n){for(let t=0;t<e.length;t++){if(e[t]<n[t])return!0;if(e[t]>n[t])return!1}return!1}function cn(e,n){return(e.length-1)/2-e.indexOf(n)}function ln(e,n={}){let t=n.maxDrift??.5,o=n.driftWeight??.001,i=n.iterations??60,r=e.edges.length,u=new Float64Array(r),l=e.edges.map(()=>[]);for(let a of e.nodes)for(let c of a.transitions){if(c.from<0||c.to<0)continue;let d=a.ports[c.from],g=a.ports[c.to],p=e.edges[d.edge],h=e.edges[g.edge];if(p===h)continue;let f=d.end==="b"?1:-1,b=g.end==="a"?1:-1,m=cn(p.order,c.route),k=cn(h.order,c.route);l[p.id].push({other:h.id,coef:b/f,constant:(b*k-f*m)/f}),l[h.id].push({other:p.id,coef:f/b,constant:(f*m-b*k)/b})}let s=a=>Math.max(-t,Math.min(t,a));for(let a=0;a<i;a++){let c=0;for(let d=0;d<r;d++){let g=l[d];if(!g.length){u[d]=0;continue}let p=g.map(k=>({v:k.coef*u[k.other]+k.constant,w:1}));p.push({v:0,w:o}),p.sort((k,y)=>k.v-y.v);let h=p.reduce((k,y)=>k+y.w,0),f=0,b=0;for(let k of p)if(f+=k.w,f>=h/2){b=k.v;break}let m=s(b);c+=Math.abs(m-u[d]),u[d]=m}if(c<1e-9)break}e.edges.forEach((a,c)=>a.baseline=u[c])}var Qn=1/5,un=-.5,we=2,et=.15,nt=.1,dn=.01;function tt(e,n,t,o,i){let r=e.length,u=16;for(;u<2*r;)u*=2;let l=(h,f)=>(Math.imul(h,73856093)^Math.imul(f,19349663))&u-1,s=new Int32Array(r),a=new Int32Array(u+1);for(let h=0;h<r;h++)s[h]=l(Math.floor(e[h]/t),Math.floor(n[h]/t)),a[s[h]+1]++;for(let h=0;h<u;h++)a[h+1]+=a[h];let c=new Int32Array(r),d=a.slice(0,u);for(let h=0;h<r;h++)c[d[s[h]]++]=h;let g=t*t,p=new Int32Array(9);for(let h=0;h<r-o;h++){let f=Math.floor(e[h]/t),b=Math.floor(n[h]/t),m=0;for(let k=b-1;k<=b+1;k++)for(let y=f-1;y<=f+1;y++){let M=l(y,k),P=!1;for(let x=0;x<m;x++)p[x]===M&&(P=!0);if(!P){p[m++]=M;for(let x=a[M+1]-1;x>=a[M];x--){let w=c[x];if(w-h<o)break;let v=e[w]-e[h],O=n[w]-n[h],A=v*v+O*O;A<g&&i(h,w,A)}}}}}var ot=1;function fn(e,n,t,o){let i=e.length/2;if(i<3||!(n>=ot))return e;let r=Math.PI/2*n,u=0;for(let S=2;S<e.length;S+=2)u+=Math.hypot(e[S]-e[S-2],e[S+1]-e[S-1]);if(u-t-o<=r)return e;{let S=0,L=0,C=0,E=Math.atan2(e[3]-e[1],e[2]-e[0]);for(let T=4;T<e.length;T+=2){let _=Math.atan2(e[T+1]-e[T-1],e[T]-e[T-2]),B=_-E;B>Math.PI?B-=2*Math.PI:B<-Math.PI&&(B+=2*Math.PI),S+=B,S<L&&(L=S),S>C&&(C=S),E=_}if(C-L<Math.acos(un))return e}let l=Math.max(2,Math.ceil(u/(n*Qn))),s=u/l,a=l+1,c=new Float64Array(a),d=new Float64Array(a);{let S=1,L=0,C=Math.hypot(e[2]-e[0],e[3]-e[1]);for(let E=0;E<a;E++){let T=E===l?u:E*s;for(;S<i-1&&T>L+C;)L+=C,S++,C=Math.hypot(e[S*2]-e[S*2-2],e[S*2+1]-e[S*2-1]);let _=C>0?Math.min(1,(T-L)/C):0;c[E]=e[S*2-2]+(e[S*2]-e[S*2-2])*_,d[E]=e[S*2-1]+(e[S*2+1]-e[S*2-1])*_}}let g=new Uint8Array(a),p=[];if(tt(c,d,n,Math.floor(r/s)+1,(S,L,C)=>{let E=Math.max(0,S-we),T=Math.min(a-1,S+we),_=Math.max(0,L-we),B=Math.min(a-1,L+we),G=c[T]-c[E],z=d[T]-d[E],j=c[B]-c[_],$=d[B]-d[_];if(G*j+z*$>un*Math.hypot(G,z)*Math.hypot(j,$))return;let X=c[L]-c[S],Z=d[L]-d[S];p.push(S,L,C),g[S]|=G*Z-z*X>0?1:2,g[L]|=$*X-j*Z>0?1:2}),!p.length)return e;let h=[];for(let S=0;S<p.length;S+=3)h.push(S);h.sort((S,L)=>p[S+2]-p[L+2]);let f=n*n,b=(S,L)=>(c[S]-c[L])*(c[S]-c[L])+(d[S]-d[L])*(d[S]-d[L]),m=new Uint8Array(a),k=[];for(let S of h){let L=p[S],C=p[S+1];if(m[L]===1||m[C]===1||m[L]&&m[C])continue;let E=L,T=C,_=-1;for(;;){if(C-L<=2){_=L+C>>1;break}let $=b(L+1,C-1),X=b(L+1,C),Z=b(L,C-1),J=Math.min($,X,Z);if(J>=f)break;$===J?(L++,C--):X===J?L++:C--}_>=0&&(L=_-1,C=_+1);let B={ai:[],bi:[],tip:_},G=L<0||C>a-1;for(;!G;){if(m[L]===1||m[C]===1){G=!0;break}B.ai.push(L),B.bi.push(C);let $=L>0&&C<a-1?b(L-1,C+1):1/0,X=L>0?b(L-1,C):1/0,Z=C<a-1?b(L,C+1):1/0,J=Math.min($,X,Z);if(J>=f)break;$===J?(L--,C++):X===J?L--:C++}if(G||!B.ai.length){m[E]||(m[E]=2),m[T]||(m[T]=2);continue}let z=B.ai[B.ai.length-1],j=B.bi[B.bi.length-1];_>=0?m.fill(1,z,j+1):(m.fill(1,z,B.ai[0]+1),m.fill(1,B.bi[0],j+1)),k.push(B)}let y=n/2,M=S=>{let L=S*s,C=Math.min((L-t)/n,(u-L-o)/n);return C<=0?0:C>=1?1:C*C*(3-2*C)},P=new Float64Array(a),x=new Float64Array(a),w=new Uint8Array(a),v=!1;for(let S of k){let L=!1;for(let E=0;E<S.ai.length&&!L;E++)L=g[S.ai[E]]===3||g[S.bi[E]]===3;if(L)continue;let C=0;if(S.tip>=0){let E=c[S.tip],T=d[S.tip],_=0,B=E,G=T,z=0;for(;_<S.ai.length;_++){let Y=(c[S.ai[_]]+c[S.bi[_]])/2,ie=(d[S.ai[_]]+d[S.bi[_]])/2,Se=Math.hypot(Y-E,ie-T);if(Se>=y){let Ge=(y-z)/(Se-z);B+=(Y-B)*Ge,G+=(ie-G)*Ge;break}B=Y,G=ie,z=Se}if(_>=S.ai.length||M(S.ai[_])<1||M(S.bi[_])<1)continue;let j=S.ai[_],$=S.bi[_],X=Math.hypot(c[j]-c[$],d[j]-d[$])/2;if(X<1e-6)continue;let Z=(c[j]-c[$])/(2*X),J=(d[j]-d[$])/(2*X),Nn=(Z*(T-G)-J*(E-B)>0?1:-1)*Math.PI,Un=Math.atan2(J,Z);for(let Y=j;Y<=$;Y++){let ie=Un+Nn*(Y-j)/($-j);P[Y]=B+Math.cos(ie)*y-c[Y],x[Y]=G+Math.sin(ie)*y-d[Y],w[Y]=1}v=!0,C=_+1}for(let E=C;E<S.ai.length;E++){let T=S.ai[E],_=S.bi[E],B=Math.hypot(c[T]-c[_],d[T]-d[_]);if(B>=n||B<1e-6)continue;let G=(n-B)/2,z=(c[T]-c[_])/B,j=(d[T]-d[_])/B;!w[T]&&Math.hypot(P[T],x[T])<G&&(P[T]=z*G,x[T]=j*G),!w[_]&&Math.hypot(P[_],x[_])<G&&(P[_]=-z*G,x[_]=-j*G),v=!0}}if(!v)return e;let O=Math.max(1,Math.round(et*n/s)),A=Float64Array.from(P),F=Float64Array.from(x);for(let S of[A,F])for(let L=0;L<2;L++){let C=Float64Array.from(S),E=0;for(let T=-O;T<=O;T++)E+=C[Math.min(a-1,Math.max(0,T))];for(let T=0;T<a;T++)S[T]=E/(2*O+1),E+=C[Math.min(a-1,T+O+1)]-C[Math.max(0,T-O)]}for(let S=0;S<a;S++){if(w[S])continue;let L=Math.hypot(P[S],x[S]),C=Math.hypot(A[S],F[S]),E=C>1e-9?Math.max(L,C)/C:0;P[S]=A[S]*E,x[S]=F[S]*E}let I=new Uint8Array(a);for(let S=0;S<a;S++){let L=M(S);if(Math.abs(P[S]*L)<dn&&Math.abs(x[S]*L)<dn){P[S]=x[S]=0;continue}P[S]*=L,x[S]*=L,I.fill(1,Math.max(0,S-1),Math.min(a,S+2))}let R=[],N=0,U=0,V=S=>{for(;N<i;N++){if(N>0){let C=Math.hypot(e[N*2]-e[N*2-2],e[N*2+1]-e[N*2-1]);if(U+C>S)return;U+=C}let L=Math.min(a-1,Math.floor(U/s));!I[L]&&!I[Math.min(a-1,L+1)]&&R.push(e[N*2],e[N*2+1])}};for(let S=0;S<a;S++){if(!I[S])continue;V(S*s);let L=[];for(;S<a&&I[S];S++)L.push(c[S]+P[S],d[S]+x[S]);for(let C of pe(L,nt))R.push(C)}return V(1/0),R}var st=16,rt=1e3,it=1,at=.001,hn=new WeakMap;function gn(e,n){let t=ct(e).order;if(!t.length)return n;let o=new Set(t),i=0;return n.map(r=>o.has(r)?t[i++]:r)}function ct(e){let n="";for(let i of e.edges)i.order.length>1&&(n+=`${i.id}:${i.order.join(",")};`);let t=hn.get(e);if(t&&t.signature===n)return t;let o={signature:n,order:lt(e)};return hn.set(e,o),o}function lt(e){let n=[],t=[],o=new Map;for(let h of e.nodes){if(h.ports.length<2)continue;let b=h.ports.map(x=>{let w=e.edges[x.edge];return x.end==="a"?ne(w.coords):te(w.coords).map(v=>-v)}),m=(x,w)=>ye(b[x],b[w]),k=(x,w)=>{let v=h.ports[x],O=e.edges[v.edge].order,A=O.indexOf(w);return v.end==="a"?A:O.length-1-A},y=h.transitions.filter(x=>x.from>=0&&x.to>=0&&x.from!==x.to),M=new Map;for(let x of y){let w=Math.min(x.from,x.to),v=Math.max(x.from,x.to),O=`${w}:${v}`,A=M.get(O);A||M.set(O,A={u:w,v,routes:[]}),A.routes.includes(x.route)||A.routes.push(x.route)}for(let x of M.values())if(!(x.routes.length<2))for(let w of y){if(x.routes.includes(w.route))continue;let v=[w.from,w.to].filter(A=>A===x.u||A===x.v),O=[];if(v.length){if(v.length===1){let A=v[0],F=w.from===A?w.to:w.from,I=x.u===A?x.v:x.u,R=m(A,F)<m(A,I),N=k(A,w.route);O=x.routes.filter(U=>N<k(A,U)!==R)}}else{let A=m(x.u,x.v);m(x.u,w.from)<A!=m(x.u,w.to)<A&&(O=x.routes)}O.length>1&&n.push({group:O,across:w.route})}let P=new Set(y.map(x=>x.route));h.ports.forEach((x,w)=>{for(let v of e.edges[x.edge].routes){if(y.some(A=>A.route===v&&(A.from===w||A.to===w)))continue;let O=!1;for(let A of P)A===v||!h.ports.some((F,I)=>I!==w&&e.edges[F.edge].routes.includes(A))||(t.push([v,A]),O=!0);O&&o.set(v,(o.get(v)??0)+1)}})}if(!n.length)return[];let i=new Set;for(let h of n){i.add(h.across);for(let f of h.group)i.add(f)}if(i.size>st)return[];let r=[...i].sort((h,f)=>(o.get(f)??0)-(o.get(h)??0)||(h<f?-1:h>f?1:0)),u=new Map(r.map((h,f)=>[h,f])),l=r.length,s=r.map(()=>[]);for(let h of n){let f=0;for(let m of h.group)f|=1<<u.get(m);let b=s[u.get(h.across)];b.includes(f)||b.push(f)}let a=r.map(()=>0);for(let[h,f]of t){let b=u.get(h),m=u.get(f);b!==void 0&&m!==void 0&&(a[b]|=1<<m)}let c=(1<<l)-1,d=new Float64Array(c+1).fill(1/0),g=new Int8Array(c+1).fill(-1);d[0]=0;for(let h=0;h<c;h++){if(d[h]===1/0)continue;let f=0;for(let b=h;b;b&=b-1)f++;for(let b=0;b<l;b++){if(h&1<<b)continue;let m=d[h]+Math.abs(b-f)*at;for(let y of s[b]){let M=h&y;M&&M!==y&&(m+=rt)}for(let y=h&a[b];y;y&=y-1)m+=it;let k=h|1<<b;m<d[k]-1e-12&&(d[k]=m,g[k]=b)}}let p=[];for(let h=c;h;h^=1<<g[h])p.push(r[g[h]]);return p.reverse()}var yn=.25,Mn=.25,ut=.6,dt=.001,ft=.42,ht=1.5,mn=.4,gt=12,mt=6,pt=1,bt=4,yt=1.5,Mt=60,wn=1.5,wt=60,xt=1.5,At=1,xn=3,he=class{constructor(){D(this,"state",null)}clear(){this.state=null}stateFor(n,t,o,i,r,u){let l=this.state;return l&&l.graph===n&&l.zoom===t&&l.spacing===o.spacing&&l.width===o.width&&l.casing===o.casingWidth&&l.smooth===i&&l.openFolds===r&&l.laneStyle===u?l:this.state=vn(n,t,o,i,r,u)}};function vt(e,n){Pt(e);let t=e(n),o=(i,r)=>typeof i=="number"&&Number.isFinite(i)&&i>=r;if(!t||!o(t.spacing,0)||!o(t.width,0)||!o(t.casingWidth,0)||t.spacing===0||t.width===0){let i=t&&typeof t=="object"?JSON.stringify({spacing:t.spacing,width:t.width,casingWidth:t.casingWidth},(r,u)=>u===void 0?"undefined":typeof u=="number"&&!Number.isFinite(u)?String(u):u):String(t);throw new TypeError(`maplibre-gl-lanes: \\`sizes(${n})\\` must return {spacing, width, casingWidth} as finite numbers in px, with spacing and width above 0; got ${i}`)}return t}function Pt(e){if(typeof e!="function")throw new TypeError("maplibre-gl-lanes: `sizes` must be a function of the zoom that returns {spacing, width, casingWidth}")}function An(e,n,t,o={}){let i=performance.now(),r=o.smooth??!0,u=o.openFolds??!0,l=o.laneStyle??null,s=vt(t,n),a=o.cache?o.cache.stateFor(e,n,s,r,u,l):vn(e,n,s,r,u,l),c=o.bounds??null,d=o.routes?new Set(o.routes):null,g=new Uint8Array(e.edges.length);for(let m of e.edges){if(!c){g[m.id]=1;continue}m.bounds||(m.bounds=nn(m.coords)),g[m.id]=tn(m.bounds,c)?1:0}let p=[],h=new Map,f=0,b=0;for(let m of e.edges)if(!(!g[m.id]||a.short[m.id])){b++;for(let k of m.routes){if(d&&!d.has(k))continue;let y=ve(a,m.id,k);y&&(h.set(se(a,m.id,k),y),f+=y.coords.length/2,p.push(y))}}for(let m=0;m<a.junctions.length;m++){if(!pn(a.junctions[m],g))continue;let k=Te(a,m).tails;for(let y of k){let M=y.tail;if(!(!g[y.port.edge]&&!M.edges.some(P=>g[P.edge]))&&(Ve(a,y),!(y.mode!==1||d&&!d.has(M.route))))for(let P of y.slide)f+=P.coords.length/2,p.push(P)}for(let y of k)if(!(y.mode===1||d&&!d.has(y.tail.route)))for(let{edge:M}of y.tail.edges){let P=se(a,M,y.tail.route);if(!g[M]||h.has(P))continue;let x=ve(a,M,y.tail.route);x&&(h.set(P,x),f+=x.coords.length/2,p.push(x))}for(let y of a.junctions[m].islands)if(!(d&&!d.has(y.route)||!y.steps.some(M=>g[M.edge])))for(let M of Ln(a,y)){if(M.kind==="lane"){let P=se(a,M.edge,y.route);if(h.has(P))continue;h.set(P,M)}f+=M.coords.length/2,p.push(M)}}for(let m=0;m<a.junctions.length;m++)if(pn(a.junctions[m],g)){for(let k of Te(a,m).groups)if(!(!g[k.edgeU]||!g[k.edgeV])){Sn(a,k);for(let y of k.members)if(!(y.plan?.mode===1||d&&!d.has(y.route)))for(let M of a.connPaths.get(y.key)??[])f+=M.coords.length/2,p.push(M)}}for(let m of p)m.look.dash&&!a.phased.has(m.route)&&(St(a,m.route),a.phased.add(m.route));return{zoom:n,scale:a.scale,paths:p,drawOrder:a.drawOrder,bounds:c,mergedEdges:a.mergedEdges,stats:{edges:e.edges.length,edgesBuilt:b,edgesMerged:a.mergedEdges.length,nodes:e.nodes.length,vertices:f,ms:performance.now()-i}}}function vn(e,n,t,o,i,r){let{spacing:u,width:l,casingWidth:s}=t,a=512*Math.pow(2,n),c=e.edges.length,d=new Map;for(let L of e.routes.keys())d.set(L,d.size);for(let L of e.edges)for(let C of L.routes)d.has(C)||d.set(C,d.size);let g=Math.max(1,d.size),p=new Float64Array(c*g);for(let L of e.edges){let C=L.order.length;for(let E=0;E<C;E++){let T=d.get(L.order[E]);T!==void 0&&(p[L.id*g+T]=((C-1)/2-E+(L.baseline??0))*u)}}let h=new Array(c),f=new Float64Array(c),b=new Array(c),m=new Array(c);for(let L of e.edges){let C=((L.routes.length-1)/2+Math.abs(L.baseline??0))*u;L.simplifyRank||(L.simplifyRank=Ze(L.coords));let E=Je(L.coords,L.simplifyRank,Math.max(yn,Mn*C)/a);for(let T=0;T<E.length;T++)E[T]*=a;h[L.id]=E,f[L.id]=H(E),b[L.id]=ne(E),m[L.id]=te(E).map(T=>-T)}let k=L=>(L.routes.length-1)/2*u+l/2+s,y=(L,C,E)=>{let T=p[L.id*g+d.get(C)];return E?T:-T},M=new Uint8Array(c),P=L=>e.nodes[L].ports.length,x=new Float64Array(e.nodes.length);for(let L of e.nodes){let C=0;for(let E of L.ports)C=Math.max(C,e.edges[E.edge].routes.length);x[L.id]=C*u}let w=[],v=new Float64Array(2*c),O=new Float64Array(2*c),A=new Uint8Array(2*c*g);for(let L=0;L<bt;L++){w=Rt(e,M,f,b,m,k),{need:v,change:O,continues:A}=Tt(e,w,y,u,d,g);let C=!1;for(let E of e.edges){if(M[E.id]||E.a===E.b||P(E.a)<2||P(E.b)<2)continue;let T=f[E.id];(T<pt*Math.max(x[E.a],x[E.b])||T<O[2*E.id]+O[2*E.id+1])&&(M[E.id]=1,C=!0)}if(!C)break}let F=new Float64Array(c),I=new Float64Array(c),R=[];for(let L of e.edges){if(M[L.id]){R.push(L.id);continue}let C=f[L.id]*ft;F[L.id]=Math.min(v[2*L.id],C),I[L.id]=Math.min(v[2*L.id+1],C)}let N=new Map,U=(L,C,E)=>{for(let T of L.ports)if(T.edge!==C){for(let _ of e.edges[T.edge].routes)if(_!==E)return!0}return!1};for(let L of e.edges)if(!M[L.id])for(let C of L.routes){let E=d.get(C);for(let T=0;T<2;T++){let _=e.nodes[T===0?L.a:L.b];!A[(2*L.id+T)*g+E]&&U(_,L.id,C)&&N.set(C,(N.get(C)??0)+1)}}let V=gn(e,[...e.routes.keys()].sort((L,C)=>(N.get(C)??0)-(N.get(L)??0)||(L<C?-1:L>C?1:0)));return{graph:e,zoom:n,scale:a,spacing:u,width:l,casing:s,smooth:o,openFolds:i,laneStyle:r,looks:new Map,routeIndex:d,routeCount:g,offsets:p,simplePx:h,edgeLen:f,dirA:b,dirB:m,short:M,junctions:w,groups:new Array(w.length),tails:new Array(w.length),continues:A,frontA:F,frontB:I,mergedEdges:R,drawOrder:V,preparedPx:new Array(c),lanes:new Array(c*g),lanePaths:new Array(c*g),connPaths:new Map,phased:new Set}}function pn(e,n){for(let t of e.edges)if(n[t])return!0;return!1}function Te(e,n){let t=e.groups[n];if(t)return{groups:t,tails:e.tails[n]};let o=e.junctions[n],i=new Map,r=[];for(let s of o.transitions){let a=o.ports[s.u],c=o.ports[s.v],d=re(e,a.edge,s.route,a.end==="b"),g=re(e,c.edge,s.route,c.end==="a"),p=`${a.edge}:${c.edge}:${(d-g).toFixed(3)}`,h=i.get(p);h||(h={edgeU:a.edge,edgeV:c.edge,members:[]},i.set(p,h),r.push(h)),h.members.push({route:s.route,key:fe(e,s.route,a.edge,a.end,c.edge,c.end),pu:a,pv:c,lateral:d,lateralOut:g,via:s.via})}let u=new Map;for(let s of r)for(let a of s.members)for(let c of a.via){let d=`${a.route}|${c.edge}`,g=u.get(d);g?g.push(a):u.set(d,[a])}for(let s of u.values())if(s.length>1)for(let a of s)a.forked=!0;let l=[];for(let s of o.tails){let a=o.ports[s.port],c=s.edges[s.side==="end"?s.edges.length-1:0],d=s.edges[s.side==="end"?0:s.edges.length-1],g={tail:s,port:a,mode:0,key:s.side==="end"?fe(e,s.route,a.edge,a.end,c.edge,c.forward?"b":"a"):fe(e,s.route,c.edge,c.forward?"a":"b",a.edge,a.end)};l.push(g);let p=s.side==="end"?a.edge:d.edge,h=s.side==="end"?d.edge:a.edge;r.push({edgeU:p,edgeV:h,members:[{route:s.route,pu:a,pv:a,lateral:0,lateralOut:0,via:[],plan:g,key:s.side==="end"?fe(e,s.route,p,a.end,h,d.forward?"a":"b"):fe(e,s.route,p,d.forward?"b":"a",h,a.end)}]})}return e.groups[n]=r,e.tails[n]=l,{groups:r,tails:l}}function se(e,n,t){return n*e.routeCount+e.routeIndex.get(t)}function fe(e,n,t,o,i,r){let u=2*e.graph.edges.length;return((t*2+(o==="b"?1:0))*u+i*2+(r==="b"?1:0))*e.routeCount+e.routeIndex.get(n)}function re(e,n,t,o){let i=e.offsets[se(e,n,t)];return o?i:-i}function xe(e,n,t,o){return e.continues[(2*n+t)*e.routeCount+e.routeIndex.get(o)]!==0}function Pn(e,n,t){let o=e.graph.routes.get(t),i=e.laneStyle?e.laneStyle(n,t):null,r=i?.color||o?.color||"#888",u=i?.dash??o?.dash,l=i?.dashColor??o?.dashColor,s=i?.dashCap??o?.dashCap,a=`${r}|${u?u[0]+","+u[1]:""}|${l??""}|${s??""}`,c=e.looks.get(a);return c||e.looks.set(a,c={color:r,dash:u,dashColor:l,dashCap:s}),c}function kn(e,n){let t=e.graph.edges[n];return((t.routes.length-1)/2+Math.abs(t.baseline??0))*e.spacing}function kt(e,n){let t=0;for(let o of n)t=Math.max(t,kn(e,o));return Math.max(yt,Mn*t)}function _e(e,n,t){return pe(Fe(n,kt(e,t),3,Mt,wn*e.spacing),yn)}function q(e,n){let t=e.preparedPx[n];if(!t){let o=e.simplePx[n];t=e.smooth?_e(e,o,[n]):o;let i=e.graph.edges[n];if(e.openFolds&&i.routes.length>1&&!e.short[n]){let r=kn(e,n);t=fn(t,2*r+e.width+2*e.casing,e.frontA[n]+e.spacing,e.frontB[n]+e.spacing)}e.preparedPx[n]=t}return t}function oe(e,n,t){let o=q(e,n);return t?o:W(o)}function ce(e,n,t){let o=se(e,n,t),i=e.lanes[o];if(i!==void 0)return i;let r=e.graph,u=r.edges[n],l=q(e,n),s;if(e.short[n])s=K(l,e.offsets[o]);else{let a=xe(e,n,0,t)?e.frontA[n]:0,c=xe(e,n,1,t)?e.frontB[n]:0,d=a>0||c>0?ue(l,a,c):l;s=u.order.length===1&&e.offsets[o]!==0?Lt(d,e.offsets[o],xe(e,n,0,t),xe(e,n,1,t),gt*e.spacing,e.spacing):K(d,e.offsets[o]);let g=r.nodes[u.a],p=r.nodes[u.b];a>0&&(s.anchors[0]=g.x*e.scale,s.anchors[1]=g.y*e.scale),c>0&&(s.anchors[s.anchors.length-2]=p.x*e.scale,s.anchors[s.anchors.length-1]=p.y*e.scale)}return e.lanes[o]=s,s}function Lt(e,n,t,o,i,r){if(!t&&!o)return K(e,0);let u=t?r:0,l=o?r:0,s=H(e)-u-l;if(s<1)return K(e,n);let a=ue(e,u,l,0),c=o?i:Math.min(i,s),d=t?i:Math.min(i,s),g=M=>1-M*M*(3-2*M),p=M=>n*Math.max(t?g(Math.min(1,M/c)):0,o?g(Math.min(1,(s-M)/d)):0),h=(M,P,x)=>{let w=Math.max(1,Math.ceil((x-P)/i*mt)),v=[];for(let O=1;O<w;O++)v.push(O/w,p(P+(x-P)*O/w));return ae(M,p(P),p(x),4,v)},f=[];u>0&&f.push(K(ge(e,u),n));let b=t?c:0,m=o?d:0;b+m>s-1?f.push(h(a,0,s)):(b>0&&f.push(h(ge(a,b),0,b)),f.push(K(ue(a,b,m,0),0)),m>0&&f.push(h(le(a,m),s-m,s))),l>0&&f.push(K(le(e,l),n));let k=[],y=[];return f.forEach((M,P)=>{for(let x=P>0?2:0;x<M.points.length;x++)k.push(M.points[x]),y.push(M.anchors[x])}),{points:k,anchors:y}}function ve(e,n,t){let o=se(e,n,t),i=e.lanePaths[o];if(i!==void 0)return i;let r=ce(e,n,t);if(r.points.length<4)return e.lanePaths[o]=null,null;let u=e.graph.edges[n],l={route:t,look:Pn(e,u,t),coords:r.points,anchors:r.anchors,kind:"lane",travel:Cn(u.direction.get(t)),startDistance:0,edge:n};return e.lanePaths[o]=l,l}function Ne(e,n,t){let o=[];for(let i of n)for(let r=0;r<i.length;r+=2)o.length&&Math.abs(o[o.length-2]-i[r])<1e-6&&Math.abs(o[o.length-1]-i[r+1])<1e-6||o.push(i[r],i[r+1]);return e.smooth?_e(e,o,t):o}function Ve(e,n){if(n.mode)return;n.mode=2;let t=n.tail,o=n.port,i=ce(e,o.edge,t.route),r=t.edges.map(y=>oe(e,y.edge,y.forward)),u=t.edges[t.side==="end"?t.edges.length-1:0],l=re(e,u.edge,t.route,u.forward),s=re(e,o.edge,t.route,t.side==="end"?o.end==="b":o.end==="a"),a=q(e,o.edge),c=t.side==="end"?le(o.end==="b"?a:W(a),o.end==="b"?e.frontB[o.edge]:e.frontA[o.edge]):ge(o.end==="a"?a:W(a),o.end==="a"?e.frontA[o.edge]:e.frontB[o.edge]),d=[o.edge,...t.edges.map(y=>y.edge)],g=t.side==="end"?Ne(e,[c,...r],d):Ne(e,[...r,c],d),p=t.side==="end"?ae(g,s,l):ae(g,l,s);if(p.points.length<4)return;let h=t.side==="end"?o.end==="b"?i.points:W(i.points):o.end==="a"?i.points:W(i.points);t.side==="end"?(p.points[0]=h[h.length-2],p.points[1]=h[h.length-1]):(p.points[p.points.length-2]=h[0],p.points[p.points.length-1]=h[1]);let{points:f,anchors:b}=de(p.points,p.anchors,xn*e.spacing);if(f.length<4)return;let m=t.side==="end"?[o.edge,u.edge]:[u.edge,o.edge],k=t.side==="end"?[{edge:o.edge,forward:o.end==="b"},...t.edges]:[...t.edges,{edge:o.edge,forward:o.end==="a"}];n.slide=Pe(e,t.route,f,b,k,o.node,m,!0),e.connPaths.set(n.key,n.slide),n.mode=1}function Ln(e,n){if(n.paths)return n.paths;let t=e.graph,o=n.steps[0],i=n.steps[n.steps.length-1],r=Ne(e,n.steps.map(c=>oe(e,c.edge,c.forward)),n.steps.map(c=>c.edge)),u=re(e,o.edge,n.route,o.forward),l=re(e,i.edge,n.route,i.forward),s=ae(r,u,l);if(s.points.length>=4){let c=t.edges[o.edge];return n.paths=Pe(e,n.route,s.points,s.anchors,n.steps,o.forward?c.a:c.b,[o.edge,i.edge],!0)}let a=[];for(let c of n.steps){let d=ve(e,c.edge,n.route);d&&a.push(d)}return n.paths=a}function St(e,n){let t=e.graph,o=new Map;for(let y of t.chains.get(n)??[])for(let M of y.steps)o.set(M.edge,M.forward);let i=y=>o.get(y)===!1?"a":"b",r=[],u=new Map,l=[],s=(y,M)=>{let P=y?Array.isArray(y)?y:[y]:[];if(P.length&&!u.has(P[0])){for(let x of P)u.set(x,r.length);r.push(P),l.push(M)}},a=y=>s(ve(e,y,n),o.get(y)!==!1);for(let y of t.edges)!e.short[y.id]&&y.routes.includes(n)&&a(y.id);for(let y=0;y<e.junctions.length;y++){let{groups:M,tails:P}=Te(e,y);for(let x of P)if(x.tail.route===n)if(Ve(e,x),x.mode===1)s(x.slide,!0);else for(let{edge:w}of x.tail.edges)a(w);for(let x of M)if(x.members.some(w=>w.route===n)){Sn(e,x);for(let w of x.members){if(w.route!==n||w.plan?.mode===1)continue;let v=!!w.plan||w.pu.end===i(w.pu.edge);s(e.connPaths.get(w.key),v)}}for(let x of e.junctions[y].islands){if(x.route!==n)continue;let w=Ln(e,x);if(w[0]?.kind==="connector")s(w,!0);else for(let v of w)s(v,!0)}}if(!r.length)return;let c=r.length,d=new Map,g=new Array(2*c);for(let y=0;y<c;y++){let M=r[y][0].coords,P=r[y][r[y].length-1].coords;for(let x=0;x<2;x++){let w=x?P[P.length-2]:M[0],v=x?P[P.length-1]:M[1],O=d.get(w);O||d.set(w,O=new Map);let A=O.get(v);A||O.set(v,A=[]),A.push(y*2+x),g[y*2+x]=A}}let p=new Float64Array(c).fill(-1),h=new Float64Array(2*c),f=new Uint8Array(c),b=(y,M,P)=>{let x=p[y];if(x<0){x=0;for(let v of r[y])x+=H(v.coords);p[y]=x}let w=l[y]?M?P-x:P:M?P+x:P;h[y*2]=w,h[y*2+1]=l[y]?M?P:P+x:M?P:P-x,f[y]=1},m=0;e:for(let y of t.chains.get(n)??[])for(let M of y.steps){let P=e.lanePaths[se(e,M.edge,n)];if(P){m=u.get(P);break e}}let k=[];for(let y=-1;y<c;y++){if(y>=0){if(f[y])continue;m=y}b(m,0,0),k.length=0,k.push(m);for(let P=0;P<k.length;P++){let x=k[P];for(let w=0;w<2;w++){let v=h[x*2+w];for(let O of g[x*2+w]){let A=O>>1;f[A]||(b(A,O&1,v),k.push(A))}}}let M=0;for(let P of k)M=Math.min(M,h[P*2],h[P*2+1]);for(let P of k){let x=h[P*2]-M;for(let w of r[P]){w.startDistance=l[P]?x:-x;let v=r[P].length>1?H(w.coords):0;x=l[P]?x+v:x-v}}}}function Sn(e,n){let t=n.members[0].plan;if(t&&(Ve(e,t),t.mode===1))return;let o=!1;for(let a of n.members)e.connPaths.has(a.key)||(o=!0);if(!o)return;let i=e.graph,r=[],u=new Map,l=!1;for(let a of n.members){if(e.connPaths.set(a.key,null),a.plan)continue;let c=ce(e,a.pu.edge,a.route),d=ce(e,a.pv.edge,a.route),g=a.pu.end==="b"?c.points:W(c.points),p=a.pv.end==="a"?d.points:W(d.points),h=a.via.length?null:Ue(g,p,e.spacing,Ae(e,a.pu.edge,a.pu.end),Ae(e,a.pv.edge,a.pv.end,!0));u.set(a,{from:g,to:p,made:h}),h&&h.coords.length>=4&&It(e,a,h.coords)&&(l=!0)}for(let a of n.members){if(a.plan){Ot(e,a,r);continue}let{from:c,to:d,made:g}=u.get(a);if((a.via.length||l)&&Et(e,a,c,d))continue;let p=g??Ue(c,d,e.spacing,Ae(e,a.pu.edge,a.pu.end),Ae(e,a.pv.edge,a.pv.end,!0));p.coords.length<4||r.push({member:a,lateral:a.lateral,own:p.coords,coords:p.coords,corner:p.corner})}let s=r.filter(a=>!a.corner);s.length>1&&Nt(s,e.spacing);for(let a of r){let c=a.member,d=a.coords,g=i.nodes[c.pu.node],p=new Array(d.length);for(let h=0;h<d.length;h+=2)p[h]=g.x*e.scale,p[h+1]=g.y*e.scale;e.connPaths.set(c.key,Pe(e,c.route,d,p,In(c),c.pu.node,[n.edgeU,n.edgeV],!1))}}function Ae(e,n,t,o=!1){let i=t==="b"?e.frontB[n]:e.frontA[n];if(i<=0)return null;let r=q(e,n),u=ue(t==="b"?r:W(r),0,i);if(u.length<4)return null;let l=me(u,e.spacing/2);return l[0]===0&&l[1]===0?null:o?[-l[0],-l[1]]:l}function It(e,n,t){let o=q(e,n.pu.edge),i=q(e,n.pv.edge),r=le(n.pu.end==="b"?o:W(o),n.pu.end==="b"?e.frontB[n.pu.edge]:e.frontA[n.pu.edge]).concat(ge(n.pv.end==="a"?i:W(i),n.pv.end==="a"?e.frontA[n.pv.edge]:e.frontB[n.pv.edge])),u=Math.max(Math.abs(n.lateral),Math.abs(n.lateralOut))+At*e.spacing,l=e.graph;if(l.edges[n.pu.edge].order.length===1&&l.edges[n.pv.edge].order.length===1){let s=l.nodes[n.pu.node],a=Math.max(Math.abs(n.lateral),Math.abs(n.lateralOut))+e.width/2+e.casing;if(Ct(s.x*e.scale,s.y*e.scale,t)>a)return!0}for(let s=0;s<t.length;s+=2){let a=!1;for(let c=2;c<r.length&&!a;c+=2){let d=r[c-2],g=r[c-1],p=r[c]-d,h=r[c+1]-g,f=p*p+h*h,b=f?Math.max(0,Math.min(1,((t[s]-d)*p+(t[s+1]-g)*h)/f)):0;a=Math.hypot(t[s]-d-b*p,t[s+1]-g-b*h)<=u}if(!a)return!0}return!1}function Ct(e,n,t){let o=1/0;for(let i=2;i<t.length;i+=2){let r=t[i-2],u=t[i-1],l=t[i]-r,s=t[i+1]-u,a=l*l+s*s,c=a?Math.max(0,Math.min(1,((e-r)*l+(n-u)*s)/a)):0;o=Math.min(o,Math.hypot(e-r-c*l,n-u-c*s))}return o}function Ot(e,n,t){let o=n.plan.tail,i=n.pu,r=o.edges[o.side==="end"?0:o.edges.length-1],u=ce(e,i.edge,o.route),l=ce(e,r.edge,o.route),s=r.forward?l.points:W(l.points),a=o.side==="end"?i.end==="b"?u.points:W(u.points):s,c=o.side==="end"?s:i.end==="a"?u.points:W(u.points),d=Ue(a,c,e.spacing);d.coords.length<4||t.push({member:n,lateral:0,own:d.coords,coords:d.coords,corner:d.corner})}function Et(e,n,t,o){let i=[],r=0,u=f=>{for(let b=0;b<f.length;b+=2){let m=i.length;m&&Math.abs(i[m-2]-f[b])<1e-6&&Math.abs(i[m-1]-f[b+1])<1e-6||(m&&(r+=Math.hypot(f[b]-i[m-2],f[b+1]-i[m-1])),i.push(f[b],f[b+1]))}},l=q(e,n.pu.edge),s=q(e,n.pv.edge),a=[];u(le(n.pu.end==="b"?l:W(l),n.pu.end==="b"?e.frontB[n.pu.edge]:e.frontA[n.pu.edge]));for(let f of n.via){let b=r;u(oe(e,f.edge,f.forward)),a.push((b+r)/2)}u(ge(n.pv.end==="a"?s:W(s),n.pv.end==="a"?e.frontA[n.pv.edge]:e.frontB[n.pv.edge]));let c=[];if(n.forked){let f=r;n.via.forEach((y,M)=>c.push(a[M]/f,re(e,y.edge,n.route,y.forward)));let b=y=>n.lateral+(n.lateralOut-n.lateral)*y,m=y=>{let M=0,P=n.lateral,x=0;for(let w=0;w<=c.length;w+=2){let v=w<c.length?c[w]:1,O=w<c.length?b(v)+(c[w+1]-b(v))*y:n.lateralOut;v>M&&(x=Math.max(x,Math.abs(O-P)/((v-M)*f))),M=v,P=O}return x},k=1;if(m(1)>mn){let y=0,M=1;for(let P=0;P<12;P++){let x=(y+M)/2;m(x)>mn?M=x:y=x}k=y}for(let y=0;y<c.length;y+=2)c[y+1]=b(c[y])+(c[y+1]-b(c[y]))*k}let d=e.smooth?_e(e,i,[n.pu.edge,n.pv.edge,...n.via.map(f=>f.edge)]):i,g=ae(d,n.lateral,n.lateralOut,4,c);if(g.points.length<4)return!1;g.points[0]=t[t.length-2],g.points[1]=t[t.length-1],g.points[g.points.length-2]=o[0],g.points[g.points.length-1]=o[1];let{points:p,anchors:h}=de(g.points,g.anchors,xn*e.spacing);return p.length<4?!1:(e.connPaths.set(n.key,Pe(e,n.route,p,h,In(n),n.pu.node,[n.pu.edge,n.pv.edge],!0)),!0)}function In(e){let n=e.plan?.tail;if(n){let t=e.pu,o=n.edges[n.side==="end"?0:n.edges.length-1];return n.side==="end"?[{edge:t.edge,forward:t.end==="b"},o]:[o,{edge:t.edge,forward:t.end==="a"}]}return[{edge:e.pu.edge,forward:e.pu.end==="b"},...e.via,{edge:e.pv.edge,forward:e.pv.end==="a"}]}function Pe(e,n,t,o,i,r,u,l){let s=e.graph,a=[],c=t,d=o;for(let h=0;h+1<i.length;h++){let[f,b]=Ft(e,c,d,i[h],i[h+1],l),m,k;if(b<=0||b>=1){let y=b<=0?f:f+2;m=c.slice(0,y+2),k=d.slice(0,y+2),c=c.slice(y),d=d.slice(y)}else{let y=c[f]+(c[f+2]-c[f])*b,M=c[f+1]+(c[f+3]-c[f+1])*b,P=d[f]+(d[f+2]-d[f])*b,x=d[f+1]+(d[f+3]-d[f+1])*b;m=c.slice(0,f+2).concat(y,M),k=d.slice(0,f+2).concat(P,x),c=[y,M,...c.slice(f+2)],d=[P,x,...d.slice(f+2)]}a.push({c:m,a:k,step:i[h],length:H(m)})}a.push({c,a:d,step:i[i.length-1],length:H(c)});let g=[],p=[];for(let h of a){if(h.length<dt){p.push(h);continue}for(let f of p.reverse())h.c=f.c.concat(h.c.slice(2)),h.a=f.a.concat(h.a.slice(2));p=[],g.push(h)}if(g.length){let h=g[g.length-1];for(let f of p)h.c=h.c.concat(f.c.slice(2)),h.a=h.a.concat(f.a.slice(2))}else{let h=a.reduce((f,b)=>b.length>f.length?b:f);g.push({...h,c:t,a:o})}return g.map(({c:h,a:f,step:b})=>{let m=s.edges[b.edge];return{route:n,look:Pn(e,m,n),coords:h,anchors:f,kind:"connector",travel:Cn(m.direction.get(n))*(b.forward?1:-1),startDistance:0,edge:b.edge,node:r,between:u}})}function bn(e,n,t){let o=1/0,i=0;for(let r=0;r+3<e.length;r+=2){let u=e[r],l=e[r+1],s=e[r+2]-u,a=e[r+3]-l,c=s*s+a*a;if(!c)continue;let d=Math.max(0,Math.min(1,((n-u)*s+(t-l)*a)/c)),g=Math.hypot(n-u-d*s,t-l-d*a);g<o&&(o=g,i=(s*(t-l)-a*(n-u))/Math.sqrt(c))}return i}function Ft(e,n,t,o,i,r){let u=e.graph.edges[o.edge],l=e.graph.nodes[o.forward?u.b:u.a],s=l.x*e.scale,a=l.y*e.scale,c=me(oe(e,o.edge,o.forward),e.spacing),d=Oe(oe(e,i.edge,i.forward),e.spacing),g=c[0]+d[0],p=c[1]+d[1],h=Math.hypot(g,p),f=r?t:n,b=M=>{let P=1/0,x=0,w=0;for(let v=0;v+3<f.length;v+=2){let O=(f[v]-s)*g+(f[v+1]-a)*p-M,A=(f[v+2]-s)*g+(f[v+3]-a)*p-M;if(O<0==A<0)continue;let F=O/(O-A),I=Math.hypot(n[v]+(n[v+2]-n[v])*F-s,n[v+1]+(n[v+3]-n[v+1])*F-a);I<P&&([P,x,w]=[I,v,F])}return P<1/0?[x,w]:null};if(h>1e-6){let M=0;if(!r){let x=n.length,w=bn(oe(e,o.edge,o.forward),n[0],n[1]),v=bn(oe(e,i.edge,i.forward),n[x-2],n[x-1]),O=c[0]*d[1]-c[1]*d[0],A=c[0]*d[0]+c[1]*d[1],F=w-v;Math.abs(O)>1e-9&&(M=Math.max(-Math.abs(F)*h,Math.min(Math.abs(F)*h,F*(1+A)/O)))}let P=b(M)??(M?b(0):null);if(P)return P}let m=1/0,k=0,y=0;for(let M=0;M+3<n.length;M+=2){let P=n[M+2]-n[M],x=n[M+3]-n[M+1],w=P*P+x*x,v=w?Math.max(0,Math.min(1,((s-n[M])*P+(a-n[M+1])*x)/w)):0,O=Math.hypot(n[M]+P*v-s,n[M+1]+x*v-a);O<m&&([m,k,y]=[O,M,v])}return[k,y]}function Rt(e,n,t,o,i,r){let u=e.nodes.length,l=new Int32Array(u);for(let w=0;w<u;w++)l[w]=w;let s=w=>{for(;l[w]!==w;)w=l[w]=l[l[w]];return w};for(let w of e.edges)n[w.id]&&(l[s(w.a)]=s(w.b));let a=new Map,c=new Array(u),d=new Int32Array(2*e.edges.length).fill(-1);for(let w=0;w<u;w++){let v=s(w),O=a.get(v);O||a.set(v,O={ports:[],transitions:[],tails:[],islands:[],edges:[]}),c[w]=O;for(let A of e.nodes[w].ports)O.edges.push(A.edge),!n[A.edge]&&(d[A.edge*2+(A.end==="a"?0:1)]=O.ports.length,O.ports.push({edge:A.edge,end:A.end,node:w,dir:A.end==="a"?o[A.edge]:i[A.edge],hw:r(e.edges[A.edge])}))}let g=[],p=new Uint8Array(e.edges.length),h=(w,v,O)=>{let A=[],F=(I,R)=>{g.push({edge:I,entryNode:R}),p[I]++;let N=e.edges[I],U=N.a===R?N.b:N.a,V=e.nodes[U],S=!1,L=null;for(let C of V.transitions){if(C.route!==w||C.from<0||C.to<0)continue;let E=V.ports[C.from],T=V.ports[C.to],_=E.edge===I&&T.edge!==I?T:T.edge===I&&E.edge!==I?E:null;_&&(n[_.edge]&&p[_.edge]||(S=!0,n[_.edge]?F(_.edge,U):A.push({edge:_.edge,end:_.end,node:U,walked:L??(L=g.slice())})))}S||A.push({edge:-1,end:"a",node:U,walked:L??(L=g.slice())}),p[I]--,g.pop()};return F(v,O),A},f=new Map,b=new Set;for(let w of e.nodes){let v=c[w.id],O=s(w.id);for(let A of w.transitions){if(A.from<0||A.to<0)continue;let F=w.ports[A.from],I=w.ports[A.to];if(!n[F.edge]&&!n[I.edge]){let V=d[F.edge*2+(F.end==="a"?0:1)],S=d[I.edge*2+(I.end==="a"?0:1)];V>=0&&S>=0&&v.transitions.push({route:A.route,u:V,v:S,via:[]});continue}if(n[F.edge]&&n[I.edge])continue;let R=!n[F.edge],N=R?F:I,U=d[N.edge*2+(N.end==="a"?0:1)];if(!(U<0))for(let V of h(A.route,(R?I:F).edge,w.id)){let S=V.walked.map(G=>({edge:G.edge,forward:e.edges[G.edge].a===G.entryNode})),L=R?S:S.reverse().map(G=>({edge:G.edge,forward:!G.forward}));if(V.edge<0){let G=`${O}|${A.route}|${U}|${L.map(z=>z.edge).join(",")}`;if(b.has(G))continue;b.add(G),v.tails.push({route:A.route,port:U,side:R?"end":"start",edges:L});continue}let C=d[V.edge*2+(V.end==="a"?0:1)];if(C<0||c[V.node]!==v)continue;let E=`${O}|${A.route}|${Math.min(U,C)}|${Math.max(U,C)}`,T=L.reduce((G,z)=>G+t[z.edge],0),_=R?{route:A.route,u:U,v:C,via:L}:{route:A.route,u:C,v:U,via:L},B=f.get(E);if(B){T<B.length&&(v.transitions[B.index]=_,B.length=T);continue}f.set(E,{index:v.transitions.length,length:T}),v.transitions.push(_)}}}let m=new Map,k=w=>{let v=m.get(w);return v===void 0&&m.set(w,v=m.size),v};for(let w of e.routes.keys())k(w);for(let w of e.chains.keys())k(w);for(let w of a.values()){for(let v of w.transitions)k(v.route);for(let v of w.tails)k(v.route)}let y=m.size,M=new Uint8Array(e.edges.length*y);for(let w of a.values()){for(let v of w.transitions){let O=m.get(v.route);for(let A of v.via)M[A.edge*y+O]=1}for(let v of w.tails){let O=m.get(v.route);for(let A of v.edges)M[A.edge*y+O]=1}}let P=(w,v)=>w.forward===v?e.edges[w.edge].a:e.edges[w.edge].b,x=(w,v,O,A)=>{let F=new Set,I=e.nodes[O];for(let R of I.transitions){if(R.route!==v||R.from<0||R.to<0)continue;let N=I.ports[R.from],U=I.ports[R.to];N.edge===A&&n[U.edge]&&F.add(U.edge),U.edge===A&&n[N.edge]&&F.add(N.edge)}if(!F.size)return-1;for(let R of I.transitions){if(R.route!==v||R.from<0||R.to<0)continue;let N=I.ports[R.from],U=I.ports[R.to],V=F.has(U.edge)&&!n[N.edge]?N:F.has(N.edge)&&!n[U.edge]?U:null;if(V&&V.edge!==A)return d[V.edge*2+(V.end==="a"?0:1)]}return-1};for(let[w,v]of e.chains){let O=m.get(w);for(let A of v){let F=A.steps;for(let I=0;I<F.length;I++){if(!n[F[I].edge]||M[F[I].edge*y+O])continue;let R=I;for(;R<F.length&&n[F[R].edge]&&!M[F[R].edge*y+O];)R++;let N=F.slice(I,R).map(E=>({edge:E.edge,forward:E.forward}));for(let E of N)M[E.edge*y+O]=1;let U=N[0],V=N[N.length-1],S=c[P(U,!0)],L=x(S,w,P(U,!0),U.edge),C=x(S,w,P(V,!1),V.edge);L>=0&&C>=0&&L!==C?S.transitions.push({route:w,u:L,v:C,via:N}):L>=0?S.tails.push({route:w,port:L,side:"end",edges:N}):C>=0?S.tails.push({route:w,port:C,side:"start",edges:N}):S.islands.push({route:w,steps:N}),I=R-1}}}return[...a.values()]}function Tt(e,n,t,o,i,r){let u=new Float64Array(2*e.edges.length),l=new Float64Array(2*e.edges.length),s=new Uint8Array(2*e.edges.length*r),a=(c,d)=>{s[(2*c.edge+(c.end==="a"?0:1))*r+i.get(d)]=1};for(let c of n){let d=c.ports,g=new Float64Array(d.length),p=new Uint8Array(d.length);for(let f of c.transitions)p[f.u]=1,p[f.v]=1,a(d[f.u],f.route),a(d[f.v],f.route);for(let f of c.tails)p[f.port]=1,a(d[f.port],f.route);for(let f=0;f<d.length;f++)if(p[f])for(let b=0;b<d.length;b++){if(b===f||!p[b])continue;let m=d[f].dir[0]*d[b].dir[0]+d[f].dir[1]*d[b].dir[1],k=Math.sqrt(Math.max(0,1-m*m)),y;k<.001?y=m>0?6*o:0:y=(d[b].hw+d[f].hw*m)/k,y=Math.max(0,y),y>0&&(y+=ut*o),g[f]=Math.max(g[f],Math.min(y,8*o))}let h=new Float64Array(d.length);for(let f of c.transitions){let b=d[f.u],m=d[f.v],k=t(e.edges[b.edge],f.route,b.end==="b"),y=t(e.edges[m.edge],f.route,m.end==="a"),M=Math.abs(k-y);if(M<1e-6)continue;let P=Math.max(2.5*M,3*o);h[f.u]=Math.max(h[f.u],P/2),h[f.v]=Math.max(h[f.v],P/2)}for(let f=0;f<d.length;f++)g[f]=Math.max(g[f],h[f]);d.forEach((f,b)=>l[2*f.edge+(f.end==="a"?0:1)]=h[b]);for(let f of c.tails){let b=d[f.port],m=f.edges[f.side==="end"?0:f.edges.length-1],k=t(e.edges[b.edge],f.route,b.end==="b"),y=t(e.edges[m.edge],f.route,m.forward),M=Math.abs(k-y);M<1e-6||(g[f.port]=Math.max(g[f.port],Math.max(2.5*M,3*o)/2))}d.forEach((f,b)=>u[2*f.edge+(f.end==="a"?0:1)]=g[b])}return{need:u,change:l,continues:s}}function le(e,n){let t=e.length/2;if(n<=0||t<2)return[e[e.length-2],e[e.length-1]];let o=[],i=n;for(let r=t-1;r>0;r--){let u=e[r*2-2],l=e[r*2-1],s=e[r*2],a=e[r*2+1],c=Math.hypot(s-u,a-l);if(o.unshift(s,a),c>=i){let d=1-i/c;return o.unshift(u+(s-u)*d,l+(a-l)*d),o}i-=c}return o.unshift(e[0],e[1]),o}function ge(e,n){return W(le(W(e),n))}function Cn(e){return e===1?1:e===-1?-1:0}function Nt(e,n){let t=e[0],o=H(t.own);for(let r of e){let u=H(r.own);u>o&&(t=r,o=u)}if(t.own.length<=4||o<ht*n)return;let i=Ut(t.own);for(let r of e){if(r===t)continue;let u=r.lateral-t.lateral,l=o+u*i;if(l<.25*o)continue;let s=qe(t.own,u);if(s.length<4)continue;let a=H(s)/l;if(a>1.1||a<.9)continue;let c=Math.hypot(s[0]-r.own[0],s[1]-r.own[1]),d=Math.hypot(s[s.length-2]-r.own[r.own.length-2],s[s.length-1]-r.own[r.own.length-1]);c>n/2||d>n/2||(s[0]=r.own[0],s[1]=r.own[1],s[s.length-2]=r.own[r.own.length-2],s[s.length-1]=r.own[r.own.length-1],r.coords=s)}}function Ut(e){let n=0;for(let t=4;t<e.length;t+=2){let o=e[t-2]-e[t-4],i=e[t-1]-e[t-3],r=e[t]-e[t-2],u=e[t+1]-e[t-1];n+=Math.atan2(o*u-i*r,o*r+i*u)}return n}function Ue(e,n,t,o=null,i=null){let r=[e[e.length-2],e[e.length-1]],u=[n[0],n[1]],l=o??me(e,t/2),s=i??Oe(n,t/2),a=[-s[0],-s[1]],c=Math.hypot(u[0]-r[0],u[1]-r[1]);if(c<1e-6)return{coords:[],corner:!1};if(Math.abs((u[0]-r[0])*l[1]-(u[1]-r[1])*l[0])<.05&&l[0]*s[0]+l[1]*s[1]>.9999)return{coords:[r[0],r[1],u[0],u[1]],corner:!1};let g=_t(r,l,u,a,c,t);if(g)return{coords:g,corner:!0};let p=Math.max(4,Math.min(32,Math.round(c/Math.max(2,t/3)))),h=Ee(r,l,u,a,p),f=(u[0]-r[0])*l[0]+(u[1]-r[1])*l[1],b=(r[0]-u[0])*a[0]+(r[1]-u[1])*a[1];if(f<0||b<0)for(let m=.5;m>.1&&Qe(h);m/=2)h=Ee(r,l,u,a,p,m);return{coords:h,corner:!1}}function _t(e,n,t,o,i,r){let u=be(e[0],e[1],e[0]+n[0],e[1]+n[1],t[0],t[1],t[0]+o[0],t[1]+o[1]);if(!u)return null;let l=(u[0]-e[0])*n[0]+(u[1]-e[1])*n[1],s=(u[0]-t[0])*o[0]+(u[1]-t[1])*o[1];if(l<=.01||s<=.01||l+s>xt*i||Math.acos(Math.max(-1,Math.min(1,-(n[0]*o[0]+n[1]*o[1]))))*180/Math.PI<wt)return null;let c=Math.min(wn*r,.45*l,.45*s),d=[u[0]-n[0]*c,u[1]-n[1]*c],g=[u[0]-o[0]*c,u[1]-o[1]*c],p=[e[0],e[1],d[0],d[1]],h=8;for(let f=1;f<h;f++){let b=f/h,m=1-b;p.push(m*m*d[0]+2*m*b*u[0]+b*b*g[0],m*m*d[1]+2*m*b*u[1]+b*b*g[1])}return p.push(g[0],g[1],t[0],t[1]),p}function On(e,n,t,o){if(t<=0)return;let i=e[e.length-1];i&&i[2]===o&&i[0]+i[1]===n?i[1]+=t:e.push([n,t,o])}var Vt=2,Bt=15,Q=9,ke=class{constructor(n,t){D(this,"v");D(this,"c");D(this,"i");D(this,"nv",0);D(this,"ni",0);this.v=new Float32Array(n*Q),this.c=new Uint8Array(n*4),this.i=new Uint32Array(t)}reset(){this.nv=0,this.ni=0}reserve(n,t){for(;(this.nv+n)*Q>this.v.length;)this.growV();for(;this.ni+t>this.i.length;)this.growI()}growV(){let n=new Float32Array(this.v.length*2);n.set(this.v),this.v=n;let t=new Uint8Array(this.c.length*2);t.set(this.c),this.c=t}growI(){let n=new Uint32Array(this.i.length*2);n.set(this.i),this.i=n}vertex(n,t,o,i,r,u,l,s,a,c){(this.nv+1)*Q>this.v.length&&this.growV();let d=this.nv*Q;this.v[d]=n,this.v[d+1]=t,this.v[d+2]=o,this.v[d+3]=i,this.v[d+4]=r,this.v[d+5]=u,this.v[d+6]=l,this.v[d+7]=s,this.v[d+8]=a;let g=this.nv*4;return this.c[g]=c[0],this.c[g+1]=c[1],this.c[g+2]=c[2],this.c[g+3]=c[3],this.nv++}tri(n,t,o){this.ni+3>this.i.length&&this.growI(),this.i[this.ni++]=n,this.i[this.ni++]=t,this.i[this.ni++]=o}quad(n,t,o,i){this.tri(n,t,o),this.tri(t,i,o)}};function Gt(e){let n=typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1).getContext("2d",{willReadFrequently:!0}):typeof document<"u"?document.createElement("canvas").getContext("2d",{willReadFrequently:!0}):null;if(!n)return null;n.fillStyle="#000000",n.fillStyle=e;let t=n.fillStyle;if(n.fillStyle="#ffffff",n.fillStyle=e,t!==n.fillStyle||typeof t!="string")return null;if(/^(#|rgba?\\()/i.test(t))return t;n.clearRect(0,0,1,1),n.fillRect(0,0,1,1);let[o,i,r,u]=n.getImageData(0,0,1,1).data;return`rgba(${o}, ${i}, ${r}, ${u/255})`}function Be(e,n=!1){let t=new Uint8Array([136,136,136,255]),o=e.trim(),i=/^#([0-9a-f]{3,8})$/i.exec(o);if(i){let s=i[1];return s.length===3||s.length===4?(t[0]=parseInt(s[0]+s[0],16),t[1]=parseInt(s[1]+s[1],16),t[2]=parseInt(s[2]+s[2],16),t[3]=s.length===4?parseInt(s[3]+s[3],16):255):(s.length===6||s.length===8)&&(t[0]=parseInt(s.slice(0,2),16),t[1]=parseInt(s.slice(2,4),16),t[2]=parseInt(s.slice(4,6),16),t[3]=s.length===8?parseInt(s.slice(6,8),16):255),t}let r={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",yellow:"#ffff00",orange:"#ffa500",purple:"#800080",gray:"#808080",grey:"#808080",silver:"#c0c0c0",navy:"#000080",magenta:"#ff00ff",fuchsia:"#ff00ff",lime:"#00ff00",brown:"#a52a2a",teal:"#008080",maroon:"#800000"};if(r[o.toLowerCase()])return Be(r[o.toLowerCase()]);let u=/^rgba?\\(([^)]+)\\)$/i.exec(o);if(u){let s=u[1].split(/[\\s,/]+/).filter(a=>a.length);for(let a=0;a<3&&a<s.length;a++){let c=s[a].endsWith("%")?parseFloat(s[a])*255/100:parseFloat(s[a]);t[a]=Math.round(Math.max(0,Math.min(255,c||0)))}if(s.length>3){let a=s[3].endsWith("%")?parseFloat(s[3])/100:parseFloat(s[3]);t[3]=Math.round(Math.max(0,Math.min(1,a))*255)}return t}let l=n?null:Gt(o);return l?Be(l,!0):t}var Le=class{constructor(){D(this,"chunks",new WeakMap);D(this,"out",null);D(this,"key","")}clear(){this.chunks=new WeakMap,this.out=null,this.key=""}builderFor(n,t){let o=`${n.scale}|${n.origin[0]}|${n.origin[1]}|${n.unitsPerMercator??1}`;return o!==this.key&&(this.chunks=new WeakMap,this.key=o),this.out||(this.out=new ke(Math.max(64,t*3),Math.max(192,t*9))),this.out.reset(),this.out}emit(n,t,o,i,r=null,u=null){let l=this.chunks.get(t),s=jt(r,u);if(l&&l.startDistance===t.startDistance&&l.color===t.look.color&&l.seams===s){Dt(n,l);return}let a=n.nv,c=n.ni;if(Rn(n,t.coords,t.anchors,o,t.startDistance,i,r,u),l===void 0){this.chunks.set(t,null);return}let d=new Uint32Array(n.ni-c);for(let g=0;g<d.length;g++)d[g]=n.i[c+g]-a;this.chunks.set(t,{vertices:n.v.slice(a*Q,n.nv*Q),colors:n.c.slice(a*4,n.nv*4),indices:d,vertexCount:n.nv-a,startDistance:t.startDistance,color:t.look.color,seams:s})}};function Dt(e,n){e.reserve(n.vertexCount,n.indices.length),e.v.set(n.vertices,e.nv*Q),e.c.set(n.colors,e.nv*4);let t=e.nv;for(let o=0;o<n.indices.length;o++)e.i[e.ni+o]=n.indices[o]+t;e.nv+=n.vertexCount,e.ni+=n.indices.length}function Fn(e,n){let t=0;for(let h of e)t+=h.coords.length;let o=n.cache??null,i=o?o.builderFor(n,t):new ke(Math.max(64,t*3),Math.max(192,t*9)),r=new Map,u=[],l=[],s=[],a=[],c=[],d=[],g=new Map;for(let h of e){let f=g.get(h.route);f||g.set(h.route,f=new Map);let b=f.get(h.look);b||f.set(h.look,b=[]),b.push(h)}let p=n.drawOrder??[...g.keys()];for(let h of p){let f=g.get(h);if(f)for(let[b,m]of f){let k=i.ni,y=r.get(b.color);y||r.set(b.color,y=Be(b.color));let M=[];for(let P=0;P<m.length;P++){let x=m[P],w=i.ni,v=P>0?En(m[P-1],x,!0):null,O=P+1<m.length?En(x,m[P+1],!1):null;o?o.emit(i,x,y,n,v,O):Rn(i,x.coords,x.anchors,y,x.startDistance,n,v,O),On(M,w,i.ni-w,x.edge)}if(i.ni>k){u.push([k,i.ni-k]),l.push(h),s.push(b),c.push(M);let P=i.ni,x=[];if(n.width&&b.dash&&b.dash[0]===0&&b.dash[1]>0)for(let w of m){let v=i.ni;zt(i,w.coords,w.anchors,y,w.startDistance,b.dash[1]*n.width,n),On(x,v,i.ni-v,w.edge)}a.push([P,i.ni-P]),d.push(x)}}}return{vertices:i.v.subarray(0,i.nv*Q),colors:i.c.subarray(0,i.nv*4),indices:i.i.subarray(0,i.ni),vertexCount:i.nv,indexCount:i.ni,groups:u,groupRoutes:l,groupLooks:s,groupDots:a,groupPieces:c,groupDotPieces:d}}function zt(e,n,t,o,i,r,u){let l=n.length/2;if(l<2)return;let s=0;for(let M=1;M<l;M++)s+=Math.hypot(n[M*2]-n[M*2-2],n[M*2+1]-n[M*2-1]);if(s<=0)return;let a=i<0,c=Math.abs(i),d=a?c-s:c,{scale:g,origin:p}=u,h=u.unitsPerMercator??1,f=1,b=0,m=Math.hypot(n[2]-n[0],n[3]-n[1]),k=Math.ceil((d-r/2)/r),y=Math.max(0,Math.ceil((d+s-r/2)/r)-k);for(let M=0;M<y;M++){let P=r/2+(a?k+y-1-M:k+M)*r,x=a?c-P:P-c;for(;f<l-1&&x>b+m;)b+=m,f++,m=Math.hypot(n[f*2]-n[f*2-2],n[f*2+1]-n[f*2-1]);let w=m>0?Math.max(0,Math.min(1,(x-b)/m)):0,v=(f-1)*2,O=f*2,A=n[v]+(n[O]-n[v])*w,F=n[v+1]+(n[O+1]-n[v+1])*w,I=t[v]+(t[O]-t[v])*w,R=t[v+1]+(t[O+1]-t[v+1])*w,N=(I/g-p[0])*h,U=(R/g-p[1])*h,V=e.vertex(N,U,A-I,F-R,-1,-1,-1,-1,P,o),S=e.vertex(N,U,A-I,F-R,1,-1,1,-1,P,o),L=e.vertex(N,U,A-I,F-R,1,1,1,1,P,o),C=e.vertex(N,U,A-I,F-R,-1,1,-1,1,P,o);e.tri(V,S,L),e.tri(V,L,C)}}function jt(e,n){return`${e?e.join():""}|${n?n.join():""}`}function En(e,n,t){if(e.kind!=="connector"||n.kind!=="connector"||e.between!==n.between||e.route!==n.route)return null;let o=e.coords,i=n.coords,r=o.length;if(r<4||i.length<4||o[r-2]!==i[0]||o[r-1]!==i[1])return null;if(t){let c=r-4;for(;c>0&&Math.abs(o[c]-o[r-2])<1e-6&&Math.abs(o[c+1]-o[r-1])<1e-6;)c-=2;let d=o[r-2]-o[c],g=o[r-1]-o[c+1],p=Math.hypot(d,g);return p<1e-6?null:[d/p,g/p]}let u=2;for(;u+2<i.length&&Math.abs(i[u]-i[0])<1e-6&&Math.abs(i[u+1]-i[1])<1e-6;)u+=2;let l=i[u]-i[0],s=i[u+1]-i[1],a=Math.hypot(l,s);return a<1e-6?null:[l/a,s/a]}function Rn(e,n,t,o,i,r,u=null,l=null){let s=[],a=[];for(let A=0;A<n.length;A+=2){let F=s.length;F>=2&&Math.abs(s[F-2]-n[A])<1e-6&&Math.abs(s[F-1]-n[A+1])<1e-6||(s.push(n[A],n[A+1]),a.push(t[A],t[A+1]))}let c=s.length/2;if(c<2)return;let{scale:d,origin:g}=r,p=r.unitsPerMercator??1,h=A=>(a[A*2]/d-g[0])*p,f=A=>(a[A*2+1]/d-g[1])*p,b=A=>s[A*2]-a[A*2],m=A=>s[A*2+1]-a[A*2+1],k=new Float64Array(c);for(let A=1;A<c;A++)k[A]=k[A-1]+Math.hypot(s[A*2]-s[A*2-2],s[A*2+1]-s[A*2-1]);let y=A=>i<0?-i-k[A]:i+k[A],M=-1,P=-1,x=(A,F,I,R,N,U)=>{let V=h(A),S=f(A),L=b(A),C=m(A),E=y(A),T=e.vertex(V,S,L,C,F,I,R,N,E,o),_=e.vertex(V,S,L,C,-F,-I,-R,-N,E,o);U&&M>=0&&e.quad(M,P,T,_),M=T,P=_},w=(A,F,I,R,N,U)=>{let V=h(A),S=f(A),L=b(A),C=m(A),E=y(A),T=e.vertex(V,S,L,C,0,0,0,0,E,o),_=Math.atan2(I,F),B=Math.atan2(N,R)-_;for(;B>Math.PI;)B-=2*Math.PI;for(;B<-Math.PI;)B+=2*Math.PI;Math.abs(Math.abs(B)-Math.PI)<1e-6&&(B=U?-Math.PI:Math.PI);let G=Math.max(1,Math.ceil(Math.abs(B)*180/Math.PI/Bt)),z=e.vertex(V,S,L,C,F,I,F,I,E,o);for(let j=1;j<=G;j++){let $=_+B*j/G,X=Math.cos($),Z=Math.sin($),J=e.vertex(V,S,L,C,X,Z,X,Z,E,o);e.tri(T,z,J),z=J}},v=new Float64Array(c-1),O=new Float64Array(c-1);for(let A=0;A<c-1;A++){let F=s[A*2+2]-s[A*2],I=s[A*2+3]-s[A*2+1],R=Math.hypot(F,I)||1;v[A]=F/R,O[A]=I/R}for(let A=0;A<c;A++){let F=A>0||!!u,I=A<c-1||!!l,R=A>0?v[A-1]:u?u[0]:0,N=A>0?O[A-1]:u?u[1]:0,U=A<c-1?v[A]:l?l[0]:0,V=A<c-1?O[A]:l?l[1]:0,S=N,L=-R,C=V,E=-U;if(!F){w(A,C,E,-C,-E,!0),x(A,C,E,C,E,!1);continue}if(!I){x(A,S,L,S,L,!0),w(A,S,L,-S,-L,!1);continue}let T=A===c-1,_=A===0,B=S+C,G=L+E,z=Math.hypot(B,G);if(z<1e-9){_||(x(A,S,L,S,L,!0),w(A,S,L,-S,-L,!1)),T||x(A,C,E,C,E,!1);continue}B/=z,G/=z;let j=B*C+G*E,$=j>1e-6?1/j:1/0;if($<=Vt)x(A,B*$,G*$,B,G,!0);else{let Z=R*V-N*U>0;_||(x(A,S,L,S,L,!0),Z?w(A,S,L,C,E,!1):w(A,-S,-L,-C,-E,!0)),T||x(A,C,E,C,E,!1)}}}function $t(e){let n=performance.now(),t=Ie(e.graph),o=new Me(t,e.order).solve();return e.stabilize!==!1&&ln(t,e.stabilize??{}),{id:e.id,cost:o,orders:t.edges.map(i=>i.order),baselines:t.edges.map(i=>i.baseline),ms:performance.now()-n}}var ee=new Map,Wt=16;function Xt(e){let n=Ie(e.graph),t=new Int32Array(n.edges.length),o=0;for(let r of n.edges)t[r.id]=o,o+=r.routes.length;let i={id:e.session,graph:n,origin:e.origin??[0,0],unitsPerMercator:e.unitsPerMercator??1,layoutCache:new he,fullCache:new he,meshCache:new Le,lookAt:t,looks:null,laneStyle:(r,u)=>{let l=i.looks;if(!l)return null;let s=r.routes.indexOf(u);return s<0?null:l[t[r.id]+s]}};return i}function Zt(e){if(e.graph)for(ee.set(e.session,Xt(e));ee.size>Wt;)ee.delete(ee.keys().next().value);let n=ee.get(e.session);if(!n)return{...Tn(e),needGraph:!0};ee.delete(e.session),ee.set(e.session,n),e.looks!==void 0&&(n.looks=e.looks,n.layoutCache.clear(),n.fullCache.clear(),n.meshCache.clear());let t=e.extent==="full",o=performance.now(),i=An(n.graph,e.zoom,()=>e.style,{bounds:t?null:e.bounds,smooth:e.smooth,openFolds:e.openFolds,routes:e.routes??void 0,laneStyle:n.looks?n.laneStyle:void 0,cache:t?n.fullCache:n.layoutCache}),r=performance.now(),u=t?Jt:Fn(i.paths,{scale:i.scale,origin:n.origin,unitsPerMercator:n.unitsPerMercator,drawOrder:i.drawOrder,width:e.style.width,cache:n.meshCache}),l=performance.now();return{kind:"layout",id:e.id,session:e.session,zoom:i.zoom,scale:i.scale,bounds:i.bounds,mergedEdges:i.mergedEdges,drawOrder:i.drawOrder,stats:i.stats,paths:Ce(i.paths),vertices:u.vertices.slice(),colors:u.colors.slice(),indices:u.indices.slice(),vertexCount:u.vertexCount,indexCount:u.indexCount,groups:u.groups,groupRoutes:u.groupRoutes,groupLooks:u.groupLooks,groupDots:u.groupDots,groupPieces:u.groupPieces,groupDotPieces:u.groupDotPieces,layoutMs:r-o,meshMs:l-r}}var Jt={vertices:new Float32Array(0),colors:new Uint8Array(0),indices:new Uint32Array(0),vertexCount:0,indexCount:0,groups:[],groupRoutes:[],groupLooks:[],groupDots:[],groupPieces:[],groupDotPieces:[]};function Tn(e){return{kind:"layout",id:e.id,session:e.session,zoom:e.zoom,scale:512*Math.pow(2,e.zoom),bounds:e.bounds,mergedEdges:[],drawOrder:[],stats:{edges:0,edgesBuilt:0,edgesMerged:0,nodes:0,vertices:0,ms:0},paths:Ce([]),vertices:new Float32Array(0),colors:new Uint8Array(0),indices:new Uint32Array(0),vertexCount:0,indexCount:0,groups:[],groupRoutes:[],groupLooks:[],groupDots:[],groupPieces:[],groupDotPieces:[],layoutMs:0,meshMs:0}}function Yt(e){return[...De(e.paths),e.vertices.buffer,e.colors.buffer,e.indices.buffer]}typeof self<"u"&&typeof self.postMessage=="function"&&typeof document>"u"&&(self.onmessage=e=>{let n=e.data;try{if(n.kind==="dispose")ee.delete(n.session),self.postMessage({kind:"dispose",id:n.id});else if(n.kind==="layout"){let t=Zt(n);self.postMessage(t,Yt(t))}else self.postMessage($t(n))}catch(t){let o=String(t?.stack??t);n.kind==="layout"?self.postMessage({...Tn(n),error:o}):n.kind==="dispose"?self.postMessage({kind:"dispose",id:n.id,error:o}):self.postMessage({id:n.id,cost:NaN,orders:[],baselines:[],ms:0,error:o})}});})();\n'], { type: "text/javascript" }))), worker = new Worker(blobUrl);
} catch {
return failed[kind] = !0, null;
}
if (!worker)
return failed[kind] = !0, null;
worker.onmessage = (ev) => {
let p = pending.get(ev.data.id);
p && (pending.delete(ev.data.id), p.resolve(ev.data));
};
let broken = (reason) => {
workers[kind] === worker && (console.warn(`maplibre-gl-lanes: ${kind} worker failed, falling back to the main thread:`, reason), worker.terminate(), workers[kind] = null, failed[kind] = !0, settleAll(kind, reason));
};
return worker.onerror = (ev) => broken(ev.message || "the worker script failed"), worker.onmessageerror = () => broken("a message from the worker could not be read"), workers[kind] = worker, worker;
}
function nextRequestId() {
return nextId++;
}
function sendToWorker(req, transfer) {
let kind = kindOf(req);
if (req.kind === "dispose" && !workers.layout) return null;
let w = getWorker(kind);
return w ? new Promise((resolve) => {
pending.set(req.id, { worker: kind, req, resolve }), w.postMessage(req, transfer ?? []);
}) : null;
}
function disposeWorkers() {
for (let kind of ["order", "layout"])
workers[kind]?.terminate(), workers[kind] = null, failed[kind] = !1;
blobUrl && URL.revokeObjectURL(blobUrl), blobUrl = null, settleAll(null, null);
}
// src/core/order-async.ts
async function orderLanesAsync(g, opts = {}) {
let order = { ...opts.order };
opts.seed && (order.initial = seedFromSnapshot(g, opts.seed));
let req = { kind: "order", id: nextRequestId(), graph: toTransfer(g), order, stabilize: opts.stabilize }, sent = opts.sync ? null : sendToWorker(req);
if (!sent) {
let cost = new LaneOrderer(g, order).solve();
return opts.stabilize !== !1 && stabilizeLanes(g, opts.stabilize ?? {}), cost;
}
let res = await sent;
return res.disposed ? orderLanesAsync(g, { ...opts, sync: !0 }) : res.error ? (console.warn("maplibre-gl-lanes: ordering in worker failed, running on main thread:", res.error), orderLanesAsync(g, { ...opts, sync: !0 })) : (g.edges.forEach((e, i) => {
e.order = res.orders[i], e.baseline = res.baselines[i];
}), res.cost);
}
// src/core/folds.ts
var STEP_PER_CLEARANCE = 1 / 5, MAX_LEG_COS = -0.5, TANGENT_SAMPLES = 2, SMOOTH_PER_CLEARANCE = 0.15, SIMPLIFY_TOLERANCE_PX = 0.1, MIN_PUSH_PX = 0.01;
function scanPairs(x, y, reach, minSep, found) {
let n = x.length, size = 16;
for (; size < 2 * n; ) size *= 2;
let hash = (cx, cy) => (Math.imul(cx, 73856093) ^ Math.imul(cy, 19349663)) & size - 1, bucket = new Int32Array(n), start = new Int32Array(size + 1);
for (let i = 0; i < n; i++)
bucket[i] = hash(Math.floor(x[i] / reach), Math.floor(y[i] / reach)), start[bucket[i] + 1]++;
for (let b = 0; b < size; b++) start[b + 1] += start[b];
let items = new Int32Array(n), fill = start.slice(0, size);
for (let i = 0; i < n; i++) items[fill[bucket[i]]++] = i;
let r2 = reach * reach, seen = new Int32Array(9);
for (let i = 0; i < n - minSep; i++) {
let cx = Math.floor(x[i] / reach), cy = Math.floor(y[i] / reach), cells = 0;
for (let gy = cy - 1; gy <= cy + 1; gy++)
for (let gx = cx - 1; gx <= cx + 1; gx++) {
let b = hash(gx, gy), again = !1;
for (let q = 0; q < cells; q++) seen[q] === b && (again = !0);
if (!again) {
seen[cells++] = b;
for (let q = start[b + 1] - 1; q >= start[b]; q--) {
let j = items[q];
if (j - i < minSep) break;
let dx = x[j] - x[i], dy = y[j] - y[i], d2 = dx * dx + dy * dy;
d2 < r2 && found(i, j, d2);
}
}
}
}
}
var MIN_CLEARANCE_PX = 1;
function openFolds(p, clearance, guardA, guardB) {
let n0 = p.length / 2;
if (n0 < 3 || !(clearance >= MIN_CLEARANCE_PX)) return p;
let arcMin = Math.PI / 2 * clearance, total = 0;
for (let i = 2; i < p.length; i += 2) total += Math.hypot(p[i] - p[i - 2], p[i + 1] - p[i - 1]);
if (total - guardA - guardB <= arcMin) return p;
{
let heading = 0, lo = 0, hi = 0, last = Math.atan2(p[3] - p[1], p[2] - p[0]);
for (let i = 4; i < p.length; i += 2) {
let a = Math.atan2(p[i + 1] - p[i - 1], p[i] - p[i - 2]), turn = a - last;
turn > Math.PI ? turn -= 2 * Math.PI : turn < -Math.PI && (turn += 2 * Math.PI), heading += turn, heading < lo && (lo = heading), heading > hi && (hi = heading), last = a;
}
if (hi - lo < Math.acos(MAX_LEG_COS)) return p;
}
let count = Math.max(2, Math.ceil(total / (clearance * STEP_PER_CLEARANCE))), step = total / count, n = count + 1, x = new Float64Array(n), y = new Float64Array(n);
{
let seg = 1, segStart = 0, segLen = Math.hypot(p[2] - p[0], p[3] - p[1]);
for (let i = 0; i < n; i++) {
let s = i === count ? total : i * step;
for (; seg < n0 - 1 && s > segStart + segLen; )
segStart += segLen, seg++, segLen = Math.hypot(p[seg * 2] - p[seg * 2 - 2], p[seg * 2 + 1] - p[seg * 2 - 1]);
let t = segLen > 0 ? Math.min(1, (s - segStart) / segLen) : 0;
x[i] = p[seg * 2 - 2] + (p[seg * 2] - p[seg * 2 - 2]) * t, y[i] = p[seg * 2 - 1] + (p[seg * 2 + 1] - p[seg * 2 - 1]) * t;
}
}
let side = new Uint8Array(n), seeds = [];
if (scanPairs(x, y, clearance, Math.floor(arcMin / step) + 1, (i, j, d2) => {
let i0 = Math.max(0, i - TANGENT_SAMPLES), i1 = Math.min(n - 1, i + TANGENT_SAMPLES), j0 = Math.max(0, j - TANGENT_SAMPLES), j1 = Math.min(n - 1, j + TANGENT_SAMPLES), tix = x[i1] - x[i0], tiy = y[i1] - y[i0], tjx = x[j1] - x[j0], tjy = y[j1] - y[j0];
if (tix * tjx + tiy * tjy > MAX_LEG_COS * Math.hypot(tix, tiy) * Math.hypot(tjx, tjy)) return;
let dx2 = x[j] - x[i], dy2 = y[j] - y[i];
seeds.push(i, j, d2), side[i] |= tix * dy2 - tiy * dx2 > 0 ? 1 : 2, side[j] |= tjy * dx2 - tjx * dy2 > 0 ? 1 : 2;
}), !seeds.length) return p;
let order = [];
for (let s = 0; s < seeds.length; s += 3) order.push(s);
order.sort((a, b) => seeds[a + 2] - seeds[b + 2]);
let c2 = clearance * clearance, dist2 = (i, j) => (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]), taken = new Uint8Array(n), folds = [];
for (let s of order) {
let i = seeds[s], j = seeds[s + 1];
if (taken[i] === 1 || taken[j] === 1 || taken[i] && taken[j]) continue;
let seedI = i, seedJ = j, tip = -1;
for (; ; ) {
if (j - i <= 2) {
tip = i + j >> 1;
break;
}
let both = dist2(i + 1, j - 1), a = dist2(i + 1, j), b = dist2(i, j - 1), best = Math.min(both, a, b);
if (best >= c2) break;
both === best ? (i++, j--) : a === best ? i++ : j--;
}
tip >= 0 && (i = tip - 1, j = tip + 1);
let fold = { ai: [], bi: [], tip }, blocked = i < 0 || j > n - 1;
for (; !blocked; ) {
if (taken[i] === 1 || taken[j] === 1) {
blocked = !0;
break;
}
fold.ai.push(i), fold.bi.push(j);
let both = i > 0 && j < n - 1 ? dist2(i - 1, j + 1) : 1 / 0, a = i > 0 ? dist2(i - 1, j) : 1 / 0, b = j < n - 1 ? dist2(i, j + 1) : 1 / 0, best = Math.min(both, a, b);
if (best >= c2) break;
both === best ? (i--, j++) : a === best ? i-- : j++;
}
if (blocked || !fold.ai.length) {
taken[seedI] || (taken[seedI] = 2), taken[seedJ] || (taken[seedJ] = 2);
continue;
}
let lo = fold.ai[fold.ai.length - 1], hi = fold.bi[fold.bi.length - 1];
tip >= 0 ? taken.fill(1, lo, hi + 1) : (taken.fill(1, lo, fold.ai[0] + 1), taken.fill(1, fold.bi[0], hi + 1)), folds.push(fold);
}
let R = clearance / 2, ramp = (i) => {
let s = i * step, t = Math.min((s - guardA) / clearance, (total - s - guardB) / clearance);
return t <= 0 ? 0 : t >= 1 ? 1 : t * t * (3 - 2 * t);
}, dx = new Float64Array(n), dy = new Float64Array(n), capped = new Uint8Array(n), moved = !1;
for (let f of folds) {
let stack = !1;
for (let k = 0; k < f.ai.length && !stack; k++) stack = side[f.ai[k]] === 3 || side[f.bi[k]] === 3;
if (stack) continue;
let from = 0;
if (f.tip >= 0) {
let tx = x[f.tip], ty = y[f.tip], k = 0, mx = tx, my = ty, reached = 0;
for (; k < f.ai.length; k++) {
let qx = (x[f.ai[k]] + x[f.bi[k]]) / 2, qy = (y[f.ai[k]] + y[f.bi[k]]) / 2, far = Math.hypot(qx - tx, qy - ty);
if (far >= R) {
let t = (R - reached) / (far - reached);
mx += (qx - mx) * t, my += (qy - my) * t;
break;
}
mx = qx, my = qy, reached = far;
}
if (k >= f.ai.length || ramp(f.ai[k]) < 1 || ramp(f.bi[k]) < 1) continue;
let a = f.ai[k], b = f.bi[k], h = Math.hypot(x[a] - x[b], y[a] - y[b]) / 2;
if (h < 1e-6) continue;
let ux = (x[a] - x[b]) / (2 * h), uy = (y[a] - y[b]) / (2 * h), sweep = (ux * (ty - my) - uy * (tx - mx) > 0 ? 1 : -1) * Math.PI, a0 = Math.atan2(uy, ux);
for (let q = a; q <= b; q++) {
let ang = a0 + sweep * (q - a) / (b - a);
dx[q] = mx + Math.cos(ang) * R - x[q], dy[q] = my + Math.sin(ang) * R - y[q], capped[q] = 1;
}
moved = !0, from = k + 1;
}
for (let k = from; k < f.ai.length; k++) {
let a = f.ai[k], b = f.bi[k], d = Math.hypot(x[a] - x[b], y[a] - y[b]);
if (d >= clearance || d < 1e-6) continue;
let push2 = (clearance - d) / 2, ux = (x[a] - x[b]) / d, uy = (y[a] - y[b]) / d;
!capped[a] && Math.hypot(dx[a], dy[a]) < push2 && (dx[a] = ux * push2, dy[a] = uy * push2), !capped[b] && Math.hypot(dx[b], dy[b]) < push2 && (dx[b] = -ux * push2, dy[b] = -uy * push2), moved = !0;
}
}
if (!moved) return p;
let half = Math.max(1, Math.round(SMOOTH_PER_CLEARANCE * clearance / step)), sx = Float64Array.from(dx), sy = Float64Array.from(dy);
for (let d of [sx, sy])
for (let pass = 0; pass < 2; pass++) {
let src = Float64Array.from(d), sum = 0;
for (let i = -half; i <= half; i++) sum += src[Math.min(n - 1, Math.max(0, i))];
for (let i = 0; i < n; i++)
d[i] = sum / (2 * half + 1), sum += src[Math.min(n - 1, i + half + 1)] - src[Math.max(0, i - half)];
}
for (let i = 0; i < n; i++) {
if (capped[i]) continue;
let given = Math.hypot(dx[i], dy[i]), averaged = Math.hypot(sx[i], sy[i]), scale = averaged > 1e-9 ? Math.max(given, averaged) / averaged : 0;
dx[i] = sx[i] * scale, dy[i] = sy[i] * scale;
}
let live = new Uint8Array(n);
for (let i = 0; i < n; i++) {
let w = ramp(i);
if (Math.abs(dx[i] * w) < MIN_PUSH_PX && Math.abs(dy[i] * w) < MIN_PUSH_PX) {
dx[i] = dy[i] = 0;
continue;
}
dx[i] *= w, dy[i] *= w, live.fill(1, Math.max(0, i - 1), Math.min(n, i + 2));
}
let out = [], vertex = 0, cum = 0, flush = (upTo) => {
for (; vertex < n0; vertex++) {
if (vertex > 0) {
let l = Math.hypot(p[vertex * 2] - p[vertex * 2 - 2], p[vertex * 2 + 1] - p[vertex * 2 - 1]);
if (cum + l > upTo) return;
cum += l;
}
let at = Math.min(n - 1, Math.floor(cum / step));
!live[at] && !live[Math.min(n - 1, at + 1)] && out.push(p[vertex * 2], p[vertex * 2 + 1]);
}
};
for (let i = 0; i < n; i++) {
if (!live[i]) continue;
flush(i * step);
let run = [];
for (; i < n && live[i]; i++) run.push(x[i] + dx[i], y[i] + dy[i]);
for (let v of simplify(run, SIMPLIFY_TOLERANCE_PX)) out.push(v);
}
return flush(1 / 0), out;
}
// src/core/stacking.ts
var MAX_ROUTES = 16, WEAVE_COST = 1e3, END_OVER_COST = 1, MOVE_COST = 1e-3, cache = /* @__PURE__ */ new WeakMap();
function restack(g, base) {
let stack = stackingOf(g).order;
if (!stack.length) return base;
let involved = new Set(stack), next = 0;
return base.map((r) => involved.has(r) ? stack[next++] : r);
}
function stackingOf(g) {
let signature = "";
for (let e of g.edges) e.order.length > 1 && (signature += `${e.id}:${e.order.join(",")};`);
let known = cache.get(g);
if (known && known.signature === signature) return known;
let made = { signature, order: solve(g) };
return cache.set(g, made), made;
}
function solve(g) {
let weaves = [], endsUnder = [], endsCount = /* @__PURE__ */ new Map();
for (let node of g.nodes) {
if (node.ports.length < 2) continue;
let dirs = node.ports.map((p) => {
let e = g.edges[p.edge];
return p.end === "a" ? startDirection(e.coords) : endDirection(e.coords).map((v) => -v);
}), sweep = (from, to) => ccwAngle(dirs[from], dirs[to]), position = (port, route) => {
let p = node.ports[port], order2 = g.edges[p.edge].order, i = order2.indexOf(route);
return p.end === "a" ? i : order2.length - 1 - i;
}, turns = node.transitions.filter((t) => t.from >= 0 && t.to >= 0 && t.from !== t.to), groups = /* @__PURE__ */ new Map();
for (let t of turns) {
let u = Math.min(t.from, t.to), v = Math.max(t.from, t.to), key = `${u}:${v}`, grp = groups.get(key);
grp || groups.set(key, grp = { u, v, routes: [] }), grp.routes.includes(t.route) || grp.routes.push(t.route);
}
for (let grp of groups.values())
if (!(grp.routes.length < 2))
for (let t of turns) {
if (grp.routes.includes(t.route)) continue;
let shared = [t.from, t.to].filter((p) => p === grp.u || p === grp.v), crossed = [];
if (shared.length) {
if (shared.length === 1) {
let leg = shared[0], mine = t.from === leg ? t.to : t.from, theirs = grp.u === leg ? grp.v : grp.u, left = sweep(leg, mine) < sweep(leg, theirs), at = position(leg, t.route);
crossed = grp.routes.filter((r) => at < position(leg, r) !== left);
}
} else {
let through = sweep(grp.u, grp.v);
sweep(grp.u, t.from) < through != sweep(grp.u, t.to) < through && (crossed = grp.routes);
}
crossed.length > 1 && weaves.push({ group: crossed, across: t.route });
}
let passing = new Set(turns.map((t) => t.route));
node.ports.forEach((p, pi) => {
for (let r of g.edges[p.edge].routes) {
if (turns.some((t) => t.route === r && (t.from === pi || t.to === pi))) continue;
let under = !1;
for (let o of passing)
o === r || !node.ports.some((q, qi) => qi !== pi && g.edges[q.edge].routes.includes(o)) || (endsUnder.push([r, o]), under = !0);
under && endsCount.set(r, (endsCount.get(r) ?? 0) + 1);
}
});
}
if (!weaves.length) return [];
let ids = /* @__PURE__ */ new Set();
for (let w of weaves) {
ids.add(w.across);
for (let r of w.group) ids.add(r);
}
if (ids.size > MAX_ROUTES) return [];
let routes = [...ids].sort((x, y) => (endsCount.get(y) ?? 0) - (endsCount.get(x) ?? 0) || (x < y ? -1 : x > y ? 1 : 0)), index = new Map(routes.map((r, i) => [r, i])), n = routes.length, groupsOf = routes.map(() => []);
for (let w of weaves) {
let mask = 0;
for (let r of w.group) mask |= 1 << index.get(r);
let list = groupsOf[index.get(w.across)];
list.includes(mask) || list.push(mask);
}
let over = routes.map(() => 0);
for (let [r, o] of endsUnder) {
let a = index.get(r), b = index.get(o);
a !== void 0 && b !== void 0 && (over[a] |= 1 << b);
}
let full = (1 << n) - 1, cost = new Float64Array(full + 1).fill(1 / 0), last = new Int8Array(full + 1).fill(-1);
cost[0] = 0;
for (let drawn = 0; drawn < full; drawn++) {
if (cost[drawn] === 1 / 0) continue;
let place = 0;
for (let b = drawn; b; b &= b - 1) place++;
for (let x = 0; x < n; x++) {
if (drawn & 1 << x) continue;
let c = cost[drawn] + Math.abs(x - place) * MOVE_COST;
for (let mask of groupsOf[x]) {
let below = drawn & mask;
below && below !== mask && (c += WEAVE_COST);
}
for (let b = drawn & over[x]; b; b &= b - 1) c += END_OVER_COST;
let then = drawn | 1 << x;
c < cost[then] - 1e-12 && (cost[then] = c, last[then] = x);
}
}
let order = [];
for (let drawn = full; drawn; drawn ^= 1 << last[drawn]) order.push(routes[last[drawn]]);
return order.reverse();
}
// src/core/layout.ts
var SIMPLIFY_TOLERANCE_PX2 = 0.25, GENERALIZE_PER_OFFSET = 0.25, MIN_FRONT_MARGIN_LANES = 0.6, MIN_PIECE_PX = 1e-3, MAX_FRONT_FRACTION = 0.42, CLIQUE_MIN_REF_LANES = 1.5, MAX_SLIDE_SLOPE = 0.4, SOLO_EASE_LANES = 12, SOLO_EASE_STEPS = 6, MERGE_BELOW_BUNDLE_WIDTHS = 1, MAX_MERGE_PASSES = 4, BEND_DEVIATION_PX = 1.5, CORNER_BEND_DEG = 60, CORNER_RADIUS_LANES = 1.5, CORNER_MIN_TURN_DEG = 60, CORNER_MAX_REACH = 1.5, FOLLOW_ABOVE_LANES = 1, SNAP_HOOK_LANES = 3, LayoutCache = class {
constructor() {
__publicField(this, "state", null);
}
clear() {
this.state = null;
}
/** @internal */
stateFor(g, zoom, style, smooth, openFolds2, laneStyle) {
let s = this.state;
return s && s.graph === g && s.zoom === zoom && s.spacing === style.spacing && s.width === style.width && s.casing === style.casingWidth && s.smooth === smooth && s.openFolds === openFolds2 && s.laneStyle === laneStyle ? s : this.state = zoomState(g, zoom, style, smooth, openFolds2, laneStyle);
}
};
function checkedSizes(sizesAt, zoom) {
requireSizesFunction(sizesAt);
let s = sizesAt(zoom), ok = (v, min) => typeof v == "number" && Number.isFinite(v) && v >= min;
if (!s || !ok(s.spacing, 0) || !ok(s.width, 0) || !ok(s.casingWidth, 0) || s.spacing === 0 || s.width === 0) {
let got = s && typeof s == "object" ? JSON.stringify({ spacing: s.spacing, width: s.width, casingWidth: s.casingWidth }, (_k, v) => v === void 0 ? "undefined" : typeof v == "number" && !Number.isFinite(v) ? String(v) : v) : String(s);
throw new TypeError(`maplibre-gl-lanes: \`sizes(${zoom})\` must return {spacing, width, casingWidth} as finite numbers in px, with spacing and width above 0; got ${got}`);
}
return s;
}
function requireSizesFunction(sizesAt) {
if (typeof sizesAt != "function")
throw new TypeError("maplibre-gl-lanes: `sizes` must be a function of the zoom that returns {spacing, width, casingWidth}");
}
function layoutAtZoom(g, zoom, styleAt, opts = {}) {
let t0 = performance.now(), smooth = opts.smooth ?? !0, open = opts.openFolds ?? !0, laneStyle = opts.laneStyle ?? null, style = checkedSizes(styleAt, zoom), st = opts.cache ? opts.cache.stateFor(g, zoom, style, smooth, open, laneStyle) : zoomState(g, zoom, style, smooth, open, laneStyle), bounds = opts.bounds ?? null, only = opts.routes ? new Set(opts.routes) : null, inView = new Uint8Array(g.edges.length);
for (let e of g.edges) {
if (!bounds) {
inView[e.id] = 1;
continue;
}
e.bounds || (e.bounds = polylineBounds(e.coords)), inView[e.id] = boundsIntersect(e.bounds, bounds) ? 1 : 0;
}
let paths = [], laneIndex = /* @__PURE__ */ new Map(), vertices = 0, edgesBuilt = 0;
for (let e of g.edges)
if (!(!inView[e.id] || st.short[e.id])) {
edgesBuilt++;
for (let r of e.routes) {
if (only && !only.has(r)) continue;
let path = lanePathOf(st, e.id, r);
path && (laneIndex.set(laneKey(st, e.id, r), path), vertices += path.coords.length / 2, paths.push(path));
}
}
for (let ji = 0; ji < st.junctions.length; ji++) {
if (!touchesView(st.junctions[ji], inView)) continue;
let tails = planJunction(st, ji).tails;
for (let plan of tails) {
let t = plan.tail;
if (!(!inView[plan.port.edge] && !t.edges.some((s) => inView[s.edge])) && (resolveTail(st, plan), !(plan.mode !== 1 || only && !only.has(t.route))))
for (let path of plan.slide)
vertices += path.coords.length / 2, paths.push(path);
}
for (let plan of tails)
if (!(plan.mode === 1 || only && !only.has(plan.tail.route)))
for (let { edge } of plan.tail.edges) {
let k = laneKey(st, edge, plan.tail.route);
if (!inView[edge] || laneIndex.has(k)) continue;
let path = lanePathOf(st, edge, plan.tail.route);
path && (laneIndex.set(k, path), vertices += path.coords.length / 2, paths.push(path));
}
for (let isl of st.junctions[ji].islands)
if (!(only && !only.has(isl.route) || !isl.steps.some((s) => inView[s.edge])))
for (let path of islandPaths(st, isl)) {
if (path.kind === "lane") {
let k = laneKey(st, path.edge, isl.route);
if (laneIndex.has(k)) continue;
laneIndex.set(k, path);
}
vertices += path.coords.length / 2, paths.push(path);
}
}
for (let ji = 0; ji < st.junctions.length; ji++)
if (touchesView(st.junctions[ji], inView)) {
for (let grp of planJunction(st, ji).groups)
if (!(!inView[grp.edgeU] || !inView[grp.edgeV])) {
buildGroup(st, grp);
for (let m of grp.members)
if (!(m.plan?.mode === 1 || only && !only.has(m.route)))
for (let path of st.connPaths.get(m.key) ?? [])
vertices += path.coords.length / 2, paths.push(path);
}
}
for (let p of paths)
p.look.dash && !st.phased.has(p.route) && (assignDashPhase(st, p.route), st.phased.add(p.route));
return {
zoom,
scale: st.scale,
paths,
drawOrder: st.drawOrder,
bounds,
mergedEdges: st.mergedEdges,
stats: { edges: g.edges.length, edgesBuilt, edgesMerged: st.mergedEdges.length, nodes: g.nodes.length, vertices, ms: performance.now() - t0 }
};
}
function zoomState(g, zoom, style, smooth, openFolds2, laneStyle) {
let { spacing, width, casingWidth: casing } = style, scale = 512 * Math.pow(2, zoom), E = g.edges.length, routeIndex = /* @__PURE__ */ new Map();
for (let r of g.routes.keys()) routeIndex.set(r, routeIndex.size);
for (let e of g.edges) for (let r of e.routes) routeIndex.has(r) || routeIndex.set(r, routeIndex.size);
let routeCount = Math.max(1, routeIndex.size), offsets = new Float64Array(E * routeCount);
for (let e of g.edges) {
let k = e.order.length;
for (let p = 0; p < k; p++) {
let r = routeIndex.get(e.order[p]);
r !== void 0 && (offsets[e.id * routeCount + r] = ((k - 1) / 2 - p + (e.baseline ?? 0)) * spacing);
}
}
let simplePx = new Array(E), edgeLen = new Float64Array(E), dirA = new Array(E), dirB = new Array(E);
for (let e of g.edges) {
let widest = ((e.routes.length - 1) / 2 + Math.abs(e.baseline ?? 0)) * spacing;
e.simplifyRank || (e.simplifyRank = simplifyRank(e.coords));
let p = simplifyRanked(e.coords, e.simplifyRank, Math.max(SIMPLIFY_TOLERANCE_PX2, GENERALIZE_PER_OFFSET * widest) / scale);
for (let i = 0; i < p.length; i++) p[i] *= scale;
simplePx[e.id] = p, edgeLen[e.id] = polylineLength(p), dirA[e.id] = startDirection(p), dirB[e.id] = endDirection(p).map((v) => -v);
}
let halfWidth = (e) => (e.routes.length - 1) / 2 * spacing + width / 2 + casing, laneOffsetTravel = (e, r, forward) => {
let off = offsets[e.id * routeCount + routeIndex.get(r)];
return forward ? off : -off;
}, short = new Uint8Array(E), degree = (n) => g.nodes[n].ports.length, bundleWidth = new Float64Array(g.nodes.length);
for (let n of g.nodes) {
let widest = 0;
for (let p of n.ports) widest = Math.max(widest, g.edges[p.edge].routes.length);
bundleWidth[n.id] = widest * spacing;
}
let junctions = [], need = new Float64Array(2 * E), change = new Float64Array(2 * E), continues = new Uint8Array(2 * E * routeCount);
for (let pass = 0; pass < MAX_MERGE_PASSES; pass++) {
junctions = buildJunctions(g, short, edgeLen, dirA, dirB, halfWidth), { need, change, continues } = junctionFronts(g, junctions, laneOffsetTravel, spacing, routeIndex, routeCount);
let merged = !1;
for (let e of g.edges) {
if (short[e.id] || e.a === e.b || degree(e.a) < 2 || degree(e.b) < 2) continue;
let len = edgeLen[e.id];
(len < MERGE_BELOW_BUNDLE_WIDTHS * Math.max(bundleWidth[e.a], bundleWidth[e.b]) || len < change[2 * e.id] + change[2 * e.id + 1]) && (short[e.id] = 1, merged = !0);
}
if (!merged) break;
}
let frontA = new Float64Array(E), frontB = new Float64Array(E), mergedEdges = [];
for (let e of g.edges) {
if (short[e.id]) {
mergedEdges.push(e.id);
continue;
}
let cap = edgeLen[e.id] * MAX_FRONT_FRACTION;
frontA[e.id] = Math.min(need[2 * e.id], cap), frontB[e.id] = Math.min(need[2 * e.id + 1], cap);
}
let endsUnder = /* @__PURE__ */ new Map(), underOther = (node, edge, r) => {
for (let p of node.ports)
if (p.edge !== edge) {
for (let o of g.edges[p.edge].routes) if (o !== r) return !0;
}
return !1;
};
for (let e of g.edges)
if (!short[e.id])
for (let r of e.routes) {
let ri = routeIndex.get(r);
for (let end = 0; end < 2; end++) {
let node = g.nodes[end === 0 ? e.a : e.b];
!continues[(2 * e.id + end) * routeCount + ri] && underOther(node, e.id, r) && endsUnder.set(r, (endsUnder.get(r) ?? 0) + 1);
}
}
let drawOrder = restack(g, [...g.routes.keys()].sort((x, y) => (endsUnder.get(y) ?? 0) - (endsUnder.get(x) ?? 0) || (x < y ? -1 : x > y ? 1 : 0)));
return {
graph: g,
zoom,
scale,
spacing,
width,
casing,
smooth,
openFolds: openFolds2,
laneStyle,
looks: /* @__PURE__ */ new Map(),
routeIndex,
routeCount,
offsets,
simplePx,
edgeLen,
dirA,
dirB,
short,
junctions,
groups: new Array(junctions.length),
tails: new Array(junctions.length),
continues,
frontA,
frontB,
mergedEdges,
drawOrder,
preparedPx: new Array(E),
lanes: new Array(E * routeCount),
lanePaths: new Array(E * routeCount),
connPaths: /* @__PURE__ */ new Map(),
phased: /* @__PURE__ */ new Set()
};
}
function touchesView(j, inView) {
for (let edge of j.edges) if (inView[edge]) return !0;
return !1;
}
function planJunction(st, ji) {
let known = st.groups[ji];
if (known) return { groups: known, tails: st.tails[ji] };
let j = st.junctions[ji], byKey = /* @__PURE__ */ new Map(), groups = [];
for (let t of j.transitions) {
let pu = j.ports[t.u], pv = j.ports[t.v], lateral = offsetTravel(st, pu.edge, t.route, pu.end === "b"), lateralOut = offsetTravel(st, pv.edge, t.route, pv.end === "a"), key = `${pu.edge}:${pv.edge}:${(lateral - lateralOut).toFixed(3)}`, grp = byKey.get(key);
grp || (grp = { edgeU: pu.edge, edgeV: pv.edge, members: [] }, byKey.set(key, grp), groups.push(grp)), grp.members.push({
route: t.route,
key: connKey(st, t.route, pu.edge, pu.end, pv.edge, pv.end),
pu,
pv,
lateral,
lateralOut,
via: t.via
});
}
let crossings = /* @__PURE__ */ new Map();
for (let grp of groups)
for (let m of grp.members)
for (let step of m.via) {
let k = `${m.route}|${step.edge}`, list = crossings.get(k);
list ? list.push(m) : crossings.set(k, [m]);
}
for (let list of crossings.values()) if (list.length > 1) for (let m of list) m.forked = !0;
let tails = [];
for (let t of j.tails) {
let p = j.ports[t.port], far = t.edges[t.side === "end" ? t.edges.length - 1 : 0], step = t.edges[t.side === "end" ? 0 : t.edges.length - 1], plan = {
tail: t,
port: p,
mode: 0,
key: t.side === "end" ? connKey(st, t.route, p.edge, p.end, far.edge, far.forward ? "b" : "a") : connKey(st, t.route, far.edge, far.forward ? "a" : "b", p.edge, p.end)
};
tails.push(plan);
let u = t.side === "end" ? p.edge : step.edge, v = t.side === "end" ? step.edge : p.edge;
groups.push({
edgeU: u,
edgeV: v,
members: [{
route: t.route,
pu: p,
pv: p,
lateral: 0,
lateralOut: 0,
via: [],
plan,
key: t.side === "end" ? connKey(st, t.route, u, p.end, v, step.forward ? "a" : "b") : connKey(st, t.route, u, step.forward ? "b" : "a", v, p.end)
}]
});
}
return st.groups[ji] = groups, st.tails[ji] = tails, { groups, tails };
}
function laneKey(st, edge, route) {
return edge * st.routeCount + st.routeIndex.get(route);
}
function connKey(st, route, edgeU, endU, edgeV, endV) {
let ends = 2 * st.graph.edges.length;
return ((edgeU * 2 + (endU === "b" ? 1 : 0)) * ends + edgeV * 2 + (endV === "b" ? 1 : 0)) * st.routeCount + st.routeIndex.get(route);
}
function offsetTravel(st, edge, route, forward) {
let off = st.offsets[laneKey(st, edge, route)];
return forward ? off : -off;
}
function continuesThrough(st, edge, end, route) {
return st.continues[(2 * edge + end) * st.routeCount + st.routeIndex.get(route)] !== 0;
}
function lookOf(st, e, r) {
let meta = st.graph.routes.get(r), over = st.laneStyle ? st.laneStyle(e, r) : null, color = over?.color || meta?.color || "#888", dash = over?.dash ?? meta?.dash, dashColor = over?.dashColor ?? meta?.dashColor, dashCap = over?.dashCap ?? meta?.dashCap, key = `${color}|${dash ? dash[0] + "," + dash[1] : ""}|${dashColor ?? ""}|${dashCap ?? ""}`, look = st.looks.get(key);
return look || st.looks.set(key, look = { color, dash, dashColor, dashCap }), look;
}
function widestOffset(st, edge) {
let e = st.graph.edges[edge];
return ((e.routes.length - 1) / 2 + Math.abs(e.baseline ?? 0)) * st.spacing;
}
function bendBudget(st, edges) {
let widest = 0;
for (let edge of edges) widest = Math.max(widest, widestOffset(st, edge));
return Math.max(BEND_DEVIATION_PX, GENERALIZE_PER_OFFSET * widest);
}
function roundedPx(st, p, edges) {
return simplify(roundBends(p, bendBudget(st, edges), 3, CORNER_BEND_DEG, CORNER_RADIUS_LANES * st.spacing), SIMPLIFY_TOLERANCE_PX2);
}
function preparedPx(st, edge) {
let px = st.preparedPx[edge];
if (!px) {
let simple = st.simplePx[edge];
px = st.smooth ? roundedPx(st, simple, [edge]) : simple;
let e = st.graph.edges[edge];
if (st.openFolds && e.routes.length > 1 && !st.short[edge]) {
let widest = widestOffset(st, edge);
px = openFolds(px, 2 * widest + st.width + 2 * st.casing, st.frontA[edge] + st.spacing, st.frontB[edge] + st.spacing);
}
st.preparedPx[edge] = px;
}
return px;
}
function orientedPx(st, edge, forward) {
let px = preparedPx(st, edge);
return forward ? px : reversed(px);
}
function laneOf(st, edge, route) {
let k = laneKey(st, edge, route), hit = st.lanes[k];
if (hit !== void 0) return hit;
let g = st.graph, e = g.edges[edge], px = preparedPx(st, edge), lane;
if (st.short[edge])
lane = offsetPolylineAnchored(px, st.offsets[k]);
else {
let cutA = continuesThrough(st, edge, 0, route) ? st.frontA[edge] : 0, cutB = continuesThrough(st, edge, 1, route) ? st.frontB[edge] : 0, trimmed = cutA > 0 || cutB > 0 ? trimPolyline(px, cutA, cutB) : px;
lane = e.order.length === 1 && st.offsets[k] !== 0 ? easedSoloLane(trimmed, st.offsets[k], continuesThrough(st, edge, 0, route), continuesThrough(st, edge, 1, route), SOLO_EASE_LANES * st.spacing, st.spacing) : offsetPolylineAnchored(trimmed, st.offsets[k]);
let na = g.nodes[e.a], nb = g.nodes[e.b];
cutA > 0 && (lane.anchors[0] = na.x * st.scale, lane.anchors[1] = na.y * st.scale), cutB > 0 && (lane.anchors[lane.anchors.length - 2] = nb.x * st.scale, lane.anchors[lane.anchors.length - 1] = nb.y * st.scale);
}
return st.lanes[k] = lane, lane;
}
function easedSoloLane(line, offset, holdA, holdB, ease, flat) {
if (!holdA && !holdB) return offsetPolylineAnchored(line, 0);
let flatA = holdA ? flat : 0, flatB = holdB ? flat : 0, len = polylineLength(line) - flatA - flatB;
if (len < 1) return offsetPolylineAnchored(line, offset);
let inner = trimPolyline(line, flatA, flatB, 0), easeA = holdB ? ease : Math.min(ease, len), easeB = holdA ? ease : Math.min(ease, len), held = (t) => 1 - t * t * (3 - 2 * t), at = (s) => offset * Math.max(
holdA ? held(Math.min(1, s / easeA)) : 0,
holdB ? held(Math.min(1, (len - s) / easeB)) : 0
), slide = (piece, s0, s1) => {
let steps = Math.max(1, Math.ceil((s1 - s0) / ease * SOLO_EASE_STEPS)), via = [];
for (let i = 1; i < steps; i++) via.push(i / steps, at(s0 + (s1 - s0) * i / steps));
return offsetPolylineSlidingAnchored(piece, at(s0), at(s1), 4, via);
}, parts = [];
flatA > 0 && parts.push(offsetPolylineAnchored(firstPortion(line, flatA), offset));
let headLen = holdA ? easeA : 0, tailLen = holdB ? easeB : 0;
headLen + tailLen > len - 1 ? parts.push(slide(inner, 0, len)) : (headLen > 0 && parts.push(slide(firstPortion(inner, headLen), 0, headLen)), parts.push(offsetPolylineAnchored(trimPolyline(inner, headLen, tailLen, 0), 0)), tailLen > 0 && parts.push(slide(lastPortion(inner, tailLen), len - tailLen, len))), flatB > 0 && parts.push(offsetPolylineAnchored(lastPortion(line, flatB), offset));
let points = [], anchors = [];
return parts.forEach((part, i) => {
for (let j = i > 0 ? 2 : 0; j < part.points.length; j++)
points.push(part.points[j]), anchors.push(part.anchors[j]);
}), { points, anchors };
}
function lanePathOf(st, edge, route) {
let k = laneKey(st, edge, route), hit = st.lanePaths[k];
if (hit !== void 0) return hit;
let lane = laneOf(st, edge, route);
if (lane.points.length < 4)
return st.lanePaths[k] = null, null;
let e = st.graph.edges[edge], path = {
route,
look: lookOf(st, e, route),
coords: lane.points,
anchors: lane.anchors,
kind: "lane",
travel: travelSign(e.direction.get(route)),
startDistance: 0,
edge
};
return st.lanePaths[k] = path, path;
}
function guideOf(st, parts, edges) {
let out = [];
for (let p of parts)
for (let i = 0; i < p.length; i += 2)
out.length && Math.abs(out[out.length - 2] - p[i]) < 1e-6 && Math.abs(out[out.length - 1] - p[i + 1]) < 1e-6 || out.push(p[i], p[i + 1]);
return st.smooth ? roundedPx(st, out, edges) : out;
}
function resolveTail(st, plan) {
if (plan.mode) return;
plan.mode = 2;
let t = plan.tail, p = plan.port, portLane = laneOf(st, p.edge, t.route), parts = t.edges.map((s) => orientedPx(st, s.edge, s.forward)), far = t.edges[t.side === "end" ? t.edges.length - 1 : 0], farOffset = offsetTravel(st, far.edge, t.route, far.forward), portOffset = offsetTravel(st, p.edge, t.route, t.side === "end" ? p.end === "b" : p.end === "a"), portPx = preparedPx(st, p.edge), portPart = t.side === "end" ? lastPortion(p.end === "b" ? portPx : reversed(portPx), p.end === "b" ? st.frontB[p.edge] : st.frontA[p.edge]) : firstPortion(p.end === "a" ? portPx : reversed(portPx), p.end === "a" ? st.frontA[p.edge] : st.frontB[p.edge]), edges = [p.edge, ...t.edges.map((s) => s.edge)], guide = t.side === "end" ? guideOf(st, [portPart, ...parts], edges) : guideOf(st, [...parts, portPart], edges), slide = t.side === "end" ? offsetPolylineSlidingAnchored(guide, portOffset, farOffset) : offsetPolylineSlidingAnchored(guide, farOffset, portOffset);
if (slide.points.length < 4) return;
let lanePts = t.side === "end" ? p.end === "b" ? portLane.points : reversed(portLane.points) : p.end === "a" ? portLane.points : reversed(portLane.points);
t.side === "end" ? (slide.points[0] = lanePts[lanePts.length - 2], slide.points[1] = lanePts[lanePts.length - 1]) : (slide.points[slide.points.length - 2] = lanePts[0], slide.points[slide.points.length - 1] = lanePts[1]);
let { points: coords, anchors } = removeLoopsAnchored(slide.points, slide.anchors, SNAP_HOOK_LANES * st.spacing);
if (coords.length < 4) return;
let between = t.side === "end" ? [p.edge, far.edge] : [far.edge, p.edge], steps = t.side === "end" ? [{ edge: p.edge, forward: p.end === "b" }, ...t.edges] : [...t.edges, { edge: p.edge, forward: p.end === "a" }];
plan.slide = splitAtNodes(st, t.route, coords, anchors, steps, p.node, between, !0), st.connPaths.set(plan.key, plan.slide), plan.mode = 1;
}
function islandPaths(st, isl) {
if (isl.paths) return isl.paths;
let g = st.graph, first = isl.steps[0], last = isl.steps[isl.steps.length - 1], guide = guideOf(st, isl.steps.map((s) => orientedPx(st, s.edge, s.forward)), isl.steps.map((s) => s.edge)), d0 = offsetTravel(st, first.edge, isl.route, first.forward), d1 = offsetTravel(st, last.edge, isl.route, last.forward), slide = offsetPolylineSlidingAnchored(guide, d0, d1);
if (slide.points.length >= 4) {
let e = g.edges[first.edge];
return isl.paths = splitAtNodes(st, isl.route, slide.points, slide.anchors, isl.steps, first.forward ? e.a : e.b, [first.edge, last.edge], !0);
}
let lanes = [];
for (let s of isl.steps) {
let path = lanePathOf(st, s.edge, isl.route);
path && lanes.push(path);
}
return isl.paths = lanes;
}
function assignDashPhase(st, route) {
let g = st.graph, forwardOn = /* @__PURE__ */ new Map();
for (let chain of g.chains.get(route) ?? [])
for (let s of chain.steps) forwardOn.set(s.edge, s.forward);
let travelEnd = (edge) => forwardOn.get(edge) === !1 ? "a" : "b", pieces = [], index = /* @__PURE__ */ new Map(), along = [], add = (p, withTravel) => {
let list = p ? Array.isArray(p) ? p : [p] : [];
if (list.length && !index.has(list[0])) {
for (let q of list) index.set(q, pieces.length);
pieces.push(list), along.push(withTravel);
}
}, addLane = (edge) => add(lanePathOf(st, edge, route), forwardOn.get(edge) !== !1);
for (let e of g.edges) !st.short[e.id] && e.routes.includes(route) && addLane(e.id);
for (let ji = 0; ji < st.junctions.length; ji++) {
let { groups, tails } = planJunction(st, ji);
for (let plan of tails)
if (plan.tail.route === route)
if (resolveTail(st, plan), plan.mode === 1) add(plan.slide, !0);
else for (let { edge } of plan.tail.edges) addLane(edge);
for (let grp of groups)
if (grp.members.some((m) => m.route === route)) {
buildGroup(st, grp);
for (let m of grp.members) {
if (m.route !== route || m.plan?.mode === 1) continue;
let withTravel = !!m.plan || m.pu.end === travelEnd(m.pu.edge);
add(st.connPaths.get(m.key), withTravel);
}
}
for (let isl of st.junctions[ji].islands) {
if (isl.route !== route) continue;
let ps = islandPaths(st, isl);
if (ps[0]?.kind === "connector") add(ps, !0);
else for (let p of ps) add(p, !0);
}
}
if (!pieces.length) return;
let n = pieces.length, atPoint = /* @__PURE__ */ new Map(), endsAt = new Array(2 * n);
for (let i = 0; i < n; i++) {
let first = pieces[i][0].coords, last = pieces[i][pieces[i].length - 1].coords;
for (let end = 0; end < 2; end++) {
let x = end ? last[last.length - 2] : first[0], y = end ? last[last.length - 1] : first[1], row = atPoint.get(x);
row || atPoint.set(x, row = /* @__PURE__ */ new Map());
let list = row.get(y);
list || row.set(y, list = []), list.push(i * 2 + end), endsAt[i * 2 + end] = list;
}
}
let length = new Float64Array(n).fill(-1), at = new Float64Array(2 * n), reached = new Uint8Array(n), reach = (i, end, d) => {
let l = length[i];
if (l < 0) {
l = 0;
for (let p of pieces[i]) l += polylineLength(p.coords);
length[i] = l;
}
let d0 = along[i] ? end ? d - l : d : end ? d + l : d;
at[i * 2] = d0, at[i * 2 + 1] = along[i] ? end ? d : d + l : end ? d : d - l, reached[i] = 1;
}, root = 0;
chains: for (let chain of g.chains.get(route) ?? [])
for (let s of chain.steps) {
let lane = st.lanePaths[laneKey(st, s.edge, route)];
if (lane) {
root = index.get(lane);
break chains;
}
}
let queue = [];
for (let next = -1; next < n; next++) {
if (next >= 0) {
if (reached[next]) continue;
root = next;
}
reach(root, 0, 0), queue.length = 0, queue.push(root);
for (let q = 0; q < queue.length; q++) {
let i = queue[q];
for (let end = 0; end < 2; end++) {
let d = at[i * 2 + end];
for (let code of endsAt[i * 2 + end]) {
let o = code >> 1;
reached[o] || (reach(o, code & 1, d), queue.push(o));
}
}
}
let least = 0;
for (let i of queue) least = Math.min(least, at[i * 2], at[i * 2 + 1]);
for (let i of queue) {
let d0 = at[i * 2] - least;
for (let p of pieces[i]) {
p.startDistance = along[i] ? d0 : -d0;
let l = pieces[i].length > 1 ? polylineLength(p.coords) : 0;
d0 = along[i] ? d0 + l : d0 - l;
}
}
}
}
function buildGroup(st, grp) {
let plan = grp.members[0].plan;
if (plan && (resolveTail(st, plan), plan.mode === 1))
return;
let missing = !1;
for (let m of grp.members) st.connPaths.has(m.key) || (missing = !0);
if (!missing) return;
let g = st.graph, clique = [], ends = /* @__PURE__ */ new Map(), follows = !1;
for (let m of grp.members) {
if (st.connPaths.set(m.key, null), m.plan) continue;
let laneU = laneOf(st, m.pu.edge, m.route), laneV = laneOf(st, m.pv.edge, m.route), from = m.pu.end === "b" ? laneU.points : reversed(laneU.points), to = m.pv.end === "a" ? laneV.points : reversed(laneV.points), made = m.via.length ? null : connector(from, to, st.spacing, cutDirection(st, m.pu.edge, m.pu.end), cutDirection(st, m.pv.edge, m.pv.end, !0));
ends.set(m, { from, to, made }), made && made.coords.length >= 4 && leavesLine(st, m, made.coords) && (follows = !0);
}
for (let m of grp.members) {
if (m.plan) {
buildTailConnector(st, m, clique);
continue;
}
let { from, to, made } = ends.get(m);
if ((m.via.length || follows) && buildViaConnector(st, m, from, to)) continue;
let curve = made ?? connector(from, to, st.spacing, cutDirection(st, m.pu.edge, m.pu.end), cutDirection(st, m.pv.edge, m.pv.end, !0));
curve.coords.length < 4 || clique.push({ member: m, lateral: m.lateral, own: curve.coords, coords: curve.coords, corner: curve.corner });
}
let arcs = clique.filter((c) => !c.corner);
arcs.length > 1 && deriveCliqueConnectors(arcs, st.spacing);
for (let c of clique) {
let m = c.member, conn = c.coords, node = g.nodes[m.pu.node], anchors = new Array(conn.length);
for (let i = 0; i < conn.length; i += 2)
anchors[i] = node.x * st.scale, anchors[i + 1] = node.y * st.scale;
st.connPaths.set(m.key, splitAtNodes(st, m.route, conn, anchors, memberSteps(m), m.pu.node, [grp.edgeU, grp.edgeV], !1));
}
}
function cutDirection(st, edge, end, leaving = !1) {
let front = end === "b" ? st.frontB[edge] : st.frontA[edge];
if (front <= 0) return null;
let px = preparedPx(st, edge), before = trimPolyline(end === "b" ? px : reversed(px), 0, front);
if (before.length < 4) return null;
let d = endDirectionOver(before, st.spacing / 2);
return d[0] === 0 && d[1] === 0 ? null : leaving ? [-d[0], -d[1]] : d;
}
function leavesLine(st, m, coords) {
let uPx = preparedPx(st, m.pu.edge), vPx = preparedPx(st, m.pv.edge), line = lastPortion(m.pu.end === "b" ? uPx : reversed(uPx), m.pu.end === "b" ? st.frontB[m.pu.edge] : st.frontA[m.pu.edge]).concat(firstPortion(m.pv.end === "a" ? vPx : reversed(vPx), m.pv.end === "a" ? st.frontA[m.pv.edge] : st.frontB[m.pv.edge])), limit = Math.max(Math.abs(m.lateral), Math.abs(m.lateralOut)) + FOLLOW_ABOVE_LANES * st.spacing, g = st.graph;
if (g.edges[m.pu.edge].order.length === 1 && g.edges[m.pv.edge].order.length === 1) {
let node = g.nodes[m.pu.node], cover = Math.max(Math.abs(m.lateral), Math.abs(m.lateralOut)) + st.width / 2 + st.casing;
if (distToPolyline(node.x * st.scale, node.y * st.scale, coords) > cover) return !0;
}
for (let i = 0; i < coords.length; i += 2) {
let within = !1;
for (let k = 2; k < line.length && !within; k += 2) {
let x1 = line[k - 2], y1 = line[k - 1], dx = line[k] - x1, dy = line[k + 1] - y1, len = dx * dx + dy * dy, t = len ? Math.max(0, Math.min(1, ((coords[i] - x1) * dx + (coords[i + 1] - y1) * dy) / len)) : 0;
within = Math.hypot(coords[i] - x1 - t * dx, coords[i + 1] - y1 - t * dy) <= limit;
}
if (!within) return !0;
}
return !1;
}
function distToPolyline(x, y, p) {
let best = 1 / 0;
for (let k = 2; k < p.length; k += 2) {
let x1 = p[k - 2], y1 = p[k - 1], dx = p[k] - x1, dy = p[k + 1] - y1, len = dx * dx + dy * dy, t = len ? Math.max(0, Math.min(1, ((x - x1) * dx + (y - y1) * dy) / len)) : 0;
best = Math.min(best, Math.hypot(x - x1 - t * dx, y - y1 - t * dy));
}
return best;
}
function buildTailConnector(st, m, clique) {
let t = m.plan.tail, p = m.pu, step = t.edges[t.side === "end" ? 0 : t.edges.length - 1], portLane = laneOf(st, p.edge, t.route), lane = laneOf(st, step.edge, t.route), tailPts = step.forward ? lane.points : reversed(lane.points), from = t.side === "end" ? p.end === "b" ? portLane.points : reversed(portLane.points) : tailPts, to = t.side === "end" ? tailPts : p.end === "a" ? portLane.points : reversed(portLane.points), made = connector(from, to, st.spacing);
made.coords.length < 4 || clique.push({ member: m, lateral: 0, own: made.coords, coords: made.coords, corner: made.corner });
}
function buildViaConnector(st, m, from, to) {
let centerline = [], length = 0, append = (pts) => {
for (let i = 0; i < pts.length; i += 2) {
let n = centerline.length;
n && Math.abs(centerline[n - 2] - pts[i]) < 1e-6 && Math.abs(centerline[n - 1] - pts[i + 1]) < 1e-6 || (n && (length += Math.hypot(pts[i] - centerline[n - 2], pts[i + 1] - centerline[n - 1])), centerline.push(pts[i], pts[i + 1]));
}
}, uPx = preparedPx(st, m.pu.edge), vPx = preparedPx(st, m.pv.edge), middles = [];
append(lastPortion(m.pu.end === "b" ? uPx : reversed(uPx), m.pu.end === "b" ? st.frontB[m.pu.edge] : st.frontA[m.pu.edge]));
for (let step of m.via) {
let before = length;
append(orientedPx(st, step.edge, step.forward)), middles.push((before + length) / 2);
}
append(firstPortion(m.pv.end === "a" ? vPx : reversed(vPx), m.pv.end === "a" ? st.frontA[m.pv.edge] : st.frontB[m.pv.edge]));
let knots = [];
if (m.forked) {
let total = length;
m.via.forEach((step, i) => knots.push(middles[i] / total, offsetTravel(st, step.edge, m.route, step.forward)));
let straight = (at) => m.lateral + (m.lateralOut - m.lateral) * at, steepest = (share2) => {
let at = 0, offset = m.lateral, most = 0;
for (let k = 0; k <= knots.length; k += 2) {
let next = k < knots.length ? knots[k] : 1, nextOffset = k < knots.length ? straight(next) + (knots[k + 1] - straight(next)) * share2 : m.lateralOut;
next > at && (most = Math.max(most, Math.abs(nextOffset - offset) / ((next - at) * total))), at = next, offset = nextOffset;
}
return most;
}, share = 1;
if (steepest(1) > MAX_SLIDE_SLOPE) {
let lo = 0, hi = 1;
for (let i = 0; i < 12; i++) {
let mid = (lo + hi) / 2;
steepest(mid) > MAX_SLIDE_SLOPE ? hi = mid : lo = mid;
}
share = lo;
}
for (let k = 0; k < knots.length; k += 2) knots[k + 1] = straight(knots[k]) + (knots[k + 1] - straight(knots[k])) * share;
}
let guide = st.smooth ? roundedPx(st, centerline, [m.pu.edge, m.pv.edge, ...m.via.map((s) => s.edge)]) : centerline, slide = offsetPolylineSlidingAnchored(guide, m.lateral, m.lateralOut, 4, knots);
if (slide.points.length < 4) return !1;
slide.points[0] = from[from.length - 2], slide.points[1] = from[from.length - 1], slide.points[slide.points.length - 2] = to[0], slide.points[slide.points.length - 1] = to[1];
let { points: coords, anchors } = removeLoopsAnchored(slide.points, slide.anchors, SNAP_HOOK_LANES * st.spacing);
return coords.length < 4 ? !1 : (st.connPaths.set(m.key, splitAtNodes(st, m.route, coords, anchors, memberSteps(m), m.pu.node, [m.pu.edge, m.pv.edge], !0)), !0);
}
function memberSteps(m) {
let t = m.plan?.tail;
if (t) {
let p = m.pu, step = t.edges[t.side === "end" ? 0 : t.edges.length - 1];
return t.side === "end" ? [{ edge: p.edge, forward: p.end === "b" }, step] : [step, { edge: p.edge, forward: p.end === "a" }];
}
return [{ edge: m.pu.edge, forward: m.pu.end === "b" }, ...m.via, { edge: m.pv.edge, forward: m.pv.end === "a" }];
}
function splitAtNodes(st, route, coords, anchors, steps, node, between, slide) {
let g = st.graph, cut = [], c = coords, a = anchors;
for (let k = 0; k + 1 < steps.length; k++) {
let [i, t] = nodeCut(st, c, a, steps[k], steps[k + 1], slide), head, headA;
if (t <= 0 || t >= 1) {
let at = t <= 0 ? i : i + 2;
head = c.slice(0, at + 2), headA = a.slice(0, at + 2), c = c.slice(at), a = a.slice(at);
} else {
let x = c[i] + (c[i + 2] - c[i]) * t, y = c[i + 1] + (c[i + 3] - c[i + 1]) * t, ax = a[i] + (a[i + 2] - a[i]) * t, ay = a[i + 1] + (a[i + 3] - a[i + 1]) * t;
head = c.slice(0, i + 2).concat(x, y), headA = a.slice(0, i + 2).concat(ax, ay), c = [x, y, ...c.slice(i + 2)], a = [ax, ay, ...a.slice(i + 2)];
}
cut.push({ c: head, a: headA, step: steps[k], length: polylineLength(head) });
}
cut.push({ c, a, step: steps[steps.length - 1], length: polylineLength(c) });
let kept = [], pending2 = [];
for (let p of cut) {
if (p.length < MIN_PIECE_PX) {
pending2.push(p);
continue;
}
for (let q of pending2.reverse())
p.c = q.c.concat(p.c.slice(2)), p.a = q.a.concat(p.a.slice(2));
pending2 = [], kept.push(p);
}
if (kept.length) {
let last = kept[kept.length - 1];
for (let q of pending2)
last.c = last.c.concat(q.c.slice(2)), last.a = last.a.concat(q.a.slice(2));
} else {
let longest = cut.reduce((x, y) => y.length > x.length ? y : x);
kept.push({ ...longest, c: coords, a: anchors });
}
return kept.map(({ c: c2, a: a2, step }) => {
let e = g.edges[step.edge];
return {
route,
look: lookOf(st, e, route),
coords: c2,
anchors: a2,
kind: "connector",
travel: travelSign(e.direction.get(route)) * (step.forward ? 1 : -1),
startDistance: 0,
edge: step.edge,
node,
between
};
});
}
function signedOffset(line, x, y) {
let best = 1 / 0, off = 0;
for (let i = 0; i + 3 < line.length; i += 2) {
let x1 = line[i], y1 = line[i + 1], dx = line[i + 2] - x1, dy = line[i + 3] - y1, l2 = dx * dx + dy * dy;
if (!l2) continue;
let t = Math.max(0, Math.min(1, ((x - x1) * dx + (y - y1) * dy) / l2)), d = Math.hypot(x - x1 - t * dx, y - y1 - t * dy);
d < best && (best = d, off = (dx * (y - y1) - dy * (x - x1)) / Math.sqrt(l2));
}
return off;
}
function nodeCut(st, c, a, from, to, slide) {
let e = st.graph.edges[from.edge], n = st.graph.nodes[from.forward ? e.b : e.a], nx = n.x * st.scale, ny = n.y * st.scale, din = endDirectionOver(orientedPx(st, from.edge, from.forward), st.spacing), dout = startDirectionOver(orientedPx(st, to.edge, to.forward), st.spacing), ux = din[0] + dout[0], uy = din[1] + dout[1], ul = Math.hypot(ux, uy), p = slide ? a : c, crossing = (shift) => {
let best2 = 1 / 0, bi2 = 0, bt2 = 0;
for (let i = 0; i + 3 < p.length; i += 2) {
let f0 = (p[i] - nx) * ux + (p[i + 1] - ny) * uy - shift, f1 = (p[i + 2] - nx) * ux + (p[i + 3] - ny) * uy - shift;
if (f0 < 0 == f1 < 0) continue;
let t = f0 / (f0 - f1), d = Math.hypot(c[i] + (c[i + 2] - c[i]) * t - nx, c[i + 1] + (c[i + 3] - c[i + 1]) * t - ny);
d < best2 && ([best2, bi2, bt2] = [d, i, t]);
}
return best2 < 1 / 0 ? [bi2, bt2] : null;
};
if (ul > 1e-6) {
let shift = 0;
if (!slide) {
let m = c.length, lu = signedOffset(orientedPx(st, from.edge, from.forward), c[0], c[1]), lv = signedOffset(orientedPx(st, to.edge, to.forward), c[m - 2], c[m - 1]), sin = din[0] * dout[1] - din[1] * dout[0], cos = din[0] * dout[0] + din[1] * dout[1], d = lu - lv;
Math.abs(sin) > 1e-9 && (shift = Math.max(-Math.abs(d) * ul, Math.min(Math.abs(d) * ul, d * (1 + cos) / sin)));
}
let hit = crossing(shift) ?? (shift ? crossing(0) : null);
if (hit) return hit;
}
let best = 1 / 0, bi = 0, bt = 0;
for (let i = 0; i + 3 < c.length; i += 2) {
let dx = c[i + 2] - c[i], dy = c[i + 3] - c[i + 1], len = dx * dx + dy * dy, t = len ? Math.max(0, Math.min(1, ((nx - c[i]) * dx + (ny - c[i + 1]) * dy) / len)) : 0, d = Math.hypot(c[i] + dx * t - nx, c[i + 1] + dy * t - ny);
d < best && ([best, bi, bt] = [d, i, t]);
}
return [bi, bt];
}
function buildJunctions(g, short, edgeLen, dirA, dirB, halfWidth) {
let N = g.nodes.length, parent = new Int32Array(N);
for (let n = 0; n < N; n++) parent[n] = n;
let find = (x) => {
for (; parent[x] !== x; ) x = parent[x] = parent[parent[x]];
return x;
};
for (let e of g.edges) short[e.id] && (parent[find(e.a)] = find(e.b));
let byRoot = /* @__PURE__ */ new Map(), junctionOf = new Array(N), portIndex = new Int32Array(2 * g.edges.length).fill(-1);
for (let n = 0; n < N; n++) {
let root = find(n), j = byRoot.get(root);
j || byRoot.set(root, j = { ports: [], transitions: [], tails: [], islands: [], edges: [] }), junctionOf[n] = j;
for (let p of g.nodes[n].ports)
j.edges.push(p.edge), !short[p.edge] && (portIndex[p.edge * 2 + (p.end === "a" ? 0 : 1)] = j.ports.length, j.ports.push({ edge: p.edge, end: p.end, node: n, dir: p.end === "a" ? dirA[p.edge] : dirB[p.edge], hw: halfWidth(g.edges[p.edge]) }));
}
let stack = [], onStack = new Uint8Array(g.edges.length), follow = (route, edge, entryNode) => {
let found = [], visit = (cur, curNode) => {
stack.push({ edge: cur, entryNode: curNode }), onStack[cur]++;
let e = g.edges[cur], far = e.a === curNode ? e.b : e.a, at = g.nodes[far], onward = !1, path = null;
for (let t2 of at.transitions) {
if (t2.route !== route || t2.from < 0 || t2.to < 0) continue;
let pa = at.ports[t2.from], pb = at.ports[t2.to], next = pa.edge === cur && pb.edge !== cur ? pb : pb.edge === cur && pa.edge !== cur ? pa : null;
next && (short[next.edge] && onStack[next.edge] || (onward = !0, short[next.edge] ? visit(next.edge, far) : found.push({ edge: next.edge, end: next.end, node: far, walked: path ?? (path = stack.slice()) })));
}
onward || found.push({ edge: -1, end: "a", node: far, walked: path ?? (path = stack.slice()) }), onStack[cur]--, stack.pop();
};
return visit(edge, entryNode), found;
}, lifted = /* @__PURE__ */ new Map(), tailsSeen = /* @__PURE__ */ new Set();
for (let node of g.nodes) {
let j = junctionOf[node.id], root = find(node.id);
for (let t of node.transitions) {
if (t.from < 0 || t.to < 0) continue;
let from = node.ports[t.from], to = node.ports[t.to];
if (!short[from.edge] && !short[to.edge]) {
let u = portIndex[from.edge * 2 + (from.end === "a" ? 0 : 1)], v = portIndex[to.edge * 2 + (to.end === "a" ? 0 : 1)];
u >= 0 && v >= 0 && j.transitions.push({ route: t.route, u, v, via: [] });
continue;
}
if (short[from.edge] && short[to.edge]) continue;
let inward = !short[from.edge], drawn = inward ? from : to, here = portIndex[drawn.edge * 2 + (drawn.end === "a" ? 0 : 1)];
if (!(here < 0))
for (let out of follow(t.route, (inward ? to : from).edge, node.id)) {
let steps = out.walked.map((w) => ({ edge: w.edge, forward: g.edges[w.edge].a === w.entryNode })), via = inward ? steps : steps.reverse().map((w) => ({ edge: w.edge, forward: !w.forward }));
if (out.edge < 0) {
let key2 = `${root}|${t.route}|${here}|${via.map((w) => w.edge).join(",")}`;
if (tailsSeen.has(key2)) continue;
tailsSeen.add(key2), j.tails.push({ route: t.route, port: here, side: inward ? "end" : "start", edges: via });
continue;
}
let there = portIndex[out.edge * 2 + (out.end === "a" ? 0 : 1)];
if (there < 0 || junctionOf[out.node] !== j) continue;
let key = `${root}|${t.route}|${Math.min(here, there)}|${Math.max(here, there)}`, length = via.reduce((sum, w) => sum + edgeLen[w.edge], 0), crossing = inward ? { route: t.route, u: here, v: there, via } : { route: t.route, u: there, v: here, via }, known = lifted.get(key);
if (known) {
length < known.length && (j.transitions[known.index] = crossing, known.length = length);
continue;
}
lifted.set(key, { index: j.transitions.length, length }), j.transitions.push(crossing);
}
}
}
let routeAt = /* @__PURE__ */ new Map(), routeIdx = (r) => {
let i = routeAt.get(r);
return i === void 0 && routeAt.set(r, i = routeAt.size), i;
};
for (let r of g.routes.keys()) routeIdx(r);
for (let r of g.chains.keys()) routeIdx(r);
for (let j of byRoot.values()) {
for (let t of j.transitions) routeIdx(t.route);
for (let t of j.tails) routeIdx(t.route);
}
let R = routeAt.size, covered = new Uint8Array(g.edges.length * R);
for (let j of byRoot.values()) {
for (let t of j.transitions) {
let r = routeAt.get(t.route);
for (let v of t.via) covered[v.edge * R + r] = 1;
}
for (let t of j.tails) {
let r = routeAt.get(t.route);
for (let v of t.edges) covered[v.edge * R + r] = 1;
}
}
let nodeOf = (s, start) => s.forward === start ? g.edges[s.edge].a : g.edges[s.edge].b, portJoinedTo = (j, route, node, edge) => {
let stems = /* @__PURE__ */ new Set(), n = g.nodes[node];
for (let t of n.transitions) {
if (t.route !== route || t.from < 0 || t.to < 0) continue;
let pa = n.ports[t.from], pb = n.ports[t.to];
pa.edge === edge && short[pb.edge] && stems.add(pb.edge), pb.edge === edge && short[pa.edge] && stems.add(pa.edge);
}
if (!stems.size) return -1;
for (let t of n.transitions) {
if (t.route !== route || t.from < 0 || t.to < 0) continue;
let pa = n.ports[t.from], pb = n.ports[t.to], drawn = stems.has(pb.edge) && !short[pa.edge] ? pa : stems.has(pa.edge) && !short[pb.edge] ? pb : null;
if (drawn && drawn.edge !== edge) return portIndex[drawn.edge * 2 + (drawn.end === "a" ? 0 : 1)];
}
return -1;
};
for (let [route, chains] of g.chains) {
let r = routeAt.get(route);
for (let chain of chains) {
let steps = chain.steps;
for (let i = 0; i < steps.length; i++) {
if (!short[steps[i].edge] || covered[steps[i].edge * R + r]) continue;
let k = i;
for (; k < steps.length && short[steps[k].edge] && !covered[steps[k].edge * R + r]; ) k++;
let run = steps.slice(i, k).map((s) => ({ edge: s.edge, forward: s.forward }));
for (let s of run) covered[s.edge * R + r] = 1;
let first = run[0], last = run[run.length - 1], j = junctionOf[nodeOf(first, !0)], u = portJoinedTo(j, route, nodeOf(first, !0), first.edge), v = portJoinedTo(j, route, nodeOf(last, !1), last.edge);
u >= 0 && v >= 0 && u !== v ? j.transitions.push({ route, u, v, via: run }) : u >= 0 ? j.tails.push({ route, port: u, side: "end", edges: run }) : v >= 0 ? j.tails.push({ route, port: v, side: "start", edges: run }) : j.islands.push({ route, steps: run }), i = k - 1;
}
}
}
return [...byRoot.values()];
}
function junctionFronts(g, junctions, laneOffsetTravel, spacing, routeIndex, routeCount) {
let need = new Float64Array(2 * g.edges.length), change = new Float64Array(2 * g.edges.length), continues = new Uint8Array(2 * g.edges.length * routeCount), markContinues = (p, route) => {
continues[(2 * p.edge + (p.end === "a" ? 0 : 1)) * routeCount + routeIndex.get(route)] = 1;
};
for (let j of junctions) {
let ports = j.ports, portNeed = new Float64Array(ports.length), active = new Uint8Array(ports.length);
for (let t of j.transitions)
active[t.u] = 1, active[t.v] = 1, markContinues(ports[t.u], t.route), markContinues(ports[t.v], t.route);
for (let t of j.tails)
active[t.port] = 1, markContinues(ports[t.port], t.route);
for (let i = 0; i < ports.length; i++)
if (active[i])
for (let k = 0; k < ports.length; k++) {
if (k === i || !active[k]) continue;
let cos = ports[i].dir[0] * ports[k].dir[0] + ports[i].dir[1] * ports[k].dir[1], sin = Math.sqrt(Math.max(0, 1 - cos * cos)), t;
sin < 1e-3 ? t = cos > 0 ? 6 * spacing : 0 : t = (ports[k].hw + ports[i].hw * cos) / sin, t = Math.max(0, t), t > 0 && (t += MIN_FRONT_MARGIN_LANES * spacing), portNeed[i] = Math.max(portNeed[i], Math.min(t, 8 * spacing));
}
let portChange = new Float64Array(ports.length);
for (let t of j.transitions) {
let u = ports[t.u], v = ports[t.v], oIn = laneOffsetTravel(g.edges[u.edge], t.route, u.end === "b"), oOut = laneOffsetTravel(g.edges[v.edge], t.route, v.end === "a"), shift = Math.abs(oIn - oOut);
if (shift < 1e-6) continue;
let len = Math.max(2.5 * shift, 3 * spacing);
portChange[t.u] = Math.max(portChange[t.u], len / 2), portChange[t.v] = Math.max(portChange[t.v], len / 2);
}
for (let i = 0; i < ports.length; i++) portNeed[i] = Math.max(portNeed[i], portChange[i]);
ports.forEach((p, i) => change[2 * p.edge + (p.end === "a" ? 0 : 1)] = portChange[i]);
for (let t of j.tails) {
let p = ports[t.port], first = t.edges[t.side === "end" ? 0 : t.edges.length - 1], oIn = laneOffsetTravel(g.edges[p.edge], t.route, p.end === "b"), oOut = laneOffsetTravel(g.edges[first.edge], t.route, first.forward), shift = Math.abs(oIn - oOut);
shift < 1e-6 || (portNeed[t.port] = Math.max(portNeed[t.port], Math.max(2.5 * shift, 3 * spacing) / 2));
}
ports.forEach((p, i) => need[2 * p.edge + (p.end === "a" ? 0 : 1)] = portNeed[i]);
}
return { need, change, continues };
}
function lastPortion(p, dist) {
let n = p.length / 2;
if (dist <= 0 || n < 2) return [p[p.length - 2], p[p.length - 1]];
let out = [], remaining = dist;
for (let i = n - 1; i > 0; i--) {
let ax = p[i * 2 - 2], ay = p[i * 2 - 1], bx = p[i * 2], by = p[i * 2 + 1], l = Math.hypot(bx - ax, by - ay);
if (out.unshift(bx, by), l >= remaining) {
let f = 1 - remaining / l;
return out.unshift(ax + (bx - ax) * f, ay + (by - ay) * f), out;
}
remaining -= l;
}
return out.unshift(p[0], p[1]), out;
}
function firstPortion(p, dist) {
return reversed(lastPortion(reversed(p), dist));
}
function travelSign(d) {
return d === 1 ? 1 : d === -1 ? -1 : 0;
}
function deriveCliqueConnectors(clique, spacing) {
let ref = clique[0], refLen = polylineLength(ref.own);
for (let c of clique) {
let len = polylineLength(c.own);
len > refLen && (ref = c, refLen = len);
}
if (ref.own.length <= 4 || refLen < CLIQUE_MIN_REF_LANES * spacing) return;
let turning = signedTurning(ref.own);
for (let c of clique) {
if (c === ref) continue;
let d = c.lateral - ref.lateral, expected = refLen + d * turning;
if (expected < 0.25 * refLen) continue;
let off = offsetPolyline(ref.own, d);
if (off.length < 4) continue;
let ratio = polylineLength(off) / expected;
if (ratio > 1.1 || ratio < 0.9) continue;
let gapStart = Math.hypot(off[0] - c.own[0], off[1] - c.own[1]), gapEnd = Math.hypot(off[off.length - 2] - c.own[c.own.length - 2], off[off.length - 1] - c.own[c.own.length - 1]);
gapStart > spacing / 2 || gapEnd > spacing / 2 || (off[0] = c.own[0], off[1] = c.own[1], off[off.length - 2] = c.own[c.own.length - 2], off[off.length - 1] = c.own[c.own.length - 1], c.coords = off);
}
}
function signedTurning(p) {
let total = 0;
for (let i = 4; i < p.length; i += 2) {
let ax = p[i - 2] - p[i - 4], ay = p[i - 1] - p[i - 3], bx = p[i] - p[i - 2], by = p[i + 1] - p[i - 1];
total += Math.atan2(ax * by - ay * bx, ax * bx + ay * by);
}
return total;
}
function connector(from, to, spacing, tpAt = null, tqAt = null) {
let P = [from[from.length - 2], from[from.length - 1]], Q = [to[0], to[1]], tp = tpAt ?? endDirectionOver(from, spacing / 2), tqIn = tqAt ?? startDirectionOver(to, spacing / 2), tq = [-tqIn[0], -tqIn[1]], chord = Math.hypot(Q[0] - P[0], Q[1] - P[1]);
if (chord < 1e-6) return { coords: [], corner: !1 };
if (Math.abs((Q[0] - P[0]) * tp[1] - (Q[1] - P[1]) * tp[0]) < 0.05 && tp[0] * tqIn[0] + tp[1] * tqIn[1] > 0.9999) return { coords: [P[0], P[1], Q[0], Q[1]], corner: !1 };
let corner = cornerTurn(P, tp, Q, tq, chord, spacing);
if (corner) return { coords: corner, corner: !0 };
let samples = Math.max(4, Math.min(32, Math.round(chord / Math.max(2, spacing / 3)))), coords = connectorCurve(P, tp, Q, tq, samples), ahead = (Q[0] - P[0]) * tp[0] + (Q[1] - P[1]) * tp[1], aheadBack = (P[0] - Q[0]) * tq[0] + (P[1] - Q[1]) * tq[1];
if (ahead < 0 || aheadBack < 0)
for (let scale = 0.5; scale > 0.1 && selfIntersects(coords); scale /= 2) coords = connectorCurve(P, tp, Q, tq, samples, scale);
return { coords, corner: !1 };
}
function cornerTurn(P, tp, Q, tq, chord, spacing) {
let I = intersectLines(P[0], P[1], P[0] + tp[0], P[1] + tp[1], Q[0], Q[1], Q[0] + tq[0], Q[1] + tq[1]);
if (!I) return null;
let t = (I[0] - P[0]) * tp[0] + (I[1] - P[1]) * tp[1], u = (I[0] - Q[0]) * tq[0] + (I[1] - Q[1]) * tq[1];
if (t <= 0.01 || u <= 0.01 || t + u > CORNER_MAX_REACH * chord || Math.acos(Math.max(-1, Math.min(1, -(tp[0] * tq[0] + tp[1] * tq[1])))) * 180 / Math.PI < CORNER_MIN_TURN_DEG) return null;
let L = Math.min(CORNER_RADIUS_LANES * spacing, 0.45 * t, 0.45 * u), A = [I[0] - tp[0] * L, I[1] - tp[1] * L], B = [I[0] - tq[0] * L, I[1] - tq[1] * L], out = [P[0], P[1], A[0], A[1]], steps = 8;
for (let i = 1; i < steps; i++) {
let s = i / steps, m = 1 - s;
out.push(m * m * A[0] + 2 * m * s * I[0] + s * s * B[0], m * m * A[1] + 2 * m * s * I[1] + s * s * B[1]);
}
return out.push(B[0], B[1], Q[0], Q[1]), out;
}
// src/render/tessellate.ts
function addPiece(pieces, first, count, edge) {
if (count <= 0) return;
let last = pieces[pieces.length - 1];
last && last[2] === edge && last[0] + last[1] === first ? last[1] += count : pieces.push([first, count, edge]);
}
function splitRanges(group, pieces, bright) {
if (!pieces.some((p) => bright.has(p[2]))) return { dimmed: group[1] ? [[group[0], group[1]]] : [], bright: [] };
let out = { dimmed: [], bright: [] };
for (let [first, count, edge] of pieces) {
let side = bright.has(edge) ? out.bright : out.dimmed, last = side[side.length - 1];
last && last[0] + last[1] === first ? last[1] += count : side.push([first, count]);
}
return out;
}
var MITER_LIMIT = 2, DEG_PER_TRIANGLE = 15, FLOATS_PER_VERTEX = 9, MeshBuilder = class {
constructor(vertexCapacity, indexCapacity) {
__publicField(this, "v");
__publicField(this, "c");
__publicField(this, "i");
__publicField(this, "nv", 0);
__publicField(this, "ni", 0);
this.v = new Float32Array(vertexCapacity * FLOATS_PER_VERTEX), this.c = new Uint8Array(vertexCapacity * 4), this.i = new Uint32Array(indexCapacity);
}
reset() {
this.nv = 0, this.ni = 0;
}
reserve(vertices, indices) {
for (; (this.nv + vertices) * FLOATS_PER_VERTEX > this.v.length; ) this.growV();
for (; this.ni + indices > this.i.length; ) this.growI();
}
growV() {
let v = new Float32Array(this.v.length * 2);
v.set(this.v), this.v = v;
let c = new Uint8Array(this.c.length * 2);
c.set(this.c), this.c = c;
}
growI() {
let i = new Uint32Array(this.i.length * 2);
i.set(this.i), this.i = i;
}
vertex(ax, ay, dx, dy, ex, ey, nx, ny, s, color) {
(this.nv + 1) * FLOATS_PER_VERTEX > this.v.length && this.growV();
let o = this.nv * FLOATS_PER_VERTEX;
this.v[o] = ax, this.v[o + 1] = ay, this.v[o + 2] = dx, this.v[o + 3] = dy, this.v[o + 4] = ex, this.v[o + 5] = ey, this.v[o + 6] = nx, this.v[o + 7] = ny, this.v[o + 8] = s;
let co = this.nv * 4;
return this.c[co] = color[0], this.c[co + 1] = color[1], this.c[co + 2] = color[2], this.c[co + 3] = color[3], this.nv++;
}
tri(a, b, c) {
this.ni + 3 > this.i.length && this.growI(), this.i[this.ni++] = a, this.i[this.ni++] = b, this.i[this.ni++] = c;
}
quad(a1, a2, b1, b2) {
this.tri(a1, a2, b1), this.tri(a2, b2, b1);
}
};
function normalizeColor(css) {
let ctx = typeof OffscreenCanvas < "u" ? new OffscreenCanvas(1, 1).getContext("2d", { willReadFrequently: !0 }) : typeof document < "u" ? document.createElement("canvas").getContext("2d", { willReadFrequently: !0 }) : null;
if (!ctx) return null;
ctx.fillStyle = "#000000", ctx.fillStyle = css;
let a = ctx.fillStyle;
if (ctx.fillStyle = "#ffffff", ctx.fillStyle = css, a !== ctx.fillStyle || typeof a != "string") return null;
if (/^(#|rgba?\()/i.test(a)) return a;
ctx.clearRect(0, 0, 1, 1), ctx.fillRect(0, 0, 1, 1);
let [r, g, bl, al] = ctx.getImageData(0, 0, 1, 1).data;
return `rgba(${r}, ${g}, ${bl}, ${al / 255})`;
}
function parseColor(css, normalized = !1) {
let out = new Uint8Array([136, 136, 136, 255]), hex = css.trim(), m = /^#([0-9a-f]{3,8})$/i.exec(hex);
if (m) {
let h = m[1];
return h.length === 3 || h.length === 4 ? (out[0] = parseInt(h[0] + h[0], 16), out[1] = parseInt(h[1] + h[1], 16), out[2] = parseInt(h[2] + h[2], 16), out[3] = h.length === 4 ? parseInt(h[3] + h[3], 16) : 255) : (h.length === 6 || h.length === 8) && (out[0] = parseInt(h.slice(0, 2), 16), out[1] = parseInt(h.slice(2, 4), 16), out[2] = parseInt(h.slice(4, 6), 16), out[3] = h.length === 8 ? parseInt(h.slice(6, 8), 16) : 255), out;
}
let named = {
black: "#000000",
white: "#ffffff",
red: "#ff0000",
green: "#008000",
blue: "#0000ff",
yellow: "#ffff00",
orange: "#ffa500",
purple: "#800080",
gray: "#808080",
grey: "#808080",
silver: "#c0c0c0",
navy: "#000080",
magenta: "#ff00ff",
fuchsia: "#ff00ff",
lime: "#00ff00",
brown: "#a52a2a",
teal: "#008080",
maroon: "#800000"
};
if (named[hex.toLowerCase()]) return parseColor(named[hex.toLowerCase()]);
let rgb = /^rgba?\(([^)]+)\)$/i.exec(hex);
if (rgb) {
let parts = rgb[1].split(/[\s,/]+/).filter((s) => s.length);
for (let i = 0; i < 3 && i < parts.length; i++) {
let v = parts[i].endsWith("%") ? parseFloat(parts[i]) * 255 / 100 : parseFloat(parts[i]);
out[i] = Math.round(Math.max(0, Math.min(255, v || 0)));
}
if (parts.length > 3) {
let a = parts[3].endsWith("%") ? parseFloat(parts[3]) / 100 : parseFloat(parts[3]);
out[3] = Math.round(Math.max(0, Math.min(1, a)) * 255);
}
return out;
}
let norm = normalized ? null : normalizeColor(hex);
return norm ? parseColor(norm, !0) : out;
}
var TessellateCache = class {
constructor() {
/** null marks a path met once: its triangles are kept from the second build on. */
__publicField(this, "chunks", /* @__PURE__ */ new WeakMap());
__publicField(this, "out", null);
__publicField(this, "key", "");
}
clear() {
this.chunks = /* @__PURE__ */ new WeakMap(), this.out = null, this.key = "";
}
/** @internal */
builderFor(opts, estimate) {
let key = `${opts.scale}|${opts.origin[0]}|${opts.origin[1]}|${opts.unitsPerMercator ?? 1}`;
return key !== this.key && (this.chunks = /* @__PURE__ */ new WeakMap(), this.key = key), this.out || (this.out = new MeshBuilder(Math.max(64, estimate * 3), Math.max(192, estimate * 9))), this.out.reset(), this.out;
}
/** @internal */
emit(b, p, color, opts, before = null, after = null) {
let hit = this.chunks.get(p), seams = seamKey(before, after);
if (hit && hit.startDistance === p.startDistance && hit.color === p.look.color && hit.seams === seams) {
appendChunk(b, hit);
return;
}
let nv = b.nv, ni = b.ni;
if (tessellatePath(b, p.coords, p.anchors, color, p.startDistance, opts, before, after), hit === void 0) {
this.chunks.set(p, null);
return;
}
let indices = new Uint32Array(b.ni - ni);
for (let k = 0; k < indices.length; k++) indices[k] = b.i[ni + k] - nv;
this.chunks.set(p, {
vertices: b.v.slice(nv * FLOATS_PER_VERTEX, b.nv * FLOATS_PER_VERTEX),
colors: b.c.slice(nv * 4, b.nv * 4),
indices,
vertexCount: b.nv - nv,
startDistance: p.startDistance,
color: p.look.color,
seams
});
}
};
function appendChunk(b, chunk) {
b.reserve(chunk.vertexCount, chunk.indices.length), b.v.set(chunk.vertices, b.nv * FLOATS_PER_VERTEX), b.c.set(chunk.colors, b.nv * 4);
let base = b.nv;
for (let k = 0; k < chunk.indices.length; k++) b.i[b.ni + k] = chunk.indices[k] + base;
b.nv += chunk.vertexCount, b.ni += chunk.indices.length;
}
function tessellate(paths, opts) {
let est = 0;
for (let p of paths) est += p.coords.length;
let cache2 = opts.cache ?? null, b = cache2 ? cache2.builderFor(opts, est) : new MeshBuilder(Math.max(64, est * 3), Math.max(192, est * 9)), colorCache = /* @__PURE__ */ new Map(), groups = [], groupRoutes = [], groupLooks = [], groupDots = [], groupPieces = [], groupDotPieces = [], byRoute = /* @__PURE__ */ new Map();
for (let p of paths) {
let byLook = byRoute.get(p.route);
byLook || byRoute.set(p.route, byLook = /* @__PURE__ */ new Map());
let l = byLook.get(p.look);
l || byLook.set(p.look, l = []), l.push(p);
}
let order = opts.drawOrder ?? [...byRoute.keys()];
for (let rid of order) {
let byLook = byRoute.get(rid);
if (byLook)
for (let [look, list] of byLook) {
let start = b.ni, c = colorCache.get(look.color);
c || colorCache.set(look.color, c = parseColor(look.color));
let pieces = [];
for (let k = 0; k < list.length; k++) {
let p = list[k], from = b.ni, before = k > 0 ? seamDirection(list[k - 1], p, !0) : null, after = k + 1 < list.length ? seamDirection(p, list[k + 1], !1) : null;
cache2 ? cache2.emit(b, p, c, opts, before, after) : tessellatePath(b, p.coords, p.anchors, c, p.startDistance, opts, before, after), addPiece(pieces, from, b.ni - from, p.edge);
}
if (b.ni > start) {
groups.push([start, b.ni - start]), groupRoutes.push(rid), groupLooks.push(look), groupPieces.push(pieces);
let dots = b.ni, dotPieces = [];
if (opts.width && look.dash && look.dash[0] === 0 && look.dash[1] > 0)
for (let p of list) {
let from = b.ni;
dotsOnPath(b, p.coords, p.anchors, c, p.startDistance, look.dash[1] * opts.width, opts), addPiece(dotPieces, from, b.ni - from, p.edge);
}
groupDots.push([dots, b.ni - dots]), groupDotPieces.push(dotPieces);
}
}
}
return {
vertices: b.v.subarray(0, b.nv * FLOATS_PER_VERTEX),
colors: b.c.subarray(0, b.nv * 4),
indices: b.i.subarray(0, b.ni),
vertexCount: b.nv,
indexCount: b.ni,
groups,
groupRoutes,
groupLooks,
groupDots,
groupPieces,
groupDotPieces
};
}
function dotsOnPath(b, px, anchorsPx, color, startDistance, period, opts) {
let n = px.length / 2;
if (n < 2) return;
let total = 0;
for (let i = 1; i < n; i++) total += Math.hypot(px[i * 2] - px[i * 2 - 2], px[i * 2 + 1] - px[i * 2 - 1]);
if (total <= 0) return;
let back = startDistance < 0, s0 = Math.abs(startDistance), lo = back ? s0 - total : s0, { scale, origin } = opts, upm = opts.unitsPerMercator ?? 1, seg = 1, before = 0, len = Math.hypot(px[2] - px[0], px[3] - px[1]), first = Math.ceil((lo - period / 2) / period), count = Math.max(0, Math.ceil((lo + total - period / 2) / period) - first);
for (let k = 0; k < count; k++) {
let center = period / 2 + (back ? first + count - 1 - k : first + k) * period, at = back ? s0 - center : center - s0;
for (; seg < n - 1 && at > before + len; )
before += len, seg++, len = Math.hypot(px[seg * 2] - px[seg * 2 - 2], px[seg * 2 + 1] - px[seg * 2 - 1]);
let t = len > 0 ? Math.max(0, Math.min(1, (at - before) / len)) : 0, i = (seg - 1) * 2, j = seg * 2, x = px[i] + (px[j] - px[i]) * t, y = px[i + 1] + (px[j + 1] - px[i + 1]) * t, gx = anchorsPx[i] + (anchorsPx[j] - anchorsPx[i]) * t, gy = anchorsPx[i + 1] + (anchorsPx[j + 1] - anchorsPx[i + 1]) * t, ax = (gx / scale - origin[0]) * upm, ay = (gy / scale - origin[1]) * upm, v0 = b.vertex(ax, ay, x - gx, y - gy, -1, -1, -1, -1, center, color), v1 = b.vertex(ax, ay, x - gx, y - gy, 1, -1, 1, -1, center, color), v2 = b.vertex(ax, ay, x - gx, y - gy, 1, 1, 1, 1, center, color), v3 = b.vertex(ax, ay, x - gx, y - gy, -1, 1, -1, 1, center, color);
b.tri(v0, v1, v2), b.tri(v0, v2, v3);
}
}
function seamKey(before, after) {
return `${before ? before.join() : ""}|${after ? after.join() : ""}`;
}
function seamDirection(p, q, last) {
if (p.kind !== "connector" || q.kind !== "connector" || p.between !== q.between || p.route !== q.route) return null;
let a = p.coords, c = q.coords, n = a.length;
if (n < 4 || c.length < 4 || a[n - 2] !== c[0] || a[n - 1] !== c[1]) return null;
if (last) {
let i = n - 4;
for (; i > 0 && Math.abs(a[i] - a[n - 2]) < 1e-6 && Math.abs(a[i + 1] - a[n - 1]) < 1e-6; ) i -= 2;
let dx2 = a[n - 2] - a[i], dy2 = a[n - 1] - a[i + 1], l2 = Math.hypot(dx2, dy2);
return l2 < 1e-6 ? null : [dx2 / l2, dy2 / l2];
}
let j = 2;
for (; j + 2 < c.length && Math.abs(c[j] - c[0]) < 1e-6 && Math.abs(c[j + 1] - c[1]) < 1e-6; ) j += 2;
let dx = c[j] - c[0], dy = c[j + 1] - c[1], l = Math.hypot(dx, dy);
return l < 1e-6 ? null : [dx / l, dy / l];
}
function tessellatePath(b, px, anchorsPx, color, startDistance, opts, before = null, after = null) {
let pts = [], anc = [];
for (let i = 0; i < px.length; i += 2) {
let n2 = pts.length;
n2 >= 2 && Math.abs(pts[n2 - 2] - px[i]) < 1e-6 && Math.abs(pts[n2 - 1] - px[i + 1]) < 1e-6 || (pts.push(px[i], px[i + 1]), anc.push(anchorsPx[i], anchorsPx[i + 1]));
}
let n = pts.length / 2;
if (n < 2) return;
let { scale, origin } = opts, upm = opts.unitsPerMercator ?? 1, AX = (i) => (anc[i * 2] / scale - origin[0]) * upm, AY = (i) => (anc[i * 2 + 1] / scale - origin[1]) * upm, DX = (i) => pts[i * 2] - anc[i * 2], DY = (i) => pts[i * 2 + 1] - anc[i * 2 + 1], along = new Float64Array(n);
for (let i = 1; i < n; i++) along[i] = along[i - 1] + Math.hypot(pts[i * 2] - pts[i * 2 - 2], pts[i * 2 + 1] - pts[i * 2 - 1]);
let S = (i) => startDistance < 0 ? -startDistance - along[i] : startDistance + along[i], lastL = -1, lastR = -1, pair = (i, ex, ey, nx, ny, connect) => {
let ax = AX(i), ay = AY(i), dx = DX(i), dy = DY(i), s = S(i), l = b.vertex(ax, ay, dx, dy, ex, ey, nx, ny, s, color), r = b.vertex(ax, ay, dx, dy, -ex, -ey, -nx, -ny, s, color);
connect && lastL >= 0 && b.quad(lastL, lastR, l, r), lastL = l, lastR = r;
}, fan = (i, fromX, fromY, toX, toY, ccwOnScreen) => {
let ax = AX(i), ay = AY(i), dx = DX(i), dy = DY(i), s = S(i), c = b.vertex(ax, ay, dx, dy, 0, 0, 0, 0, s, color), a0 = Math.atan2(fromY, fromX), da = Math.atan2(toY, toX) - a0;
for (; da > Math.PI; ) da -= 2 * Math.PI;
for (; da < -Math.PI; ) da += 2 * Math.PI;
Math.abs(Math.abs(da) - Math.PI) < 1e-6 && (da = ccwOnScreen ? -Math.PI : Math.PI);
let steps = Math.max(1, Math.ceil(Math.abs(da) * 180 / Math.PI / DEG_PER_TRIANGLE)), prev = b.vertex(ax, ay, dx, dy, fromX, fromY, fromX, fromY, s, color);
for (let k = 1; k <= steps; k++) {
let a = a0 + da * k / steps, vx = Math.cos(a), vy = Math.sin(a), cur = b.vertex(ax, ay, dx, dy, vx, vy, vx, vy, s, color);
b.tri(c, prev, cur), prev = cur;
}
}, sdx = new Float64Array(n - 1), sdy = new Float64Array(n - 1);
for (let i = 0; i < n - 1; i++) {
let dx = pts[i * 2 + 2] - pts[i * 2], dy = pts[i * 2 + 3] - pts[i * 2 + 1], l = Math.hypot(dx, dy) || 1;
sdx[i] = dx / l, sdy[i] = dy / l;
}
for (let i = 0; i < n; i++) {
let hasPrev = i > 0 || !!before, hasNext = i < n - 1 || !!after, dPrevX = i > 0 ? sdx[i - 1] : before ? before[0] : 0, dPrevY = i > 0 ? sdy[i - 1] : before ? before[1] : 0, dNextX = i < n - 1 ? sdx[i] : after ? after[0] : 0, dNextY = i < n - 1 ? sdy[i] : after ? after[1] : 0, nPrevX = dPrevY, nPrevY = -dPrevX, nNextX = dNextY, nNextY = -dNextX;
if (!hasPrev) {
fan(i, nNextX, nNextY, -nNextX, -nNextY, !0), pair(i, nNextX, nNextY, nNextX, nNextY, !1);
continue;
}
if (!hasNext) {
pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), fan(i, nPrevX, nPrevY, -nPrevX, -nPrevY, !1);
continue;
}
let seamEnd = i === n - 1, seamStart = i === 0, jx = nPrevX + nNextX, jy = nPrevY + nNextY, jl = Math.hypot(jx, jy);
if (jl < 1e-9) {
seamStart || (pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), fan(i, nPrevX, nPrevY, -nPrevX, -nPrevY, !1)), seamEnd || pair(i, nNextX, nNextY, nNextX, nNextY, !1);
continue;
}
jx /= jl, jy /= jl;
let cosHalf = jx * nNextX + jy * nNextY, miterLen = cosHalf > 1e-6 ? 1 / cosHalf : 1 / 0;
if (miterLen <= MITER_LIMIT)
pair(i, jx * miterLen, jy * miterLen, jx, jy, !0);
else {
let outsideLeft = dPrevX * dNextY - dPrevY * dNextX > 0;
seamStart || (pair(i, nPrevX, nPrevY, nPrevX, nPrevY, !0), outsideLeft ? fan(i, nPrevX, nPrevY, nNextX, nNextY, !1) : fan(i, -nPrevX, -nPrevY, -nNextX, -nNextY, !0)), seamEnd || pair(i, nNextX, nNextY, nNextX, nNextY, !1);
}
}
}
// src/render/layer.ts
var VERTEX_SHADER_BODY = `
in vec2 a_anchor;
in vec2 a_delta;
in vec2 a_extrude;
in vec2 a_normal;
in float a_along;
in vec4 a_color;
uniform float u_units_per_px;
uniform float u_outset;
out vec2 v_normal;
out vec4 v_color;
out float v_along;
out float v_depth;
void main() {
v_along = a_along;
float thickness = projectLineThickness(a_anchor.y);
vec2 p = a_anchor + (a_delta + a_extrude * u_outset) * (u_units_per_px * thickness);
gl_Position = projectTile(p);
v_depth = gl_Position.z / gl_Position.w;
v_normal = a_normal;
v_color = a_color;
}`, FRAGMENT_SHADER_BODY = `
in vec2 v_normal;
in vec4 v_color;
in float v_along;
in float v_depth;
uniform float u_outset;
uniform float u_blur;
uniform vec4 u_override;
uniform float u_opacity;
uniform vec2 u_dash;
uniform float u_cap;
uniform float u_along_scale;
uniform float u_cover;
out vec4 fragColor;
void main() {
#ifdef GLOBE
if (v_depth > 1.0) discard;
#endif
float dist = length(v_normal) * u_outset;
float alpha = clamp((u_outset - dist) / u_blur, 0.0, 1.0);
if (u_dash.y > 0.0) {
if (u_dash.x > 0.0) {
float period = u_dash.x + u_dash.y;
float t = mod(v_along, period);
if (u_cap < 0.5) {
float edge = min(t, u_dash.x - t) * u_along_scale;
alpha *= clamp(edge / u_blur + 0.5, 0.0, 1.0);
} else {
float r = u_outset - 0.5 * u_blur;
float best = 1e9;
for (int k = -1; k <= 1; k++) {
float tk = t - float(k) * period;
float c = clamp(tk, 0.0, u_dash.x);
best = min(best, length(vec2((tk - c) * u_along_scale, dist)) - r);
}
alpha *= clamp(-best / u_blur + 0.5, 0.0, 1.0);
}
} else {
float period = u_dash.y;
float t = mod(v_along, period) - period * 0.5;
float r = u_outset - 0.5 * u_blur;
float d = length(vec2(t * u_along_scale, dist));
alpha = clamp((r - d) / u_blur + 0.5, 0.0, 1.0);
}
}
if (u_cover > 0.5) {
if (u_cover < 1.5) {
if (alpha < 1.0) discard;
} else if (u_cover < 2.5) {
if (alpha <= 0.0 || alpha >= 1.0) discard;
} else if (alpha < 0.5) discard;
}
vec4 c = u_override.a < 0.0 ? v_color : u_override;
fragColor = vec4(c.rgb, 1.0) * (c.a * alpha * u_opacity);
}`, DEPTH_GAP = 1 / 65536, DEPTH_CLEAR = 4 / 8, DEPTH_MARK = 3 / 8, DEPTH_FILL = 2 / 8, DEPTH_FILL_OVER = 1 / 8, offscreens = /* @__PURE__ */ new WeakMap(), COMPOSITE_VERTEX_SHADER = `#version 300 es
void main() {
vec2 p = vec2(gl_VertexID == 1 ? 3.0 : -1.0, gl_VertexID == 2 ? 3.0 : -1.0);
gl_Position = vec4(p, 0.0, 1.0);
}`, COMPOSITE_FRAGMENT_SHADER = `#version 300 es
precision highp float;
uniform sampler2D u_color;
out vec4 fragColor;
void main() {
vec4 c = texelFetch(u_color, ivec2(gl_FragCoord.xy), 0);
if (c.a == 0.0) discard;
fragColor = c;
}`, COVER_ALL = 0, COVER_FULL = 1, COVER_PARTIAL = 2, COVER_HALF = 3;
function widthAt(w, zoom) {
return typeof w == "function" ? w(zoom) : w;
}
var LaneLayer = class {
constructor(opts) {
__publicField(this, "id");
__publicField(this, "type", "custom");
__publicField(this, "renderingMode", "2d");
__publicField(this, "map", null);
__publicField(this, "gl", null);
/** Per projection variant; null for one that failed to build, so it is not tried every frame. */
__publicField(this, "programs", /* @__PURE__ */ new Map());
__publicField(this, "vbo", null);
__publicField(this, "cbo", null);
__publicField(this, "ibo", null);
__publicField(this, "mesh", null);
/** Materialized from `packed` on demand. */
__publicField(this, "layout", null);
/** A worker's answer, kept as typed arrays until something asks for paths. */
__publicField(this, "packed", null);
__publicField(this, "built", null);
__publicField(this, "inFlight", null);
__publicField(this, "session", nextSession++);
__publicField(this, "sentGraph", !1);
__publicField(this, "looksDirty", !0);
__publicField(this, "layoutCache", new LayoutCache());
__publicField(this, "meshCache", new TessellateCache());
/**
* A tile the size of the graph, at its northwest corner. Anchors are in
* its local units, so float32 keeps sub-pixel precision at high zoom.
*/
__publicField(this, "tile", { z: 0, x: 0, y: 0 });
__publicField(this, "origin", [0, 0]);
__publicField(this, "unitsPerMercator", EXTENT);
/**
* What the uploaded mesh and the last build were made from. After `setGraph` the old
* mesh keeps drawing until the new build lands, so it needs its own tile, and queries
* on the old layout need the old graph's edges.
*/
__publicField(this, "builtWith", null);
__publicField(this, "dirty", !0);
__publicField(this, "graph");
__publicField(this, "sizes");
__publicField(this, "casing");
__publicField(this, "opacity");
__publicField(this, "zoomEpsilon");
__publicField(this, "smooth");
__publicField(this, "openFolds");
__publicField(this, "laneStyle");
__publicField(this, "cull");
__publicField(this, "cullMargin");
__publicField(this, "useWorker");
__publicField(this, "onBuild");
__publicField(this, "builds", 0);
__publicField(this, "fullFeatures", null);
/** By cache key, so repeat calls share one request. */
__publicField(this, "fullPending", /* @__PURE__ */ new Map());
/** Bumped by every setter a full-extent answer depends on, so one asked before it is not kept. */
__publicField(this, "generation", 0);
__publicField(this, "highlight", []);
__publicField(this, "highlightStyle", null);
/** Each group's bright split, kept until the mesh or the highlight changes. */
__publicField(this, "brightSplit", null);
__publicField(this, "timings", { layoutMs: 0, meshMs: 0, renderThreadMs: 0 });
/** The depth MapLibre gave this layer for the frame being drawn. */
__publicField(this, "depthBase", 1 - DEPTH_GAP);
/** The layer's index in the style when `depthBase` was read, or -1. */
__publicField(this, "depthPlace", -1);
if (this.id = opts.id, this.graph = opts.graph, !opts.graph || !Array.isArray(opts.graph.edges)) throw new TypeError("maplibre-gl-lanes: `graph` must be a line graph from `buildLineGraph`");
requireSizesFunction(opts.sizes), this.sizes = opts.sizes, this.opacity = Math.max(0, Math.min(1, opts.opacity ?? 1)), this.zoomEpsilon = opts.zoomEpsilon ?? 0.25, this.smooth = opts.smooth ?? !0, this.openFolds = opts.openFolds ?? !0, this.laneStyle = opts.laneStyle ?? null, this.cull = opts.cull ?? !0, this.cullMargin = opts.cullMargin ?? 0.5, this.useWorker = opts.worker ?? !0, this.onBuild = opts.onBuild ?? null;
let casingCss = opts.casingColor === void 0 ? "#333333" : opts.casingColor;
this.casing = casingCss === null ? null : rgba(parseColor(casingCss)), this.computeOrigin();
}
/** Replace the graph (e.g. after re-ordering or filtering routes). */
setGraph(graph) {
this.graph = graph, this.generation++, this.layoutCache.clear(), this.meshCache.clear(), this.fullFeatures = null, this.fullPending.clear(), this.closeSession(), this.session = nextSession++, this.sentGraph = !1, this.looksDirty = !0, this.computeOrigin(), this.dirty = !0, this.map?.triggerRepaint();
}
/** Change the sizes per zoom (see `LaneLayerOptions.sizes`). */
setSizes(sizes) {
requireSizesFunction(sizes), this.sizes = sizes, this.generation++, this.fullFeatures = null, this.fullPending.clear(), this.dirty = !0, this.map?.triggerRepaint();
}
/** Change or remove the per-edge styling (see `LaneLayerOptions.laneStyle`). */
setLaneStyle(laneStyle) {
this.laneStyle = laneStyle, this.generation++, this.layoutCache.clear(), this.meshCache.clear(), this.fullFeatures = null, this.fullPending.clear(), this.looksDirty = !0, this.dirty = !0, this.map?.triggerRepaint();
}
/** Change the opacity of the whole layer, 0 to 1, without a rebuild. */
setOpacity(opacity) {
this.opacity = Math.max(0, Math.min(1, opacity)), this.map?.triggerRepaint();
}
/** Change the casing color (see `LaneLayerOptions.casingColor`); null removes the casing. */
setCasingColor(css) {
this.casing = css === null ? null : rgba(parseColor(css)), this.map?.triggerRepaint();
}
/**
* Lift one route, or several: their lanes are drawn last, with a halo
* and an outline, and the rest can be dimmed. It draws inside this
* layer, so layers above it cover it. Pass null, or an empty list, to
* clear.
*/
setHighlight(route, style = {}) {
this.highlight = route === null ? [] : typeof route == "string" ? [route] : [...route], this.highlightStyle = this.highlight.length === 0 ? null : {
halo: style.halo === null ? null : rgba(parseColor(style.halo ?? "#ffb700")),
haloWidth: style.haloWidth ?? 4,
haloBlur: style.haloBlur ?? 3,
outline: style.outline === null ? null : rgba(parseColor(style.outline ?? "#000000")),
outlineWidth: style.outlineWidth ?? 1.5,
dim: style.dim ?? 1,
bright: new Set(style.bright ?? [])
}, this.map?.triggerRepaint();
}
/** The highlighted routes, in the order they were given; empty when none. */
getHighlight() {
return [...this.highlight];
}
/**
* What the last build covers, without its geometry. Cheap enough to call
* every frame, unlike `getLayout`.
*/
getBuildInfo() {
let l = this.layout ?? this.packed;
return l ? { build: this.builds, zoom: l.zoom, bounds: l.bounds, stats: l.stats, timings: this.timings } : null;
}
/**
* Listen for finished builds; refresh sources derived from
* `laneFeatures` here, not on `idle`, which can arrive before a worker
* build. One listener, which this replaces; null clears it.
*/
setOnBuild(listener) {
this.onBuild = listener;
}
/**
* The lane geometry of the last build, in world pixels at `layout.zoom`.
* The first call after a worker build unpacks it, so do not call it
* every frame.
*/
getLayout() {
if (this.layout) return this.layout;
let p = this.packed;
return p ? (this.layout = {
zoom: p.zoom,
scale: p.scale,
paths: unpackPaths(p.paths),
drawOrder: p.drawOrder,
bounds: p.bounds,
mergedEdges: p.mergedEdges,
stats: p.stats
}, this.layout) : null;
}
/**
* Lane geometry as GeoJSON LineStrings, one per lane piece, with
* properties `route`, `name`, `color`, `direction`, `kind`, `edge`,
* `lanes`, `routes` and the graph's `uniformProperties` (see
* docs/api.md). Lane positions depend on the zoom and on the build,
* so refresh on `moveend` and from `setOnBuild`.
*/
laneFeatures(opts = {}) {
if (opts.extent === "full") return this.fullLaneFeatures(opts);
let layout = this.getLayout(), features = [];
if (!layout) return { type: "FeatureCollection", features };
let z = opts.zoom ?? this.map?.getZoom() ?? layout.zoom, only = opts.routes ? new Set(opts.routes) : null, { scale } = layout, nowScale = 512 * Math.pow(2, z);
for (let p of layout.paths) {
if (only && !only.has(p.route)) continue;
let coords = [];
for (let i = 0; i < p.coords.length; i += 2) {
let x = (p.anchors[i] + (p.coords[i] - p.anchors[i]) * (scale / nowScale)) / scale, y = (p.anchors[i + 1] + (p.coords[i + 1] - p.anchors[i + 1]) * (scale / nowScale)) / scale;
coords.push([x * 360 - 180, Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI]);
}
coords.length < 2 || features.push(this.laneFeature(p, coords, this.builtWith?.graph ?? this.graph));
}
return { type: "FeatureCollection", features };
}
/**
* `laneFeatures` with `extent: 'full'` laid out in the worker. Without a
* worker, or for the built extent, it resolves with `laneFeatures`.
*/
laneFeaturesAsync(opts = {}) {
if (opts.extent !== "full" || !this.useWorker) return Promise.resolve(this.laneFeatures(opts));
let z = opts.zoom ?? this.map?.getZoom() ?? this.built?.zoom ?? 0, routes = opts.routes ? [...opts.routes].sort() : null, key = `${z}|${routes ? routes.join("\0") : "*"}`, cached = this.fullFeatures;
if (cached && cached.graph === this.graph && cached.key === key) return Promise.resolve(cached.fc);
let waiting = this.fullPending.get(key);
if (waiting) return waiting;
let wanted = this.requestFullFeatures(z, routes, key);
this.fullPending.set(key, wanted);
let settle2 = () => {
this.fullPending.get(key) === wanted && this.fullPending.delete(key);
};
return wanted.then(settle2, settle2), wanted;
}
async requestFullFeatures(z, routes, key) {
let graph = this.graph, generation = this.generation;
for (let attempt = 0; attempt < 2; attempt++) {
let req = this.layoutRequest(z, null, "full", routes), sent = sendToWorker(req);
if (!sent) {
this.unsent(req);
break;
}
let res = await sent;
if (res.needGraph) {
this.sentGraph = !1;
continue;
}
if (res.error) {
console.warn("maplibre-gl-lanes: lane features in the worker failed, building on this thread:", res.error);
break;
}
if (res.session !== this.session || graph !== this.graph || generation !== this.generation) {
graph = this.graph, generation = this.generation;
continue;
}
let fc = this.featureCollection(unpackPaths(res.paths), res.scale, graph);
return this.fullFeatures = { graph, key, fc }, fc;
}
return this.fullLaneFeatures({ zoom: z, routes: routes ?? void 0, extent: "full" });
}
laneFeature(p, coords, graph) {
let meta = graph.routes.get(p.route), edge = p.edge, e = graph.edges[edge];
p.travel === -1 && coords.reverse();
let properties = {
...e?.properties,
route: p.route,
name: meta?.name ?? p.route,
color: p.look.color,
direction: p.travel === 0 ? 0 : 1,
kind: p.kind,
edge,
lanes: e?.routes.length ?? 1,
routes: e ? (e.order.length === e.routes.length ? e.order : e.routes).slice() : [p.route]
};
return { type: "Feature", geometry: { type: "LineString", coordinates: coords }, properties };
}
fullLaneFeatures(opts) {
let z = opts.zoom ?? this.map?.getZoom() ?? this.built?.zoom ?? 0, routes = opts.routes ? [...opts.routes].sort() : null, key = `${z}|${routes ? routes.join("\0") : "*"}`, cached = this.fullFeatures;
if (cached && cached.graph === this.graph && cached.key === key) return cached.fc;
let layout = layoutAtZoom(this.graph, z, this.sizes, { smooth: this.smooth, openFolds: this.openFolds, routes: routes ?? void 0, laneStyle: this.laneStyle ?? void 0 }), fc = this.featureCollection(layout.paths, layout.scale, this.graph);
return this.fullFeatures = { graph: this.graph, key, fc }, fc;
}
featureCollection(paths, scale, graph) {
let features = [];
for (let p of paths) {
let coords = [];
for (let i = 0; i < p.coords.length; i += 2) {
let x = p.coords[i] / scale, y = p.coords[i + 1] / scale;
coords.push([x * 360 - 180, Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI]);
}
coords.length < 2 || features.push(this.laneFeature(p, coords, graph));
}
return { type: "FeatureCollection", features };
}
/**
* The lane nearest to a screen point, within `tolerancePx` (default 6),
* or null. Only the last build is searched.
*/
queryLane(point, tolerancePx = 6) {
if (!this.map) return null;
let lngLat = this.map.unproject([point.x, point.y]);
return this.queryLaneAt([lngLat.lng, lngLat.lat], this.map.getZoom(), tolerancePx);
}
/** `queryLane` for a geographic point, with the zoom that sets the pixel tolerance. */
queryLaneAt(lngLat, zoom, tolerancePx = 6) {
let layout = this.getLayout();
if (!layout) return null;
let merc = lngLatToMercator(lngLat[0], lngLat[1]), nowScale = 512 * Math.pow(2, zoom), px = [merc[0] * nowScale, merc[1] * nowScale], ratio = layout.scale / nowScale, best = null, bestD2 = tolerancePx * tolerancePx, bestX = 0, bestY = 0;
for (let p of layout.paths) {
let c = p.coords, a = p.anchors, prevX = 0, prevY = 0;
for (let i = 0; i < c.length; i += 2) {
let x = a[i] / ratio + (c[i] - a[i]), y = a[i + 1] / ratio + (c[i + 1] - a[i + 1]);
if (i > 0) {
let [d2, cx, cy] = segNearest(px[0], px[1], prevX, prevY, x, y);
d2 < bestD2 && (bestD2 = d2, best = p, bestX = cx, bestY = cy);
}
prevX = x, prevY = y;
}
}
if (!best) return null;
let edgeId = best.edge, graph = this.builtWith?.graph ?? this.graph, e = graph.edges[edgeId];
return {
route: best.route,
name: graph.routes.get(best.route)?.name,
distancePx: Math.sqrt(bestD2),
lngLat: mercatorToLngLat(bestX / nowScale, bestY / nowScale),
kind: best.kind,
edge: edgeId,
routes: e ? (e.order.length === e.routes.length ? e.order : e.routes).slice() : [best.route],
properties: e?.properties ?? {}
};
}
dashColor(css) {
let c = dashColorCache.get(css);
return c || dashColorCache.set(css, c = rgba(parseColor(css))), c;
}
computeOrigin() {
let minX = 1 / 0, minY = 1 / 0, maxX = -1 / 0, maxY = -1 / 0;
for (let node of this.graph.nodes)
node.x < minX && (minX = node.x), node.x > maxX && (maxX = node.x), node.y < minY && (minY = node.y), node.y > maxY && (maxY = node.y);
if (!Number.isFinite(minX)) {
this.tile = { z: 0, x: 0, y: 0 }, this.origin = [0, 0], this.unitsPerMercator = EXTENT;
return;
}
let span = Math.max(maxX - minX, maxY - minY), z = span > 0 ? Math.max(0, Math.min(22, Math.floor(-Math.log2(span)))) : 22, n = Math.pow(2, z);
this.tile = { z, x: Math.min(n - 1, Math.floor(minX * n)), y: Math.min(n - 1, Math.floor(minY * n)) }, this.origin = [this.tile.x / n, this.tile.y / n], this.unitsPerMercator = EXTENT * n;
}
onAdd(map, anyGl) {
if (!isWebGL2(anyGl)) {
console.error("maplibre-gl-lanes: this map has a WebGL1 context; the lane layer needs WebGL2 and will not draw."), this.map = map;
return;
}
let gl = anyGl;
this.map = map, this.gl = gl;
let share = offscreens.get(gl);
if (share) share.users++;
else {
let made = { users: 1, target: null, composite: void 0, onLost: () => {
made.target = null, made.composite = void 0;
} };
offscreens.set(gl, made), gl.canvas.addEventListener?.("webglcontextlost", made.onLost);
}
map.getTerrain() && console.warn("maplibre-gl-lanes: 3D terrain is enabled; lanes are drawn at sea level and will be hidden under raised terrain."), this.vbo = gl.createBuffer(), this.cbo = gl.createBuffer(), this.ibo = gl.createBuffer(), this.dirty = !0;
}
onRemove(_map, anyGl) {
let gl = this.gl;
if (!gl) {
this.map = null;
return;
}
for (let p of this.programs.values())
p && (gl.deleteProgram(p.program), gl.deleteVertexArray(p.vao));
this.programs.clear();
for (let b of [this.vbo, this.cbo, this.ibo]) b && gl.deleteBuffer(b);
this.vbo = this.cbo = this.ibo = null;
let share = offscreens.get(gl);
share && --share.users <= 0 && (share.target && releaseOffscreen(gl, share.target), share.composite && (gl.deleteProgram(share.composite.program), gl.deleteVertexArray(share.composite.vao)), gl.canvas.removeEventListener?.("webglcontextlost", share.onLost), offscreens.delete(gl)), this.layoutCache.clear(), this.meshCache.clear(), this.closeSession(), this.mesh = null, this.map = null, this.gl = null;
}
/** A failure is logged once and draws nothing, rather than throwing every frame. */
programFor(gl, shaderData) {
let name = shaderData.variantName;
if (this.programs.has(name)) return this.programs.get(name);
let entry = null;
try {
entry = this.buildProgram(gl, shaderData);
} catch (err) {
console.error(`maplibre-gl-lanes: lanes will not draw in the ${name} projection:`, err);
}
return this.programs.set(name, entry), entry;
}
buildProgram(gl, shaderData) {
let vsSource = `#version 300 es
precision highp float;
${shaderData.vertexShaderPrelude}
${shaderData.define}
${VERTEX_SHADER_BODY}`, fsSource = `#version 300 es
precision highp float;
${shaderData.define}
${FRAGMENT_SHADER_BODY}`, vs = compile(gl, gl.VERTEX_SHADER, vsSource), fs = compile(gl, gl.FRAGMENT_SHADER, fsSource), program = gl.createProgram();
if (gl.attachShader(program, vs), gl.attachShader(program, fs), gl.linkProgram(program), gl.deleteShader(vs), gl.deleteShader(fs), !gl.getProgramParameter(program, gl.LINK_STATUS)) {
let log = gl.getProgramInfoLog(program);
throw gl.deleteProgram(program), new Error(`program link failed: ${log}`);
}
let uniforms = {};
for (let u of [
"u_units_per_px",
"u_outset",
"u_blur",
"u_override",
"u_opacity",
"u_dash",
"u_cap",
"u_along_scale",
"u_cover",
"u_projection_matrix",
"u_projection_tile_mercator_coords",
"u_projection_clipping_plane",
"u_projection_transition",
"u_projection_fallback_matrix"
])
uniforms[u] = gl.getUniformLocation(program, u);
let vao = gl.createVertexArray();
gl.bindVertexArray(vao), gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
let stride = FLOATS_PER_VERTEX * 4, attribs = [["a_anchor", 0, 2], ["a_delta", 8, 2], ["a_extrude", 16, 2], ["a_normal", 24, 2], ["a_along", 32, 1]];
for (let [name, offset, size] of attribs) {
let loc = gl.getAttribLocation(program, name);
loc < 0 || (gl.enableVertexAttribArray(loc), gl.vertexAttribPointer(loc, size, gl.FLOAT, !1, stride, offset));
}
let aCol = gl.getAttribLocation(program, "a_color");
return gl.bindBuffer(gl.ARRAY_BUFFER, this.cbo), gl.enableVertexAttribArray(aCol), gl.vertexAttribPointer(aCol, 4, gl.UNSIGNED_BYTE, !0, 4, 0), gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.ibo), gl.bindVertexArray(null), { program, vao, uniforms };
}
viewBounds() {
if (!this.cull || !this.map) return null;
let b = this.map.getBounds(), sw = lngLatToMercator(b.getWest(), b.getSouth()), ne = lngLatToMercator(b.getEast(), b.getNorth()), minX = Math.min(sw[0], ne[0]), maxX = Math.max(sw[0], ne[0]), minY = Math.min(sw[1], ne[1]), maxY = Math.max(sw[1], ne[1]), mx = (maxX - minX) * this.cullMargin, my = (maxY - minY) * this.cullMargin;
return { minX: minX - mx, minY: minY - my, maxX: maxX + mx, maxY: maxY + my };
}
viewInside(built) {
if (!built) return !0;
let b = this.map.getBounds(), sw = lngLatToMercator(b.getWest(), b.getSouth()), ne = lngLatToMercator(b.getEast(), b.getNorth());
return Math.min(sw[0], ne[0]) >= built.minX && Math.max(sw[0], ne[0]) <= built.maxX && Math.min(sw[1], ne[1]) >= built.minY && Math.max(sw[1], ne[1]) <= built.maxY;
}
serves(build, zoom) {
let dz = zoom - build.zoom;
return dz >= -this.zoomEpsilon && dz <= 2 * this.zoomEpsilon && this.viewInside(build.bounds);
}
/**
* Only one build is ever in flight: a pan that outruns the worker asks
* again once its answer lands, rather than queueing a request per frame.
*/
rebuild(zoom) {
if (this.inFlight) return;
let bounds = this.viewBounds();
if (this.useWorker && this.sendLayout(zoom, bounds)) {
this.dirty = !1;
return;
}
let t0 = performance.now(), layout = layoutAtZoom(this.graph, zoom, this.sizes, { bounds, smooth: this.smooth, openFolds: this.openFolds, laneStyle: this.laneStyle ?? void 0, cache: this.layoutCache }), t1 = performance.now(), mesh = tessellate(layout.paths, { scale: layout.scale, origin: this.origin, unitsPerMercator: this.unitsPerMercator, drawOrder: layout.drawOrder, width: checkedSizes(this.sizes, zoom).width, cache: this.meshCache }), t2 = performance.now();
this.upload(mesh), this.layout = layout, this.packed = null, this.built = { zoom, bounds }, this.dirty = !1, this.timings = { layoutMs: t1 - t0, meshMs: t2 - t1, renderThreadMs: performance.now() - t0 }, this.finished();
}
layoutRequest(zoom, bounds, extent, routes) {
let req = {
kind: "layout",
id: nextRequestId(),
session: this.session,
zoom,
style: checkedSizes(this.sizes, zoom),
smooth: this.smooth,
openFolds: this.openFolds,
bounds,
extent
};
return routes && (req.routes = routes), this.sentGraph || (req.graph = toTransfer(this.graph), req.origin = this.origin, req.unitsPerMercator = this.unitsPerMercator, this.looksDirty = !0, this.sentGraph = !0), this.looksDirty && (req.looks = this.lookTable(), this.looksDirty = !1), req;
}
unsent(req) {
req.graph && (this.sentGraph = !1), req.looks !== void 0 && (this.looksDirty = !0);
}
sendLayout(zoom, bounds) {
let req = this.layoutRequest(zoom, bounds, "built"), sent = sendToWorker(req);
return sent ? (this.inFlight = { id: req.id }, sent.then((res) => this.onLayout(res)), !0) : (this.unsent(req), this.useWorker = !1, !1);
}
onLayout(res) {
if (!this.inFlight || res.id !== this.inFlight.id) return;
if (this.inFlight = null, res.session !== this.session) {
this.dirty = !0, this.map?.triggerRepaint();
return;
}
if (res.needGraph) {
this.sentGraph = !1, this.dirty = !0, this.map?.triggerRepaint();
return;
}
if (res.error) {
console.warn("maplibre-gl-lanes: layout in the worker failed, building on the main thread:", res.error), this.useWorker = !1, this.dirty = !0, this.map?.triggerRepaint();
return;
}
if (this.dirty) {
this.map?.triggerRepaint();
return;
}
if (!this.gl) return;
let t0 = performance.now();
this.upload(res), this.packed = res, this.layout = null, this.built = { zoom: res.zoom, bounds: res.bounds }, this.timings = { layoutMs: res.layoutMs, meshMs: res.meshMs, renderThreadMs: performance.now() - t0 }, this.finished(), this.map?.triggerRepaint();
}
/** The listener runs in a microtask, never inside the render call. */
finished() {
this.builds++;
let listener = this.onBuild;
if (!listener) return;
let info = this.getBuildInfo();
queueMicrotask(() => {
this.map && listener(info);
});
}
/** In the worker's reading order: edges, then each edge's routes. */
lookTable() {
let laneStyle = this.laneStyle;
if (!laneStyle) return null;
let out = [];
for (let e of this.graph.edges) for (let r of e.routes) out.push(laneStyle(e, r) ?? null);
return out;
}
closeSession() {
this.fullPending.clear(), this.inFlight = null, this.sentGraph && (this.sentGraph = !1, sendToWorker({ kind: "dispose", id: nextRequestId(), session: this.session }));
}
upload(mesh) {
let gl = this.gl;
gl.bindVertexArray(null), gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo), gl.bufferData(gl.ARRAY_BUFFER, mesh.vertices, gl.DYNAMIC_DRAW), gl.bindBuffer(gl.ARRAY_BUFFER, this.cbo), gl.bufferData(gl.ARRAY_BUFFER, mesh.colors, gl.DYNAMIC_DRAW), gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.ibo), gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh.indices, gl.DYNAMIC_DRAW), this.mesh = mesh, this.builtWith = { graph: this.graph, tile: this.tile, unitsPerMercator: this.unitsPerMercator };
}
render(anyGl, args) {
let gl = this.gl;
if (!this.map || !this.vbo || !gl) return;
let zoom = this.map.getZoom();
(this.dirty || !this.built || !this.serves(this.built, zoom)) && this.rebuild(zoom);
let mesh = this.mesh, frame = this.builtWith;
if (!mesh || !mesh.indexCount || !frame) return;
let entry = this.programFor(gl, args.shaderData);
if (!entry) return;
let { program, vao, uniforms } = entry, tileID = { canonical: frame.tile, wrap: 0 }, pd = args.getProjectionData ? args.getProjectionData({ tileID, applyGlobeMatrix: !0 }) : this.map.transform.getProjectionData({ overscaledTileID: tileID, applyGlobeMatrix: !0 }), dpr = this.map.getPixelRatio(), style = checkedSizes(this.sizes, zoom), built = this.built ? this.built.zoom : zoom, dashStyle = built === zoom ? style : checkedSizes(this.sizes, built), alongScale = Math.pow(2, zoom - built), unitsPerPx = frame.unitsPerMercator / (512 * Math.pow(2, zoom));
gl.useProgram(program), gl.bindVertexArray(vao), gl.uniformMatrix4fv(uniforms.u_projection_matrix, !1, pd.mainMatrix), gl.uniformMatrix4fv(uniforms.u_projection_fallback_matrix, !1, pd.fallbackMatrix), gl.uniform4f(uniforms.u_projection_tile_mercator_coords, ...pd.tileMercatorCoords), gl.uniform4f(uniforms.u_projection_clipping_plane, ...pd.clippingPlane), gl.uniform1f(uniforms.u_projection_transition, pd.projectionTransition), gl.uniform1f(uniforms.u_units_per_px, unitsPerPx), gl.uniform1f(uniforms.u_along_scale, alongScale), gl.uniform1f(uniforms.u_blur, 1 / dpr), gl.uniform1f(uniforms.u_opacity, this.opacity), gl.uniform1f(uniforms.u_cover, COVER_ALL);
let place = this.map.getLayersOrder ? this.map.getLayersOrder().indexOf(this.id) : -1;
if (place < 0 || place !== this.depthPlace) {
let range = gl.getParameter(gl.DEPTH_RANGE);
this.depthBase = range ? range[0] : 1 - DEPTH_GAP, this.depthPlace = place;
}
this.depthAt(gl, 0), gl.enable(gl.DEPTH_TEST), gl.depthFunc(gl.LEQUAL), gl.depthMask(!1), gl.disable(gl.STENCIL_TEST), gl.disable(gl.CULL_FACE), gl.enable(gl.BLEND), gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
let aa = 0.5 / dpr;
gl.uniform2f(uniforms.u_dash, 0, 0), gl.uniform1f(uniforms.u_cap, 0);
let runs = [];
for (let gi = 0; gi < mesh.groupRoutes.length; ) {
let route = mesh.groupRoutes[gi], run = [];
for (; gi < mesh.groupRoutes.length && mesh.groupRoutes[gi] === route; )
mesh.groups[gi][1] && run.push(gi), gi++;
run.length && runs.push(run);
}
let hl = this.highlightStyle, liftedRuns = [], lifted = /* @__PURE__ */ new Set();
if (hl)
for (let route of this.highlight) {
let run = runs.find((r) => mesh.groupRoutes[r[0]] === route);
if (run) {
liftedRuns.push(run);
for (let gi of run) lifted.add(gi);
}
}
let dimmed = !!hl && hl.dim < 1, translucent = this.opacity < 1 || dimmed, once = !!this.casing && (this.casing[3] < 1 || translucent), marks = once || translucent, offscreen = marks ? acquireOffscreen(gl) : null;
offscreen || (once = marks = !1);
let mapFramebuffer = null;
offscreen && (mapFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING), gl.bindFramebuffer(gl.FRAMEBUFFER, offscreen.target.framebuffer), gl.clearColor(0, 0, 0, 0), gl.clearDepth(1), gl.depthMask(!0), gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT), gl.depthMask(!1));
let split = dimmed && hl.bright.size > 0 ? this.splitFor(mesh, hl) : null, restOpacity = dimmed ? this.opacity * hl.dim : this.opacity, opacities = split ? { dimmed: restOpacity, bright: this.opacity, split } : null;
dimmed && gl.uniform1f(uniforms.u_opacity, restOpacity);
for (let run of runs)
lifted.has(run[0]) || this.drawRoute(gl, uniforms, run, style, dashStyle, aa, once, marks, restOpacity, opacities);
if (hl && liftedRuns.length) {
gl.uniform1f(uniforms.u_opacity, this.opacity);
let outlineEdge = style.width / 2 + style.casingWidth + widthAt(hl.outlineWidth, zoom), lift = () => {
for (let gi of lifted) gl.drawElements(gl.TRIANGLES, mesh.groups[gi][1], gl.UNSIGNED_INT, mesh.groups[gi][0] * 4);
if (once) {
gl.depthFunc(gl.ALWAYS), gl.depthMask(!0), this.depthAt(gl, DEPTH_CLEAR), gl.colorMask(!1, !1, !1, !1);
for (let gi of lifted) gl.drawElements(gl.TRIANGLES, mesh.groups[gi][1], gl.UNSIGNED_INT, mesh.groups[gi][0] * 4);
gl.colorMask(!0, !0, !0, !0), gl.depthMask(!1), gl.depthFunc(gl.LEQUAL), this.depthAt(gl, 0);
}
};
hl.halo && (gl.uniform1f(uniforms.u_blur, Math.max(1 / dpr, widthAt(hl.haloBlur, zoom))), gl.uniform1f(uniforms.u_outset, outlineEdge + widthAt(hl.haloWidth, zoom) + aa), gl.uniform4fv(uniforms.u_override, hl.halo), lift(), gl.uniform1f(uniforms.u_blur, 1 / dpr)), hl.outline && (gl.uniform1f(uniforms.u_outset, outlineEdge + aa), gl.uniform4fv(uniforms.u_override, hl.outline), lift());
for (let run of liftedRuns) this.drawRoute(gl, uniforms, run, style, dashStyle, aa, once, marks, this.opacity);
}
offscreen && (gl.invalidateFramebuffer(gl.FRAMEBUFFER, [gl.DEPTH_ATTACHMENT]), gl.bindFramebuffer(gl.FRAMEBUFFER, mapFramebuffer), gl.useProgram(offscreen.composite.program), gl.bindVertexArray(offscreen.composite.vao), gl.activeTexture(gl.TEXTURE0), gl.bindTexture(gl.TEXTURE_2D, offscreen.target.color), gl.uniform1i(offscreen.composite.color, 0), gl.depthFunc(gl.LEQUAL), gl.depthMask(!1), this.depthAt(gl, 0), gl.drawArrays(gl.TRIANGLES, 0, 3)), gl.depthFunc(gl.LEQUAL), gl.depthMask(!1), gl.depthRange(this.depthBase, this.depthBase), gl.bindVertexArray(null);
}
/** Draw at an offset behind this layer's depth, in units of the gap (see `DEPTH_GAP`). */
depthAt(gl, offset) {
let d = this.depthBase + offset * DEPTH_GAP;
gl.depthRange(d, d);
}
/** The bright split of every group, worked out once per mesh and highlight. */
splitFor(mesh, hl) {
let cached = this.brightSplit;
if (cached && cached.mesh === mesh && cached.style === hl) return cached.groups;
let groups = [];
for (let gi = 0; gi < mesh.groups.length; gi++) {
let ribbon = splitRanges(mesh.groups[gi], mesh.groupPieces[gi], hl.bright), dots = splitRanges(mesh.groupDots[gi], mesh.groupDotPieces[gi], hl.bright);
groups.push(ribbon.bright.length || dots.bright.length ? { dimmed: ribbon.dimmed, bright: ribbon.bright, dotsDimmed: dots.dimmed, dotsBright: dots.bright } : null);
}
return this.brightSplit = { mesh, style: hl, groups }, groups;
}
/**
* Every casing before any fill, or a group's casing would seam over its
* neighbor's fill. `dashStyle` is in the mesh's build pixels.
*
* With `opacities`, the pieces on bright edges draw at full opacity in
* the same passes as the rest of the route, so they keep its place in
* the drawing order and its once-only casing. Their casings go after
* the dimmed ones: where a bright cap reaches into a dimmed neighbor,
* the neighbor's own casing already holds the mark, so a full-strength
* casing never shows through the neighbor's translucent fill. Their
* fills go last, so they cover the dimmed caps that reach into them.
*
* A translucent fill paints each pixel once (`DEPTH_FILL`), over all of
* one side's groups, and the mark is cleared only after them, so a
* connector meeting a lane of another look counts as one too. The groups
* go last first, since the first full fragment keeps its pixel, so the
* one on top stays the one on top.
*/
drawRoute(gl, uniforms, run, style, dashStyle, aa, once, marks, opacity, opacities = null) {
let mesh = this.mesh, meta = (this.builtWith?.graph ?? this.graph).routes.get(mesh.groupRoutes[run[0]]), periodOf = (look) => look.dash ? [look.dash[0] * dashStyle.width, look.dash[1] * dashStyle.width] : [0, 0], split = opacities ? opacities.split : null, ribbon = (gi, pass) => {
let sp = split && split[gi];
return sp ? pass === "bright" ? sp.bright : sp.dimmed : pass === "bright" ? [] : [mesh.groups[gi]];
}, dotRanges = (gi, pass) => {
let sp = split && split[gi];
return sp ? pass === "bright" ? sp.dotsBright : sp.dotsDimmed : pass === "bright" ? [] : [mesh.groupDots[gi]];
}, drawAll = (ranges) => {
for (let [first, count] of ranges) count && gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_INT, first * 4);
}, draw = (gi, pass) => drawAll(ribbon(gi, pass)), drawDashes = (gi, look, pass) => {
let dots = mesh.groupDots[gi];
if (look.dash[0] === 0 && dots && dots[1]) {
drawAll(dotRanges(gi, pass));
return;
}
let period = periodOf(look);
gl.uniform2f(uniforms.u_dash, period[0], period[1]), draw(gi, pass), gl.uniform2f(uniforms.u_dash, 0, 0);
}, lit = !!split && run.some((gi) => split[gi]), passes = lit ? ["dimmed", "bright"] : ["all"], setOpacity = (pass) => {
lit && gl.uniform1f(uniforms.u_opacity, pass === "bright" ? opacities.bright : opacities.dimmed);
};
if (this.casing && meta?.casing !== !1) {
gl.uniform1f(uniforms.u_outset, style.width / 2 + style.casingWidth + aa), gl.uniform4fv(uniforms.u_override, this.casing);
for (let pass of passes) for (let gi of run) {
if (pass === "bright" && !split[gi]) continue;
setOpacity(pass);
let look = mesh.groupLooks[gi], drawCasing = !!look.dash && look.dash[0] === 0 && !look.dashColor ? () => drawDashes(gi, look, pass) : () => draw(gi, pass);
once ? (gl.depthFunc(gl.LESS), this.depthAt(gl, DEPTH_MARK), gl.depthMask(!0), gl.uniform1f(uniforms.u_cover, COVER_FULL), drawCasing(), gl.depthMask(!1), gl.uniform1f(uniforms.u_cover, COVER_PARTIAL), drawCasing(), gl.uniform1f(uniforms.u_cover, COVER_ALL)) : drawCasing();
}
}
once && (gl.depthFunc(gl.LEQUAL), this.depthAt(gl, 0)), gl.uniform1f(uniforms.u_outset, style.width / 2 + aa);
let fillPasses = lit ? ["dimmed", "bright"] : ["all"];
for (let pass of fillPasses) {
let groups = pass === "bright" ? run.filter((gi) => split[gi]) : run, paintOnce = marks && (pass === "all" ? opacity : pass === "bright" ? opacities.bright : opacities.dimmed) < 1, fill = (paint, depth) => {
if (!paintOnce) {
paint();
return;
}
gl.depthFunc(gl.LESS), this.depthAt(gl, depth), gl.depthMask(!0), gl.uniform1f(uniforms.u_cover, COVER_FULL), paint(), gl.depthMask(!1), gl.uniform1f(uniforms.u_cover, COVER_PARTIAL), paint(), gl.uniform1f(uniforms.u_cover, COVER_ALL);
};
setOpacity(pass);
for (let gi of paintOnce ? [...groups].reverse() : groups) {
let look = mesh.groupLooks[gi], dash = look.dash;
gl.uniform1f(uniforms.u_cap, look.dashCap === "round" ? 1 : 0), dash && look.dashColor && paintOnce ? (gl.depthFunc(gl.LESS), this.depthAt(gl, DEPTH_FILL), gl.depthMask(!0), gl.uniform1f(uniforms.u_cover, COVER_FULL), gl.uniform4f(uniforms.u_override, 0, 0, 0, -1), drawDashes(gi, look, pass), gl.uniform4fv(uniforms.u_override, this.dashColor(look.dashColor)), fill(() => draw(gi, pass), DEPTH_FILL), this.depthAt(gl, DEPTH_FILL_OVER), gl.uniform1f(uniforms.u_cover, COVER_PARTIAL), gl.uniform4f(uniforms.u_override, 0, 0, 0, -1), drawDashes(gi, look, pass), gl.uniform1f(uniforms.u_cover, COVER_ALL)) : dash && look.dashColor ? (gl.uniform4fv(uniforms.u_override, this.dashColor(look.dashColor)), draw(gi, pass), gl.uniform4f(uniforms.u_override, 0, 0, 0, -1), drawDashes(gi, look, pass)) : dash ? (gl.uniform4f(uniforms.u_override, 0, 0, 0, -1), fill(() => drawDashes(gi, look, pass), DEPTH_FILL)) : (gl.uniform4f(uniforms.u_override, 0, 0, 0, -1), fill(() => draw(gi, pass), DEPTH_FILL));
}
if (once || paintOnce) {
gl.depthFunc(gl.ALWAYS), gl.colorMask(!1, !1, !1, !1), gl.depthMask(!0), this.depthAt(gl, DEPTH_CLEAR), gl.uniform1f(uniforms.u_cover, COVER_HALF);
for (let gi of groups) {
let look = mesh.groupLooks[gi];
look.dash && !look.dashColor ? drawDashes(gi, look, pass) : draw(gi, pass);
}
gl.uniform1f(uniforms.u_cover, COVER_ALL), gl.depthMask(!1), gl.colorMask(!0, !0, !0, !0), gl.depthFunc(gl.LEQUAL), this.depthAt(gl, 0);
}
}
lit && gl.uniform1f(uniforms.u_opacity, opacities.dimmed);
}
}, EXTENT = 8192, nextSession = 1, dashColorCache = /* @__PURE__ */ new Map();
function segNearest(px, py, ax, ay, bx, by) {
let dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy, t = l2 > 0 ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / l2)) : 0, x = ax + dx * t, y = ay + dy * t;
return [(px - x) * (px - x) + (py - y) * (py - y), x, y];
}
function isWebGL2(gl) {
return typeof gl.createVertexArray == "function";
}
function acquireOffscreen(gl) {
let share = offscreens.get(gl);
if (!share) return null;
let width = gl.drawingBufferWidth, height = gl.drawingBufferHeight, target = share.target, stale = target && (target.width !== width || target.height !== height);
return target && stale && (releaseOffscreen(gl, target), target = share.target = null), target || (target = share.target = createOffscreen(gl, width, height)), share.composite === void 0 && (share.composite = buildComposite(gl)), target && share.composite ? { target, composite: share.composite } : null;
}
function createOffscreen(gl, width, height) {
let color = gl.createTexture(), depth = gl.createRenderbuffer(), framebuffer = gl.createFramebuffer();
if (!color || !depth || !framebuffer) return null;
gl.bindTexture(gl.TEXTURE_2D, color), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE), gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null), gl.bindRenderbuffer(gl.RENDERBUFFER, depth), gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT24, width, height);
let bound = gl.getParameter(gl.FRAMEBUFFER_BINDING);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer), gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, color, 0), gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
let complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
gl.bindFramebuffer(gl.FRAMEBUFFER, bound);
let target = { framebuffer, color, depth, width, height };
return complete ? target : (releaseOffscreen(gl, target), null);
}
function releaseOffscreen(gl, target) {
gl.deleteFramebuffer(target.framebuffer), gl.deleteTexture(target.color), gl.deleteRenderbuffer(target.depth);
}
function buildComposite(gl) {
try {
let program = gl.createProgram();
if (gl.attachShader(program, compile(gl, gl.VERTEX_SHADER, COMPOSITE_VERTEX_SHADER)), gl.attachShader(program, compile(gl, gl.FRAGMENT_SHADER, COMPOSITE_FRAGMENT_SHADER)), gl.linkProgram(program), !gl.getProgramParameter(program, gl.LINK_STATUS))
return gl.deleteProgram(program), null;
let vao = gl.createVertexArray();
return { program, vao, color: gl.getUniformLocation(program, "u_color") };
} catch {
return null;
}
}
function rgba(c) {
return new Float32Array([c[0] / 255, c[1] / 255, c[2] / 255, c[3] / 255]);
}
function compile(gl, type, src) {
let s = gl.createShader(type);
if (gl.shaderSource(s, src), gl.compileShader(s), !gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
let log = gl.getShaderInfoLog(s);
throw gl.deleteShader(s), new Error(`shader compile failed: ${log}`);
}
return s;
}
export {
LaneLayer,
LayoutCache,
applyLaneOrders,
buildLineGraph,
disposeWorkers,
filterGraph,
layoutAtZoom,
lngLatToMercator,
mercatorToLngLat,
orderLanes,
orderLanesAsync,
seedFromSnapshot,
snapshotLaneOrders,
stabilizeLanes
};