// ============================================================================= (function () { 'use strict'; const R_EARTH = 6371000, RAD = Math.PI / 180; const hav = (la1, lo1, la2, lo2) => { const dLa = (la2 - la1) * RAD, dLo = (lo2 - lo1) * RAD; const a = Math.sin(dLa / 2) ** 2 + Math.cos(la1 * RAD) * Math.cos(la2 * RAD) * Math.sin(dLo / 2) ** 2; return 2 * R_EARTH * Math.asin(Math.sqrt(a)); }; // ---- Réglages ------------------------------------------------------------ const CFG = { DENSIFY_M: 25, // pas max entre deux sommets (permet de se brancher au milieu d'une voie) JOIN_TOL_M: 10, // tolérance de raccord entre extrémités de tronçons JOIN_PENALTY_M: 20, // pénalité de raccord (décourage les faux raccords entre voies parallèles) WP_SNAP_MAX_M: 700, // distance max gare -> voie CORRIDOR_DEG: 0.08, // marge autour de chaque tronçon gare->gare (~9 km) OFF_LINE_COST: 1.4, // coût multiplié pour les lignes absentes de la marche VS_COST: 6, // coût multiplié pour les voies de service MAX_EXPANSIONS: 600000 }; // ---- Tas binaire min ----------------------------------------------------- class MinHeap { constructor() { this.k = []; this.v = []; } get size() { return this.k.length; } push(key, val) { const k = this.k, v = this.v; let i = k.length; k.push(key); v.push(val); while (i > 0) { const p = (i - 1) >> 1; if (k[p] <= key) break; k[i] = k[p]; v[i] = v[p]; i = p; } k[i] = key; v[i] = val; } pop() { const k = this.k, v = this.v, topK = k[0], topV = v[0]; const lk = k.pop(), lv = v.pop(), n = k.length; if (n > 0) { let i = 0; for (;;) { let c = 2 * i + 1; if (c >= n) break; if (c + 1 < n && k[c + 1] < k[c]) c++; if (k[c] >= lk) break; k[i] = k[c]; v[i] = v[c]; i = c; } k[i] = lk; v[i] = lv; } return [topK, topV]; } } // ---- Index spatial ------------------------------------------------------- const CELL = 0.0003; // ~33 m const cellKey = (lon, lat) => Math.floor((lon + 180) / CELL) * 1000003 + Math.floor((lat + 90) / CELL); function hashAdd(h, lon, lat, id) { const k = cellKey(lon, lat); (h.get(k) || h.set(k, []).get(k)).push(id); } // ---- Construction du graphe --------------------------------------------- function buildGraph(featsByLine, legBoxes, marcheLines) { const G = { lat: [], lon: [], adj: [], line: [], feat: [] }; const hash = new Map(); const ends = []; let featId = 0, nFeat = 0; const addNode = (lon, lat, line, f) => { const id = G.lat.length; G.lat.push(lat); G.lon.push(lon); G.adj.push([]); G.line.push(line); G.feat.push(f); hashAdd(hash, lon, lat, id); return id; }; const addEdge = (a, b, w) => { G.adj[a].push({ t: b, w }); G.adj[b].push({ t: a, w }); }; for (const [code, list] of Object.entries(featsByLine)) { const mult0 = marcheLines.has(code) ? 1 : CFG.OFF_LINE_COST; for (const ft of list) { const geom = ft.g; if (!geom || !geom.coordinates) continue; const parts = geom.type === 'MultiLineString' ? geom.coordinates : [geom.coordinates]; const mult = mult0 * (ft.p && ft.p.type_voie === 'VS' ? CFG.VS_COST : 1); for (const c of parts) { if (!Array.isArray(c) || c.length < 2) continue; // bbox du tronçon let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const q of c) { if (q[0] < x0) x0 = q[0]; if (q[0] > x1) x1 = q[0]; if (q[1] < y0) y0 = q[1]; if (q[1] > y1) y1 = q[1]; } let inside = false; for (const b of legBoxes) { if (x1 >= b[0] && x0 <= b[2] && y1 >= b[1] && y0 <= b[3]) { inside = true; break; } } if (!inside) continue; const f = featId++; nFeat++; let prev = addNode(c[0][0], c[0][1], code, f); const first = prev; for (let i = 1; i < c.length; i++) { const la0 = c[i - 1][1], lo0 = c[i - 1][0], la1 = c[i][1], lo1 = c[i][0]; const seg = hav(la0, lo0, la1, lo1); const n = Math.max(1, Math.ceil(seg / CFG.DENSIFY_M)); for (let s = 1; s <= n; s++) { const t = s / n; const id = addNode(lo0 + t * (lo1 - lo0), la0 + t * (la1 - la0), code, f); addEdge(prev, id, (seg / n) * mult); prev = id; } } ends.push(first, prev); } } } // Raccords des extrémités vers les sommets des autres tronçons for (const e of ends) { const lo = G.lon[e], la = G.lat[e]; const cx = Math.floor((lo + 180) / CELL), cy = Math.floor((la + 90) / CELL); let best = -1, bestD = CFG.JOIN_TOL_M; for (let ix = cx - 1; ix <= cx + 1; ix++) for (let iy = cy - 1; iy <= cy + 1; iy++) { const arr = hash.get(ix * 1000003 + iy); if (!arr) continue; for (const o of arr) { if (G.feat[o] === G.feat[e]) continue; const d = hav(la, lo, G.lat[o], G.lon[o]); if (d < bestD) { bestD = d; best = o; } } } if (best >= 0) addEdge(e, best, bestD + CFG.JOIN_PENALTY_M); } G.hash = hash; G.nFeat = nFeat; return G; } function nearestNode(G, lat, lon, maxM) { const cx = Math.floor((lon + 180) / CELL), cy = Math.floor((lat + 90) / CELL); const maxCells = Math.ceil(maxM / 33) + 1; let best = -1, bestD = maxM; for (let r = 0; r <= maxCells; r++) { for (let ix = cx - r; ix <= cx + r; ix++) for (let iy = cy - r; iy <= cy + r; iy++) { if (Math.max(Math.abs(ix - cx), Math.abs(iy - cy)) !== r) continue; const arr = G.hash.get(ix * 1000003 + iy); if (!arr) continue; for (const o of arr) { const d = hav(lat, lon, G.lat[o], G.lon[o]); if (d < bestD) { bestD = d; best = o; } } } if (best >= 0 && r * 33 > bestD) break; } return best; } // ---- A* ----------------------------------------------------------------- function makeSolver(G) { const n = G.lat.length; const dist = new Float64Array(n).fill(Infinity); const prev = new Int32Array(n).fill(-1); const closed = new Uint8Array(n); return function astar(s, t) { const touched = [s]; dist[s] = 0; const heap = new MinHeap(); const tl = G.lat[t], to = G.lon[t]; heap.push(hav(G.lat[s], G.lon[s], tl, to), s); let found = false, exp = 0; while (heap.size) { const [, u] = heap.pop(); if (closed[u]) continue; closed[u] = 1; if (u === t) { found = true; break; } if (++exp > CFG.MAX_EXPANSIONS) break; for (const e of G.adj[u]) { const nd = dist[u] + e.w; if (nd < dist[e.t]) { if (dist[e.t] === Infinity) touched.push(e.t); dist[e.t] = nd; prev[e.t] = u; heap.push(nd + hav(G.lat[e.t], G.lon[e.t], tl, to), e.t); } } } let path = null; if (found) { path = []; for (let v = t; v !== -1; v = prev[v]) path.push(v); path.reverse(); } for (const v of touched) { dist[v] = Infinity; prev[v] = -1; closed[v] = 0; } return path; }; } // ---- API principale ------------------------------------------------------ // Retourne [{d, lat, lon, ligne, pk}] ou null. 'd' est recalé sur les distances // de la marche (DT.G[i][0]) pour rester synchro avec horaires/profil/LTV. window.buildGraphRoute = function (DT) { const info = t => { const el = document.getElementById('mapSnapInfo'); if (el) el.textContent = t; window.__graphInfo = t; }; if (typeof getMergedVoiesByLine !== 'function') return null; const feats = getMergedVoiesByLine(); if (!Object.keys(feats).length) { info('Graphe : aucune donnée db_voies chargée'); return null; } // 1. Waypoints = gares / chantiers géolocalisés de la marche const raw = (DT.G || []) .filter(g => typeof g[7] === 'number' && typeof g[8] === 'number' && g[7] && g[8]) .map(g => ({ d: g[0], lat: g[7], lon: g[8], name: g[1] })) .sort((a, b) => a.d - b.d); const wps = []; for (const w of raw) { const p = wps[wps.length - 1]; if (!p || hav(p.lat, p.lon, w.lat, w.lon) > 40) wps.push(w); } if (wps.length < 2) return null; // 2. Couloir de recherche (une boîte par tronçon gare->gare) const M = CFG.CORRIDOR_DEG, legBoxes = []; for (let i = 1; i < wps.length; i++) { const a = wps[i - 1], b = wps[i]; legBoxes.push([Math.min(a.lon, b.lon) - M, Math.min(a.lat, b.lat) - M, Math.max(a.lon, b.lon) + M, Math.max(a.lat, b.lat) + M]); } const marcheLines = new Set(); for (const s of (DT.PLI || [])) if (s && s.l) marcheLines.add(String(s.l).padStart(6, '0')); // 3. Graphe const t0 = performance.now(); const G = buildGraph(feats, legBoxes, marcheLines); if (G.lat.length < 10) { info('Graphe : aucun tronçon de voie dans le couloir de la marche'); return null; } // 4. Accrochage des gares puis A* gare par gare const solve = makeSolver(G); const snapped = wps.map(w => ({ ...w, node: nearestNode(G, w.lat, w.lon, CFG.WP_SNAP_MAX_M) })) .filter(w => w.node >= 0); if (snapped.length < 2) { info('Graphe : gares trop éloignées des voies (>' + CFG.WP_SNAP_MAX_M + ' m)'); return null; } const pts = [], wpIdx = []; let rawCum = 0, okLegs = 0, badLegs = 0; const push = (lat, lon, line) => { const p = pts[pts.length - 1]; if (p) rawCum += hav(p.lat, p.lon, lat, lon); pts.push({ lat, lon, ligne: line || '', pk: null, raw: rawCum }); }; push(G.lat[snapped[0].node], G.lon[snapped[0].node], G.line[snapped[0].node]); wpIdx.push({ i: 0, d: snapped[0].d }); for (let i = 1; i < snapped.length; i++) { const a = snapped[i - 1], b = snapped[i]; const path = a.node === b.node ? [a.node] : solve(a.node, b.node); if (path) { for (let k = 1; k < path.length; k++) push(G.lat[path[k]], G.lon[path[k]], G.line[path[k]]); okLegs++; } else { push(G.lat[b.node], G.lon[b.node], G.line[b.node]); // repli : segment droit badLegs++; } wpIdx.push({ i: pts.length - 1, d: b.d }); } // 5. Recalage des distances sur celles de la marche (linéaire par morceaux) for (let w = 1; w < wpIdx.length; w++) { const A = wpIdx[w - 1], B = wpIdx[w]; const r0 = pts[A.i].raw, r1 = pts[B.i].raw, span = r1 - r0; for (let k = A.i; k <= B.i; k++) { const t = span > 0 ? (pts[k].raw - r0) / span : 0; pts[k].d = A.d + t * (B.d - A.d); } } for (let k = 1; k < pts.length; k++) if (pts[k].d < pts[k - 1].d) pts[k].d = pts[k - 1].d; info('Graphe : ' + G.nFeat + ' tronçons · ' + G.lat.length + ' nœuds · ' + okLegs + '/' + (okLegs + badLegs) + ' sections routées' + (badLegs ? ' (' + badLegs + ' en ligne droite)' : '') + ' · ' + Math.round(performance.now() - t0) + ' ms'); return pts; }; // ---- Positionnement du GPS réel sur le tracé routé ---------------------- let lastIdx = 0; window.matchGpsOnRoute = function (lat, lon) { const R = window.miniMapRouteCoords; if (!R || R.length < 2) return null; const kx = Math.cos(lat * RAD); const test = (i) => { const a = R[i], b = R[i + 1]; const ax = (a.lon - lon) * kx, ay = a.lat - lat, bx = (b.lon - lon) * kx, by = b.lat - lat; const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy; let t = L2 > 0 ? -(ax * dx + ay * dy) / L2 : 0; t = t < 0 ? 0 : t > 1 ? 1 : t; const px = ax + t * dx, py = ay + t * dy; return { distM: Math.sqrt(px * px + py * py) * 111320, d: a.d + t * (b.d - a.d), i }; }; let best = null; const lo = Math.max(0, lastIdx - 150), hi = Math.min(R.length - 2, lastIdx + 300); for (let i = lo; i <= hi; i++) { const c = test(i); if (!best || c.distM < best.distM) best = c; } if (!best || best.distM > 250) { for (let i = 0; i < R.length - 1; i++) { const c = test(i); if (!best || c.distM < best.distM) best = c; } } if (best) lastIdx = best.i; return best; }; // ---- Locomotive 3D (72 vues, 5° par image) ------------------------------ // À ADAPTER selon le JSON br186_vues_3d (nom des fichiers, sens, origine). window.LOCO3D = { count: 72, dir: 'src/loco_3d/br186_vues_3d/frames/', name: i => 'frame_' + String(i).padStart(2, '0') + '.png', // <- à ajuster offsetDeg: 0, // décalage si la frame 0 n'est pas "vue de l'arrière" sign: 1, // -1 si les frames tournent dans l'autre sens _preloaded: false, preload() { if (this._preloaded) return; this._preloaded = true; for (let i = 0; i < this.count; i++) { const im = new Image(); im.src = this.dir + this.name(i); } }, // relDeg = angle entre le cap du train et l'axe de la caméra src(relDeg) { const step = 360 / this.count; let i = Math.round((this.sign * relDeg + this.offsetDeg) / step) % this.count; if (i < 0) i += this.count; return this.dir + this.name(i); } }; })();