// Boucle du Hainaut – AR : pylônes « Équilibre » (modèle RTE, 70 m) répartis le long du tracé. // three.js 0.181 + LocAR.js 0.2.12 (AR géolocalisée : GPS + boussole + caméra). import * as THREE from 'three'; import * as LocAR from 'locar'; import { PYLON_TYPES } from './pylon.js?v=46'; import { BuildingOccluders } from './buildings.js?v=46'; import { LidarOccluders } from './lidar.js?v=46'; import { Terrain, TerrainOccluders } from './terrain.js?v=46'; import { registerServiceWorker, offlineSupported, offlineStatus, downloadAll, clearOffline, sourceSize } from './offline.js?v=46'; import { LineSegments2 } from './lib/lines/LineSegments2.js'; import { LineSegmentsGeometry } from './lib/lines/LineSegmentsGeometry.js'; import { LineMaterial } from './lib/lines/LineMaterial.js'; const APP_VERSION = 'v46'; // affichée à gauche de l'indication « Tourne à… » // --------------------------------------------------------------------------- // Configuration // --------------------------------------------------------------------------- const CONFIG = { traceUrl: 'data/trace.json', // tracé extrait de https://limonier.be/carte-bdh/ (data.js, route.line) // realiste = couleurs du modèle (acier peint blanc, isolateurs gris) ; vive = tout teinté orange colors: { realiste: 0xffffff, vive: 0xff6a00 }, cableColors: { realiste: 0x30353a, vive: 0xff6a00 }, // câbles : gris foncé (comme vus sur le ciel) ou orange cableWidth: 1.6, // px à l'écran (un faisceau de 3 conducteurs reste fin, même de près) // Flèche (affaissement au milieu de la portée), en fraction de la portée. ~3,5 % pour des // conducteurs 400 kV par temps chaud ; le point bas reste > 11 m du sol (engagement RTE p. 18). sagConductor: 0.035, sagEarth: 0.028, // câbles de garde : plus légers et plus tendus cableSegments: 16, // nombre de segments par portée (courbe) cableRadius: 3500, // m, câbles dessinés seulement près de l'utilisateur (au-delà ils sont invisibles // en vrai, et dessinés à largeur fixe ils formeraient une bande sur l'horizon) // Brume : estompage progressif avec la distance (début → fin, en m). Sans cela, les pylônes // lointains apparaissaient comme de petits traits nets sans câbles sur l'horizon. fadePylons: [2000, 5500], fadeCables: [1200, 3500], eyeHeight: 1.6, // m, hauteur de la caméra au-dessus du sol (relief réel : data/terrain, MNT 10 m) groundRadius: 6000, // m, rayon où le sol (collines) peut cacher la ligne fovLongDefault: 65, // champ de vision de la caméra arrière sur son CÔTÉ LONG, en degrés // Répartition des pylônes : espacement régulier le long du tracé (distance mesurée sur la ligne). // 370 m = portée moyenne des pylônes Équilibre sur Avelin–Gavrelle (mémoire descriptif RTE, p. 16), // cohérent avec les 350–400 m annoncés pour la Boucle du Hainaut. Ce ne sont PAS les emplacements officiels. nearRadius: 3000, // m, pour compter les pylônes proches labelMaxDist: 3000, // m, distance affichée au-dessus des pylônes jusqu'à cette distance labelMax: 8, // nombre maximal d'étiquettes de distance (les plus proches) drawRadius: 6000, // m, seuls les pylônes à moins de cette distance sont dessinés (au-delà : brume) redrawMove: 1000, // m, déplacement après lequel on recalcule les pylônes dessinés gpsMinAccuracy: 100, // m, les mesures GPS moins précises sont ignorées gpsMinDistance: 0, // m, déplacement minimal pour mettre à jour la position (0 = chaque mesure) gpsStaleRestart: 15, // s sans aucune mesure GPS → on relance le suivi GPS orientationSmoothing: 0.85, // 0 = aucun lissage, proche de 1 = très lissé (mais en retard) farFromLine: 50000, // m, au-delà on signale une position GPS suspecte far: 30000, // m, distance d'affichage maximale }; // Paramètres d'URL : // ?fake=50.64,3.87 → test sur ordinateur : GPS simulé, pas de boussole (glisser la souris pour tourner) const params = new URLSearchParams(location.search); const FAKE = params.get('fake')?.split(',').map(Number); const fakeMode = Array.isArray(FAKE) && FAKE.length === 2 && FAKE.every(Number.isFinite); // --------------------------------------------------------------------------- // Projection locale en mètres. // LocAR utilise par défaut la projection Web Mercator (EPSG:3857), dont les distances // sont gonflées d'un facteur 1/cos(lat) ≈ 1,57 en Belgique. On utilise une projection // équirectangulaire centrée sur le Hainaut : 1 unité three.js = 1 mètre // (erreur < 0,5 % sur toute la zone du tracé). // --------------------------------------------------------------------------- const R = 6371008.8; const DEG = Math.PI / 180; const LAT0 = 50.6; const K = Math.cos(LAT0 * DEG); const localProjection = { project: (lon, lat) => [R * K * lon * DEG, R * lat * DEG], unproject: ([x, y]) => [x / (R * K) / DEG, y / R / DEG], }; // --------------------------------------------------------------------------- // Utilitaires géographiques // --------------------------------------------------------------------------- function distance(lat1, lon1, lat2, lon2) { return LocAR.LocAR.haversineDist({ latitude: lat1, longitude: lon1 }, { latitude: lat2, longitude: lon2 }); } function bearing(lat1, lon1, lat2, lon2) { const φ1 = lat1 * DEG, φ2 = lat2 * DEG, Δλ = (lon2 - lon1) * DEG; const y = Math.sin(Δλ) * Math.cos(φ2); const x = Math.cos(φ1) * Math.sin(φ2) - Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ); return (Math.atan2(y, x) / DEG + 360) % 360; } function destination(lat, lon, bearingDeg, dist) { const δ = dist / R, θ = bearingDeg * DEG, φ1 = lat * DEG, λ1 = lon * DEG; const φ2 = Math.asin(Math.sin(φ1) * Math.cos(δ) + Math.cos(φ1) * Math.sin(δ) * Math.cos(θ)); const λ2 = λ1 + Math.atan2(Math.sin(θ) * Math.sin(δ) * Math.cos(φ1), Math.cos(δ) - Math.sin(φ1) * Math.sin(φ2)); return { lat: φ2 / DEG, lon: λ2 / DEG }; } const fmtDist = (m) => (m < 1000 ? `${Math.round(m)} m` : m < 10000 ? `${(m / 1000).toFixed(2)} km` : `${Math.round(m / 1000)} km`); const CARDINAUX = ['N', 'NE', 'E', 'SE', 'S', 'SO', 'O', 'NO']; const cardinal = (deg) => CARDINAUX[Math.round(deg / 45) % 8]; const dirText = (d, b) => `${fmtDist(d)} au ${Math.round(b)}° ${cardinal(b)}`; // --------------------------------------------------------------------------- // Tracé de la ligne : point le plus proche de l'utilisateur // --------------------------------------------------------------------------- let trace = null; // [[lat, lon], ...] const traceReady = fetch(CONFIG.traceUrl) .then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }) .then((j) => { trace = j.line; computeLine(); }) .catch((e) => { showRuntimeError(`tracé non chargé (${e.message})`); }); // Emplacements estimés des pylônes : un tous les `span` mètres le long du tracé // (span = portée moyenne du type de pylône choisi) let pylonPts = null, pylonStats = null; function computeLine() { if (!trace) return; pylonPts = buildPylonPoints(trace, curType().span); const st = pylonStats, t = curType(); document.getElementById('line-stats').textContent = `Ligne estimée : ${st.count} pylônes « ${t.label} » sur ${(st.length / 1000).toFixed(1)} km, ` + `un tous les ${t.span} m le long du tracé. Source du modèle : ${t.source}. Emplacements calculés, pas officiels.`; rebuildLine(); } function buildPylonPoints(line, span) { const pts = line.map(([la, lo]) => localProjection.project(lo, la)); const out = [[...pts[0], Math.atan2(pts[1][0] - pts[0][0], pts[1][1] - pts[0][1]) / DEG]]; let next = span, acc = 0; for (let i = 0; i < pts.length - 1; i++) { const [ax, ay] = pts[i], [bx, by] = pts[i + 1]; const L = Math.hypot(bx - ax, by - ay); const brg = Math.atan2(bx - ax, by - ay) / DEG; // cap de la ligne (° depuis le nord, horaire) while (acc + L >= next) { const t = (next - acc) / L; out.push([ax + (bx - ax) * t, ay + (by - ay) * t, brg]); next += span; } acc += L; } const n = pts.length; if (acc - (next - span) > span / 3) { // extrémité out.push([...pts[n - 1], Math.atan2(pts[n - 1][0] - pts[n - 2][0], pts[n - 1][1] - pts[n - 2][1]) / DEG]); } pylonStats = { count: out.length, length: acc, span: acc / (out.length - 1) }; return out.map(([x, y, brg]) => { const [lon, lat] = localProjection.unproject([x, y]); return { lat, lon, brg }; }); } function nearestOnTrace(lat, lon) { if (!trace) return null; const [px, py] = localProjection.project(lon, lat); let best = null; for (let i = 0; i < trace.length - 1; i++) { const [ax, ay] = localProjection.project(trace[i][1], trace[i][0]); const [bx, by] = localProjection.project(trace[i + 1][1], trace[i + 1][0]); const dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy; const t = len2 ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / len2)) : 0; const qx = ax + t * dx, qy = ay + t * dy; const d2 = (px - qx) ** 2 + (py - qy) ** 2; if (!best || d2 < best.d2) best = { d2, qx, qy }; } const [qlon, qlat] = localProjection.unproject([best.qx, best.qy]); return { lat: qlat, lon: qlon, dist: distance(lat, lon, qlat, qlon) }; } // --------------------------------------------------------------------------- // Préférences – stockage local facultatif // --------------------------------------------------------------------------- function loadPref(key, def, ok) { try { const v = localStorage.getItem(key); if (v !== null && ok(v)) return v; } catch (e) { /* ignoré */ } return def; } function savePref(key, v) { try { localStorage.setItem(key, String(v)); } catch (e) { /* ignoré */ } } let fovLong = +loadPref('bdh-fov-long', CONFIG.fovLongDefault, (v) => +v >= 40 && +v <= 90); // Correction de boussole (°) : ajoutée au cap mesuré, pour compenser un nord faux (aimantation locale, // capteur mal calibré). Positive = la scène tourne vers la droite. let compassOffset = +loadPref('bdh-compass', 0, (v) => Math.abs(+v) <= 60); let miniMapOn = loadPref('bdh-minimap', '1', (v) => v === '0' || v === '1') === '1'; let showDist = loadPref('bdh-dist', '1', (v) => v === '0' || v === '1') === '1'; let occlOn = loadPref('bdh-occl', '1', (v) => v === '0' || v === '1') === '1'; // masquage par les bâtiments let occlShow = false; // afficher les bâtiments (contrôle) // Source du masquage : relief LiDAR (3 précisions) ou bâtiments OpenStreetMap const OCCL_SOURCES = { lidar1: { label: 'Très précis (relief LiDAR 1 m)', short: 'Très précis', base: 'data/lidar/1m/', ext: 'png' }, lidar2: { label: 'Moyen (relief LiDAR 2 m)', short: 'Moyen', base: 'data/lidar/2m/', ext: 'png' }, lidar4: { label: 'Léger (relief LiDAR 4 m)', short: 'Léger', base: 'data/lidar/4m/', ext: 'png' }, osm: { label: 'Bâtiments OpenStreetMap seulement (ancien)', short: 'OSM', base: 'data/bat/', ext: 'json' }, }; // m sans obstacle autour de soi. v28 : 6 m au lieu de 20 (20 m effaçait la maison voisine, qui cache réellement la ligne) let clearRadius = +loadPref('bdh-clear2', 6, (v) => +v >= 0 && +v <= 60); let occlSrc = loadPref('bdh-occl-src', 'lidar2', (v) => v in OCCL_SOURCES); let buildings = null; // Avec le LiDAR (2021-2022), on ajoute les bâtiments OSM proches (< 150 m) : constructions plus récentes. let nearBld = null; const occluders = () => [buildings, nearBld].filter(Boolean); // Relief du terrain : y du monde = altitude (m). groundMe = altitude du sol sous l'utilisateur (null = inconnue). const TERRAIN_SRC = { base: 'data/terrain/', ext: 'png', short: 'relief' }; const terrain = new Terrain({ baseUrl: TERRAIN_SRC.base, onError: (m) => showRuntimeError(m) }); let groundOcc = null, groundMe = null; const MINIMAP_RADII = [5000, 1500, 500, 100]; // m : toucher la carte zoome (5 km → 1,5 km → 500 m → 100 m), puis la cache let miniMapRadius = +loadPref('bdh-minimap-r2', 5000, (v) => MINIMAP_RADII.includes(+v)); let hudCompact = loadPref('bdh-hud-compact2', '1', (v) => v === '0' || v === '1') === '1'; let colorMode = loadPref('bdh-color', 'realiste', (v) => v in CONFIG.colors); let pylonType = loadPref('bdh-pylon', 'equilibre', (v) => v in PYLON_TYPES); const curType = () => PYLON_TYPES[pylonType]; // --------------------------------------------------------------------------- // Interface // --------------------------------------------------------------------------- const $ = (id) => document.getElementById(id); const ui = { intro: $('intro'), start: $('start'), error: $('error'), hud: $('hud'), gps: $('h-gps'), heading: $('h-heading'), trace: $('h-trace'), pylon: $('h-pylon'), prec: $('h-prec'), hint: $('h-hint'), err: $('h-err'), sensors: $('h-sensors'), bar: $('bar'), toggle: $('btn-toggle'), fov: $('fov'), fovOut: $('fov-out'), color: $('btn-color'), shotBtn: $('btn-shot'), shot: $('shot'), shotImg: $('shot-img'), shotShare: $('shot-share'), shotSave: $('shot-save'), shotClose: $('shot-close'), minimap: $('minimap'), labels: $('labels'), distChk: $('chk-dist'), offDl: $('off-dl'), offClear: $('off-clear'), offStatus: $('off-status'), settings: $('settings'), introOffline: $('intro-offline'), occlChk: $('chk-occl'), occlShowChk: $('chk-occl-show'), batStats: $('bat-stats'), compass: $('compass'), compassOut: $('compass-out'), cal: $('btn-cal'), calDone: $('cal-done'), occlBtn: $('btn-occl'), calInfo: $('cal-info'), calVal: $('cal-val'), calZero: $('cal-zero'), miniChk: $('chk-minimap'), miniBtn: $('btn-mini'), }; function showError(msg) { ui.error.hidden = false; ui.error.textContent = msg; } // Affiche les erreurs JavaScript à l'écran (pas de console sur téléphone) function showRuntimeError(msg) { if (ui.hud.hidden) showError(msg); else { ui.err.hidden = false; ui.err.textContent = `Erreur : ${msg}`; } } window.addEventListener('error', (e) => showRuntimeError(e.message)); window.addEventListener('unhandledrejection', (e) => showRuntimeError(e.reason?.message || e.reason)); // --------------------------------------------------------------------------- // Pylônes (voir pylon.js pour les modèles, sources et cotes) // --------------------------------------------------------------------------- const pylonMaterial = new THREE.MeshLambertMaterial({ color: CONFIG.colors[colorMode], vertexColors: true, transparent: true }); // Brume : multiplie l'opacité par (1 - smoothstep(début, fin, distance à la caméra)). // La distance est calculée dans le shader (espace caméra), pour chaque sommet. const FADE_DECL = 'varying float vBdhDist;\nuniform vec2 bdhFade;\n'; const FADE = (dist) => `(1.0 - smoothstep(bdhFade.x, bdhFade.y, ${dist}))`; pylonMaterial.onBeforeCompile = (sh) => { sh.uniforms.bdhFade = { value: new THREE.Vector2(...CONFIG.fadePylons) }; sh.vertexShader = FADE_DECL + sh.vertexShader.replace('#include ', '#include \nvBdhDist = length(mvPosition.xyz);'); sh.fragmentShader = FADE_DECL + sh.fragmentShader.replace('#include ', `#include \ngl_FragColor.a *= ${FADE('vBdhDist')};`); }; const geomCache = {}; const pylonGeometry = () => (geomCache[pylonType] ??= curType().build()); // Rotation autour de la verticale pour que les consoles soient perpendiculaires à la ligne. // Repère : nord = -Z, est = +X ; l'axe Z local du modèle doit suivre le cap de la ligne. const yawForLine = (lineBearingDeg) => (180 - lineBearingDeg) * DEG; // --------------------------------------------------------------------------- // État // --------------------------------------------------------------------------- let app = null, locar = null; let lineMesh = null; // pylônes du tracé proches de l'utilisateur (InstancedMesh) let nearPylons = []; // les mêmes, avec leur position 3D (pour les étiquettes de distance) let lineCenter = null; // position utilisée pour choisir les pylônes dessinés let cables = null; // câbles entre pylônes voisins (LineSegments2) const cableMaterial = new LineMaterial({ color: CONFIG.cableColors[colorMode], linewidth: CONFIG.cableWidth, transparent: true }); cableMaterial.onBeforeCompile = (sh) => { sh.uniforms.bdhFade = { value: new THREE.Vector2(...CONFIG.fadeCables) }; sh.vertexShader = FADE_DECL + sh.vertexShader.replace('vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );', 'vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );\nvBdhDist = length(start.xyz);'); sh.fragmentShader = FADE_DECL + sh.fragmentShader.replace('gl_FragColor = vec4( diffuseColor.rgb, alpha );', `gl_FragColor = vec4( diffuseColor.rgb, alpha * ${FADE('vBdhDist')} );`); }; let lineVisible = true; let me = null; // dernière position ACCEPTÉE par LocAR { lat, lon, acc } let raw = null; // dernière mesure brute du GPS, même imprécise { lat, lon, acc, t } let rawCount = 0, rawWatch = null, lastRestart = 0, gpsErr = null; // Diagnostic capteurs / affichage let frames = 0, oriEvents = 0, oriNull = 0, lastOriValid = 0, lastRate = Date.now(), fps = 0, oriRate = 0, nullRate = 0; let lastReconnect = 0; const tmpDir = new THREE.Vector3(); // Suivi GPS « brut » pour l'affichage : montre que le GPS vit, même quand LocAR // ignore les mesures trop imprécises (> gpsMinAccuracy). function startRawWatch() { if (fakeMode || !navigator.geolocation) return; if (rawWatch !== null) navigator.geolocation.clearWatch(rawWatch); rawWatch = navigator.geolocation.watchPosition((p) => { raw = { lat: p.coords.latitude, lon: p.coords.longitude, acc: p.coords.accuracy, t: Date.now() }; rawCount++; gpsErr = null; }, (e) => { gpsErr = `erreur GPS ${e.code} : ${e.message}`; }, { enableHighAccuracy: true, maximumAge: 0 }); } // Si plus aucune mesure n'arrive (GPS « figé »), on relance les deux suivis. async function restartGps() { lastRestart = Date.now(); startRawWatch(); if (locar) { locar.stopGps(); await locar.startGps(); } } // Écran toujours allumé (si supporté) – à redemander à chaque retour sur la page. async function keepAwake() { try { await navigator.wakeLock?.request('screen'); } catch (e) { /* ignoré */ } } // La vidéo peut être mise en pause par le navigateur (changement d'appli, économie d'énergie). function resumeVideo() { const v = app?.webcam?.video; if (v && v.paused) v.play().catch(() => {}); } // Caméra : sur Android (surtout l'app installée), le flux peut être coupé quand l'app passe en arrière-plan // (partage ou ouverture de la photo…). Au retour, la vidéo reste noire : relancer la lecture ne suffit pas. // Toutes les secondes, on vérifie que l'image avance ; sinon (3 s), on rouvre la caméra. // La caméra ne peut servir qu'à une seule app à la fois : si le site est ouvert dans un onglet ET dans // l'app installée, celui qui est en arrière-plan la gardait → écran noir. On la rend donc dès que la page // est cachée, et on la reprend au retour. let camStarted = false, camLastT = -1, camStall = 0, camRestarting = false, camErrShown = 0; function releaseCamera() { const v = app?.webcam?.video; v?.srcObject?.getTracks?.().forEach((t) => t.stop()); } async function restartCamera() { const v = app?.webcam?.video; if (!v || camRestarting || fakeMode) return; camRestarting = true; try { v.srcObject?.getTracks?.().forEach((t) => t.stop()); v.srcObject = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }); await v.play().catch(() => {}); } catch (e) { if (Date.now() - camErrShown > 20000) { // pas plus d'un message toutes les 20 s (nouvel essai toutes les 3 s) camErrShown = Date.now(); showRuntimeError(e.name === 'NotReadableError' || e.name === 'AbortError' ? 'caméra occupée : l\'app est sans doute ouverte ailleurs (autre onglet, app installée, appareil photo). Ferme-la, l\'image revient toute seule.' : `caméra : ${e.message || e.name}`); } } finally { camRestarting = false; } } function cameraWatchdog() { const v = app?.webcam?.video; if (fakeMode || !camStarted || !v || camRestarting || document.visibilityState !== 'visible') { camStall = 0; return; } if (v.paused) v.play().catch(() => {}); const tr = v.srcObject?.getVideoTracks?.()[0]; const moving = v.currentTime !== camLastT; camLastT = v.currentTime; if (tr && tr.readyState === 'live' && !tr.muted && moving && v.videoWidth) { camStall = 0; return; } if (++camStall >= 3) { camStall = 0; restartCamera(); } } // Compte les événements de la boussole (même nom d'événement que LocAR) pour le diagnostic. function onOrientationEvent(e) { oriEvents++; if (e.alpha == null) oriNull++; else lastOriValid = Date.now(); } // Rebranche l'écoute de la boussole (utile si le navigateur n'a rien envoyé au démarrage). function reconnectOrientation() { const doc = app?.deviceOrientationControls; if (!doc) return; lastReconnect = Date.now(); window.removeEventListener(doc.orientationChangeEventName, onOrientationEvent); window.addEventListener(doc.orientationChangeEventName, onOrientationEvent); doc.disconnect(); doc.connect(); } const orientationStale = () => Date.now() - lastOriValid > 2000; // Crée les pylônes du tracé (une seule géométrie instanciée : 1 appel de dessin). // Nécessite le tracé ET une première position GPS (origine du repère LocAR). // Seuls les pylônes à moins de CONFIG.drawRadius sont dessinés (économie pour le téléphone). // Altitude du sol sous l'utilisateur (relief SPW 10 m). Hors du couloir couvert : altitude du point // le plus proche du tracé. Met aussi à jour le sol « écran » (collines) autour de lui. function updateGround() { const [X, Y] = localProjection.project(me.lon, me.lat); if (groundOcc && !groundOcc.origin) groundOcc.setOrigin(locar, me.lon, me.lat); groundOcc?.update(me.lon, me.lat); if (!terrain.index) { terrain.ready.then(updateGround); return; } const key = Terrain.keyOf(X, Y), nb = terrain.neighbours(key); if (nb.some((k) => !terrain.loaded(k))) { terrain.ensure(nb).then(updateGround); return; } // en cours de chargement let g = terrain.alt(X, Y, null); if (g === null) { // hors couloir : point le plus proche du tracé const q = nearestOnTrace(me.lat, me.lon); if (!q) return; const [qX, qY] = localProjection.project(q.lon, q.lat), qk = Terrain.keyOf(qX, qY); if (!terrain.loaded(qk)) { terrain.ensure([qk]).then(updateGround); return; } g = terrain.alt(qX, qY, 0); } const first = groundMe === null; groundMe = g; terrain.def = g; if (first) buildLine(); } let lineWait = false; function buildLine() { if (lineMesh || lineWait || !locar || !me || !pylonPts || groundMe === null) return; const near = []; pylonPts.forEach((p, idx) => { if (distance(me.lat, me.lon, p.lat, p.lon) < CONFIG.drawRadius) near.push({ ...p, idx }); }); // Altitude du pied de chaque pylône : on attend d'abord les dalles de relief concernées near.forEach((p) => { [p.X, p.Y] = localProjection.project(p.lon, p.lat); }); const keys = [...new Set(near.flatMap((p) => terrain.neighbours(Terrain.keyOf(p.X, p.Y))))].filter((k) => !terrain.loaded(k)); if (keys.length) { lineWait = true; terrain.ensure(keys).then(() => { lineWait = false; buildLine(); }); return; } lineCenter = { lat: me.lat, lon: me.lon }; lineMesh = new THREE.InstancedMesh(pylonGeometry(), pylonMaterial, Math.max(1, near.length)); lineMesh.count = near.length; const m = new THREE.Matrix4(), q = new THREE.Quaternion(), one = new THREE.Vector3(1, 1, 1), up = new THREE.Vector3(0, 1, 0); near.forEach((p, i) => { const [x, z] = locar.lonLatToWorldCoords(p.lon, p.lat); q.setFromAxisAngle(up, yawForLine(p.brg)); p.pos = new THREE.Vector3(x, terrain.alt(p.X, p.Y), z); p.q = q.clone(); m.compose(p.pos, q, one); // pied du pylône posé sur le relief lineMesh.setMatrixAt(i, m); }); lineMesh.instanceMatrix.needsUpdate = true; lineMesh.frustumCulled = false; lineMesh.visible = lineVisible; app.scene.add(lineMesh); nearPylons = near; buildCables(near); } // Câbles : pour chaque paire de pylônes consécutifs, chaque point d'accroche (phases + câbles de garde) // est relié au point correspondant du pylône suivant par une courbe qui s'affaisse (parabole, // très proche d'une chaînette pour ces flèches faibles). // Distance horizontale de l'utilisateur (caméra) à une portée A–B function nearSpan(A, B) { const cam = app.camera.position, ax = A.pos.x, az = A.pos.z, dx = B.pos.x - ax, dz = B.pos.z - az; const t = Math.max(0, Math.min(1, ((cam.x - ax) * dx + (cam.z - az) * dz) / (dx * dx + dz * dz))); return Math.hypot(cam.x - (ax + t * dx), cam.z - (az + t * dz)) < CONFIG.cableRadius; } function buildCables(near) { const t = curType(); const attach = [...t.phases().map((v) => [v, CONFIG.sagConductor]), ...t.earth().map((v) => [v, CONFIG.sagEarth])]; const pos = [], a = new THREE.Vector3(), b = new THREE.Vector3(), prev = new THREE.Vector3(), cur = new THREE.Vector3(); const N = CONFIG.cableSegments; for (let i = 0; i < near.length - 1; i++) { const A = near[i], B = near[i + 1]; if (B.idx !== A.idx + 1) continue; // pylônes non consécutifs (bord de la zone dessinée) if (!nearSpan(A, B)) continue; // portée trop loin de l'utilisateur const span = A.pos.distanceTo(B.pos); for (const [local, ratio] of attach) { a.copy(local).applyQuaternion(A.q).add(A.pos); b.copy(local).applyQuaternion(B.q).add(B.pos); const sag = ratio * span; prev.copy(a); for (let k = 1; k <= N; k++) { const u = k / N; cur.lerpVectors(a, b, u); cur.y -= 4 * sag * u * (1 - u); pos.push(prev.x, prev.y, prev.z, cur.x, cur.y, cur.z); prev.copy(cur); } } } if (!pos.length) return; const g = new LineSegmentsGeometry(); g.setPositions(pos); cables = new LineSegments2(g, cableMaterial); cables.frustumCulled = false; cables.visible = lineVisible; app.scene.add(cables); } function rebuildLine() { if (lineMesh) { app.scene.remove(lineMesh); lineMesh.dispose(); lineMesh = null; } if (cables) { app.scene.remove(cables); cables.geometry.dispose(); cables = null; } buildLine(); } // Après un déplacement important, on recalcule les pylônes dessinés function maybeRedrawLine() { if (lineMesh && lineCenter && me && distance(me.lat, me.lon, lineCenter.lat, lineCenter.lon) > CONFIG.redrawMove) rebuildLine(); } function setPylonType(t) { if (!(t in PYLON_TYPES)) return; pylonType = t; savePref('bdh-pylon', t); computeLine(); } function setHint(html) { ui.hint.innerHTML = `${APP_VERSION} ${html}`; } // --------------------------------------------------------------------------- // Champ de vision : calculé à partir des vraies dimensions de la vidéo. // LocAR suppose que l'angle donné couvre la LARGEUR de la vidéo ; en portrait, la largeur // est le petit côté du capteur, ce qui rendait le champ de vision trop large et le pylône // ~40 % trop petit. Ici, l'angle est celui du CÔTÉ LONG de l'image (indépendant de // l'orientation), puis on tient compte du recadrage « object-fit: cover » à l'écran. // --------------------------------------------------------------------------- function applyFov() { if (!app) return; const cam = app.camera, W = window.innerWidth, H = window.innerHeight; const v = app.webcam?.video; let vw = v?.videoWidth, vh = v?.videoHeight; if (!vw || !vh) { vw = 4; vh = 3; if (H > W) [vw, vh] = [vh, vw]; } // vidéo pas encore prête : 4:3 supposé const focalVideo = (Math.max(vw, vh) / 2) / Math.tan((fovLong / 2) * DEG); // focale en pixels vidéo const scale = Math.max(W / vw, H / vh); // agrandissement « cover » const vfov = (2 * Math.atan((H / 2) / (focalVideo * scale))) / DEG; const aspect = W / H; cableMaterial.resolution.set(W, H); // largeur des câbles en pixels CSS if (Math.abs(cam.fov - vfov) > 0.01 || Math.abs(cam.aspect - aspect) > 1e-4) { cam.fov = vfov; cam.aspect = aspect; cam.updateProjectionMatrix(); } } // Boucle d'affichage : remplace celle de LocAR, avec protection contre les erreurs // (une exception dans la boucle de three.js l'arrête définitivement → image figée). function startRenderLoop() { if (!app) return; app.renderer.setAnimationLoop(() => { try { renderWithOffset(); frames++; } catch (e) { showRuntimeError(`affichage : ${e.message}`); } }); } // Rendu avec correction de boussole : la rotation est appliquée seulement le temps du rendu, // puis retirée (sinon le lissage de LocAR, qui part de l'orientation précédente, la cumulerait). const rawQuat = new THREE.Quaternion(), offsetQuat = new THREE.Quaternion(), Y_AXIS = new THREE.Vector3(0, 1, 0); function renderWithOffset() { app.deviceOrientationControls?.update(); const cam = app.camera; rawQuat.copy(cam.quaternion); if (compassOffset) cam.quaternion.premultiply(offsetQuat.setFromAxisAngle(Y_AXIS, -compassOffset * DEG)); // Zone sans obstacle autour de soi : 12 m, ou 1,5 × la précision GPS (max 40 m) // Hauteur de la caméra : sol sous l'utilisateur + 1,6 m (transition douce quand on se déplace) if (groundMe !== null) { const y = groundMe + CONFIG.eyeHeight; cam.position.y = Math.abs(cam.position.y - y) > 30 ? y : cam.position.y + (y - cam.position.y) * 0.1; } const clearR = Math.max(clearRadius, Math.min(30, 1.5 * (me?.acc || 0))); buildings?.setClearZone?.(cam.position.x, cam.position.z, clearR); nearBld?.setClearZone(cam.position.x, cam.position.z, clearR); groundOcc?.setClearZone(cam.position.x, cam.position.z, clearR); app.renderer.render(app.scene, cam); updateLabels(); // juste après le rendu : matrices de la caméra (correction comprise) à jour cam.quaternion.copy(rawQuat); } // --------------------------------------------------------------------------- // Étiquettes de distance au-dessus des pylônes proches et visibles // --------------------------------------------------------------------------- const labelPool = [], tmpV = new THREE.Vector3(), tmpC = new THREE.Vector3(); let lastLabels = []; const fmtLabel = (m) => (m < 1000 ? `${Math.round(m / 10) * 10} m` : `${(m / 1000).toFixed(1).replace('.', ',')} km`); function updateLabels() { const cam = app.camera, W = window.innerWidth, H = window.innerHeight, list = []; if (showDist && lineVisible && me) { const top = curType().height + 6; for (const p of nearPylons) { const d = Math.hypot(p.pos.x - cam.position.x, p.pos.z - cam.position.z); if (d > CONFIG.labelMaxDist) continue; tmpV.set(p.pos.x, p.pos.y + top, p.pos.z); tmpC.copy(tmpV).applyMatrix4(cam.matrixWorldInverse); if (tmpC.z > -1) continue; // derrière la caméra tmpV.project(cam); const x = (tmpV.x + 1) / 2 * W, y = (1 - tmpV.y) / 2 * H; if (x < -40 || x > W + 40 || y < -40 || y > H + 40) continue; list.push({ x, y, d }); } list.sort((a, b) => a.d - b.d); // Pas de chevauchement : une étiquette qui recouvrirait une plus proche est omise const kept = []; for (const l of list) { if (kept.length >= CONFIG.labelMax) break; if (!kept.some((k) => Math.abs(k.x - l.x) < 62 && Math.abs(k.y - l.y) < 22)) kept.push(l); } list.length = 0; list.push(...kept); } for (let i = 0; i < Math.max(list.length, labelPool.length); i++) { let el = labelPool[i]; if (!el) { el = document.createElement('div'); el.className = 'plabel'; ui.labels.appendChild(el); labelPool.push(el); } const l = list[i]; if (!l) { el.hidden = true; continue; } el.hidden = false; const txt = fmtLabel(l.d); if (el.textContent !== txt) el.textContent = txt; el.style.transform = `translate(${l.x.toFixed(1)}px, ${l.y.toFixed(1)}px) translate(-50%, -100%)`; } lastLabels = list; } // Cap de la caméra (direction où regarde l'objectif), lu directement sur la caméra three.js // pour être cohérent avec ce qui est affiché (correction de boussole comprise). Nord = -Z, Est = +X. function cameraHeading() { app.camera.getWorldDirection(tmpDir); return (Math.atan2(tmpDir.x, -tmpDir.z) / DEG + compassOffset + 720) % 360; } // Champ de vision horizontal actuel de la caméra 3D (°) const fmtOffset = (v) => `${v > 0 ? '+' : ''}${v.toFixed(1).replace('.', ',')}°`; const hFovNow = () => 2 * Math.atan(Math.tan(app.camera.fov * DEG / 2) * app.camera.aspect) / DEG; // --------------------------------------------------------------------------- // Mini-carte : nord en haut, tracé, pylônes, ta position et ton cône de vision. // Permet de comparer avec la carte Leaflet et de repérer une boussole décalée. // --------------------------------------------------------------------------- let traceXY = null; function drawMiniMap() { const cv = ui.minimap; cv.hidden = !miniMapOn || !me; if (cv.hidden) return; const dpr = Math.min(window.devicePixelRatio || 1, 2), size = Math.round(cv.clientWidth * dpr); if (cv.width !== size || cv.height !== size) { cv.width = size; cv.height = size; } const c = cv.getContext('2d'), r = size / 2, sc = (r - 4 * dpr) / miniMapRadius; const [mx, my] = localProjection.project(me.lon, me.lat); const P = (x, y) => [r + (x - mx) * sc, r - (y - my) * sc]; c.clearRect(0, 0, size, size); c.save(); c.beginPath(); c.arc(r, r, r - dpr, 0, 2 * Math.PI); c.fillStyle = 'rgba(0,0,0,.55)'; c.fill(); c.clip(); // Cône de vision const h = cameraHeading(), half = hFovNow() / 2; c.beginPath(); c.moveTo(r, r); c.arc(r, r, r, (h - half - 90) * DEG, (h + half - 90) * DEG); c.closePath(); c.fillStyle = 'rgba(255,255,255,.22)'; c.fill(); // Tracé if (trace) { traceXY ??= trace.map(([la, lo]) => localProjection.project(lo, la)); c.beginPath(); traceXY.forEach(([x, y], i) => { const [px, py] = P(x, y); i ? c.lineTo(px, py) : c.moveTo(px, py); }); c.strokeStyle = '#ff6a00'; c.lineWidth = 2 * dpr; c.stroke(); } // Pylônes if (pylonPts) { c.fillStyle = '#fff'; for (const p of pylonPts) { const [x, y] = localProjection.project(p.lon, p.lat); if (Math.abs(x - mx) > miniMapRadius * 1.1 || Math.abs(y - my) > miniMapRadius * 1.1) continue; const [px, py] = P(x, y); c.fillRect(px - 1.5 * dpr, py - 1.5 * dpr, 3 * dpr, 3 * dpr); } } // Moi c.beginPath(); c.arc(r, r, 4 * dpr, 0, 2 * Math.PI); c.fillStyle = '#2d7ff9'; c.fill(); c.lineWidth = 1.5 * dpr; c.strokeStyle = '#fff'; c.stroke(); c.restore(); // Nord + échelle c.fillStyle = '#fff'; c.font = `600 ${11 * dpr}px system-ui, sans-serif`; c.textAlign = 'center'; c.fillText('N', r, 13 * dpr); c.font = `${9 * dpr}px system-ui, sans-serif`; c.fillText(miniMapRadius < 1000 ? `${miniMapRadius} m` : `${miniMapRadius / 1000} km`, r, size - 6 * dpr); } // Ligne « Précision » du bandeau : précision du masquage choisie, relief, zone sans obstacle function precisionText() { if (!occlOn) return 'masquage désactivé (la ligne est dessinée par-dessus tout) · relief 10 m'; const src = OCCL_SOURCES[occlSrc], clearR = Math.round(Math.max(clearRadius, Math.min(30, 1.5 * (me?.acc || 0)))); const n = buildings?.count ?? 0; const what = occlSrc === 'osm' ? `bâtiments OSM seuls (${n} chargés)` : `${src.short} : LiDAR ${buildings?.meta?.res ?? '?'} m (${n} dalle${n > 1 ? 's' : ''}) + bâtiments OSM proches`; return `${what} · relief 10 m · rien de caché à moins de ${clearR} m`; } function updateHud() { if (!app) return; applyFov(); // la vidéo peut changer de dimensions (rotation, reprise) const h = cameraHeading(); const abs = fakeMode || app.deviceOrientationControls?.orientationChangeEventName === 'deviceorientationabsolute' || /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent); ui.heading.innerHTML = `${Math.round(h)}° ${cardinal(h)}` + (abs ? '' : ' (boussole non absolue ?)') + (compassOffset ? ` (correction ${fmtOffset(compassOffset)})` : ''); drawMiniMap(); if (me && locar) updateGround(); if (buildings) { if (me && locar) { // aussi ici : l'index des dalles peut arriver après la première position GPS for (const o of occluders()) { if (!o.origin) o.setOrigin(locar, me.lon, me.lat); o.update(me.lon, me.lat); } } ui.batStats.textContent = !buildings.index ? 'Masquage : chargement…' : occlSrc === 'osm' ? `${buildings.count} bâtiments OSM chargés autour de toi (rayon 800 m). Hauteurs : tag OSM si présent, sinon estimée selon le type (maison ~8 m, abri ~3 m).` : `Relief LiDAR ${buildings.meta?.res} m : ${buildings.count} dalle(s) de 1 km chargée(s) autour de toi (rayon 800 m). Bâtiments, arbres et haies mesurés par avion en 2021-2022 (SPW) ; ce qui est plus récent n'y est pas. ` + `En plus, ${nearBld?.count ?? 0} bâtiments OpenStreetMap à moins de 150 m (constructions plus récentes que le LiDAR ; en vert en mode contrôle).`; } // Ligne GPS : précision et coordonnées de la dernière mesure brute + son âge const g = fakeMode ? (me && { ...me, t: Date.now() }) : raw; if (g) { const age = Math.round((Date.now() - g.t) / 1000); const accCls = g.acc > 30 ? 'bad' : g.acc > 10 ? 'warn' : ''; const ageCls = age > 10 ? 'warn' : ''; let s = `± ${Math.round(g.acc)} m · il y a ${age} s` + ` · ${rawCount} mes. · ${g.lat.toFixed(5)}, ${g.lon.toFixed(5)}`; if (g.acc > CONFIG.gpsMinAccuracy) s += ` (trop imprécis, en attente < ${CONFIG.gpsMinAccuracy} m)`; ui.gps.innerHTML = s; } else { ui.gps.textContent = 'en attente de la première mesure…'; } if (gpsErr) ui.gps.innerHTML += ` ${gpsErr}`; // Aucune mesure depuis trop longtemps → relance automatique if (!fakeMode && Date.now() - lastRestart > CONFIG.gpsStaleRestart * 1000 && (!raw || Date.now() - raw.t > CONFIG.gpsStaleRestart * 1000)) { restartGps(); } // Ligne capteurs : images/s et mesures de boussole/s const now = Date.now(); if (now - lastRate >= 1000) { const dt = (now - lastRate) / 1000; fps = Math.round(frames / dt); oriRate = Math.round(oriEvents / dt); nullRate = Math.round(oriNull / dt); frames = 0; oriEvents = 0; oriNull = 0; lastRate = now; } if (!fakeMode) { let s = `${fps} img/s · boussole ${oriRate} mes./s`; if (fps === 0) s += ' (affichage figé : touche l\'écran)'; if (oriRate === 0) s += ' (aucune donnée : touche l\'écran ; vérifie l\'autorisation « capteurs de mouvement » du navigateur)'; else if (nullRate >= oriRate) s += ' (valeurs vides : boussole indisponible, recalibre en faisant un 8)'; ui.sensors.innerHTML = s; // Pas de boussole valide depuis 2 s → on rebranche l'écoute (au plus toutes les 3 s) if (orientationStale() && now - lastReconnect > 3000) reconnectOrientation(); if (fps === 0) startRenderLoop(); } ui.prec.textContent = precisionText(); if (!me) { ui.trace.textContent = '–'; ui.pylon.textContent = '–'; setHint('Recherche du GPS…'); return; } // Ligne la plus proche + contrôle de vraisemblance de la position const n = nearestOnTrace(me.lat, me.lon); if (n) { const bt = bearing(me.lat, me.lon, n.lat, n.lon); let s = `${dirText(n.dist, bt)} au plus proche`; if (n.dist > CONFIG.farFromLine) { s += `
Position GPS très loin du tracé. Si tu es en Hainaut, ta position est falsifiée ou mise en cache : sur Murena, Advanced Privacy › Localisation › « Utiliser ma vraie position ».`; } ui.trace.innerHTML = s; } else { ui.trace.textContent = 'chargement…'; } buildLine(); maybeRedrawLine(); // Pylône le plus proche let target = null, near = 0; if (pylonPts) { for (const p of pylonPts) { const d = distance(me.lat, me.lon, p.lat, p.lon); if (d < CONFIG.nearRadius) near++; if (!target || d < target.d) target = { ...p, d }; } } let txt = ''; if (target) { const b = bearing(me.lat, me.lon, target.lat, target.lon); const [tX, tY] = localProjection.project(target.lon, target.lat); const angTop = Math.atan2(terrain.alt(tX, tY) + curType().height - (groundMe ?? 0) - CONFIG.eyeHeight, target.d) / DEG; txt = `${curType().label.split(' (')[0]} · le plus proche ${dirText(target.d, b)} · sommet à ${angTop.toFixed(1)}° · ${near} à moins de ${CONFIG.nearRadius / 1000} km`; } ui.pylon.textContent = txt || 'chargement du tracé…'; if (!target) { setHint(''); return; } const b = bearing(me.lat, me.lon, target.lat, target.lon); const rel = ((b - h + 540) % 360) - 180; // -180..180, positif = à droite if (!lineVisible) setHint('Ligne masquée'); else if (Math.abs(rel) < 15) setHint('▲ Pylône le plus proche droit devant'); else setHint(rel > 0 ? `Tourne à droite de ${Math.round(rel)}° ▶` : `◀ Tourne à gauche de ${Math.round(-rel)}°`); } // --------------------------------------------------------------------------- // Démarrage (doit être déclenché par un geste utilisateur, obligatoire sur iPhone) // --------------------------------------------------------------------------- async function start() { ui.start.disabled = true; ui.error.hidden = true; if (!window.isSecureContext) { showError('Cette page doit être ouverte en HTTPS.'); ui.start.disabled = false; return; } // iPhone : la permission des capteurs doit être demandée directement dans le clic, // avant tout autre « await », sinon Safari la refuse. if (!fakeMode && typeof DeviceOrientationEvent !== 'undefined' && typeof DeviceOrientationEvent.requestPermission === 'function') { try { const res = await DeviceOrientationEvent.requestPermission(); if (res !== 'granted') throw new Error('refusé'); } catch (e) { showError('Accès aux capteurs de mouvement refusé.\nRéglages › Safari › Mouvement et orientation, puis recharge la page.'); ui.start.disabled = false; return; } } // La création de l'App ouvre la caméra (getUserMedia) et crée le rendu three.js. app = new LocAR.App({ cameraOptions: { hFov: fovLong, near: 0.5, far: CONFIG.far }, gpsOptions: { gpsMinAccuracy: CONFIG.gpsMinAccuracy, gpsMinDistance: CONFIG.gpsMinDistance }, videoConstraints: { video: { facingMode: 'environment' } }, // La permission iOS a déjà été obtenue ci-dessus : pas de boîte de dialogue LocAR. deviceOrientationOptions: { enabled: !fakeMode, enablePermissionDialog: false, smoothingFactor: CONFIG.orientationSmoothing }, projection: localProjection, }); app.webcam?.on?.('webcamstarted', () => { camStarted = true; }); // Remplace le calcul de champ de vision de LocAR par le nôtre (voir applyFov) app.matchFovToWebcam = applyFov; app.syncFovWithWebcam = applyFov; app.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); app.renderer.setSize(window.innerWidth, window.innerHeight); applyFov(); startRenderLoop(); // Éclairage modéré : le pylône reste gris, il ne vire pas au blanc app.scene.add(new THREE.HemisphereLight(0xffffff, 0x777777, 2.6)); const sun = new THREE.DirectionalLight(0xffffff, 1.6); sun.position.set(-1, 2, 1); app.scene.add(sun); try { locar = await app.start(); } catch (err) { if (!fakeMode) { showError(`Impossible de démarrer : ${err.message || err.code || err}\n` + '(caméra ou capteurs indisponibles ou refusés – vérifie les autorisations du navigateur)'); app.webcam?.dispose(); app.renderer.setAnimationLoop(null); app.renderer.domElement.remove(); app = null; ui.start.disabled = false; return; } locar = app.locar; // mode test : on continue sans caméra } locar.setElevation(CONFIG.eyeHeight); groundOcc = new TerrainOccluders({ scene: app.scene, projection: localProjection, terrain, radius: CONFIG.groundRadius }); groundOcc.setEnabled(occlOn || calMode); makeOccluders(); locar.on('gpsupdate', (ev) => { const c = ev.position.coords; me = { lat: c.latitude, lon: c.longitude, acc: c.accuracy }; for (const o of occluders()) { if (!o.origin) o.setOrigin(locar, me.lon, me.lat); o.update(me.lon, me.lat); } updateGround(); buildLine(); }); locar.on('gpserror', (e) => { gpsErr = `erreur GPS ${e.code} : ${e.message}`; }); // Affiche l'interface AR tout de suite (sans attendre le GPS) ui.intro.hidden = true; ui.hud.hidden = false; ui.bar.hidden = false; ui.fov.value = fovLong; ui.fovOut.textContent = fovLong; ui.color.textContent = colorLabel(); setInterval(updateHud, 250); updateHud(); const v = app.webcam?.video; if (v) { v.muted = true; v.setAttribute('muted', ''); v.addEventListener('resize', applyFov); } if (v?.videoWidth) camStarted = true; setInterval(cameraWatchdog, 1000); reconnectOrientation(); // installe aussi le compteur d'événements de la boussole document.addEventListener('pointerdown', () => { resumeVideo(); if (orientationStale()) reconnectOrientation(); if (fps === 0) startRenderLoop(); }); window.addEventListener('pagehide', releaseCamera); // fermeture / changement de page : rendre la caméra document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { releaseCamera(); return; } if (document.visibilityState === 'visible') { camStall = 0; if (camStarted) restartCamera(); else resumeVideo(); keepAwake(); restartGps(); reconnectOrientation(); startRenderLoop(); } }); keepAwake(); // pas d'await : ne doit jamais bloquer le démarrage await traceReady; if (fakeMode) { locar.fakeGps(FAKE[1], FAKE[0], CONFIG.eyeHeight, 5); enableMouseLook(); } else { lastRestart = Date.now(); startRawWatch(); locar.startGps(); } } // Test sur ordinateur : glisser pour regarder autour function enableMouseLook() { const cam = app.camera; cam.rotation.order = 'YXZ'; // ?heading=222&pitch=-5 : orientation de départ (degrés), pratique pour les tests let yaw = -(+params.get('heading') || 0) * DEG, pitch = (+params.get('pitch') || 0) * DEG, last = null; cam.rotation.set(pitch, yaw, 0); const el = app.renderer.domElement; el.addEventListener('pointerdown', (e) => { if (calMode) return; last = [e.clientX, e.clientY]; el.setPointerCapture(e.pointerId); }); el.addEventListener('pointerup', () => { last = null; }); el.addEventListener('pointermove', (e) => { if (!last) return; yaw -= (e.clientX - last[0]) * 0.2 * DEG; pitch = Math.max(-1.4, Math.min(1.4, pitch - (e.clientY - last[1]) * 0.2 * DEG)); last = [e.clientX, e.clientY]; cam.rotation.set(pitch, yaw, 0); }); } // --------------------------------------------------------------------------- // Boutons // --------------------------------------------------------------------------- const colorLabel = () => (colorMode === 'realiste' ? 'Couleur : gris réaliste' : 'Couleur : orange vif'); ui.start.addEventListener('click', start); function setLineObjectsVisible(v) { lineVisible = v; if (lineMesh) lineMesh.visible = v; if (cables) cables.visible = v; } ui.toggle.addEventListener('click', () => { setLineObjectsVisible(!lineVisible); ui.toggle.textContent = lineVisible ? 'Masquer la ligne' : 'Afficher la ligne'; }); // --------------------------------------------------------------------------- // Étape 5 : photo avant / après (même image caméra, sans puis avec la ligne simulée) // --------------------------------------------------------------------------- const pad2 = (n) => String(n).padStart(2, '0'); let shotUrl = null, shotBlob = null, shotName = ''; function roundRect(ctx, x, y, w, h, r) { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); } function label(ctx, text, x, y, size, bg) { ctx.font = `600 ${size}px system-ui, sans-serif`; const w = ctx.measureText(text).width + size; ctx.fillStyle = bg; roundRect(ctx, x, y, w, size * 1.6, size * 0.4); ctx.fill(); ctx.fillStyle = '#fff'; ctx.textBaseline = 'middle'; ctx.fillText(text, x + size / 2, y + size * 0.8); } async function capturePhoto() { if (!app) return; const r = app.renderer, gl = r.domElement, W = gl.width, H = gl.height; // Rendu frais puis copie immédiate (dans la même tâche, le tampon WebGL est encore lisible). // La photo « avec la ligne » montre toujours la ligne, même si elle est masquée à l'écran. const wasVisible = lineVisible; setLineObjectsVisible(true); renderWithOffset(); const overlay = document.createElement('canvas'); overlay.width = W; overlay.height = H; overlay.getContext('2d').drawImage(gl, 0, 0); const labels = lastLabels; setLineObjectsVisible(wasVisible); if (!wasVisible) updateLabels(); // retire les étiquettes de l'écran // Image caméra recadrée comme à l'écran (object-fit: cover) const cam = document.createElement('canvas'); cam.width = W; cam.height = H; const cx = cam.getContext('2d'); cx.fillStyle = '#000'; cx.fillRect(0, 0, W, H); const v = app.webcam?.video; if (v && v.videoWidth) { const sc = Math.max(W / v.videoWidth, H / v.videoHeight), dw = v.videoWidth * sc, dh = v.videoHeight * sc; cx.drawImage(v, (W - dw) / 2, (H - dh) / 2, dw, dh); } if (!fakeMode && (!v || !v.videoWidth || v.srcObject?.getVideoTracks?.()[0]?.readyState !== 'live')) { showRuntimeError('caméra coupée : photo sans image. Réouverture de la caméra, réessaie dans 2 s.'); restartCamera(); } // Mise en page : côte à côte en portrait, l'une sous l'autre en paysage const portrait = H >= W, gap = Math.round(Math.min(W, H) * 0.015); const fs = Math.round(Math.max(14, Math.min(W, H) * 0.035)); // taille de texte const capH = Math.round(fs * 4.6); // bandeau de légende const outW = portrait ? W * 2 + gap : W, outH = (portrait ? H : H * 2 + gap) + capH; const out = document.createElement('canvas'); out.width = outW; out.height = outH; const o = out.getContext('2d'); o.fillStyle = '#111'; o.fillRect(0, 0, outW, outH); const p2 = portrait ? [W + gap, 0] : [0, H + gap]; o.drawImage(cam, 0, 0); o.drawImage(cam, p2[0], p2[1]); o.drawImage(overlay, p2[0], p2[1]); // Étiquettes de distance (positions calculées au moment du rendu ci-dessus) const k = W / window.innerWidth, lf = Math.round(12 * k); o.font = `600 ${lf}px system-ui, sans-serif`; o.textBaseline = 'middle'; o.textAlign = 'center'; for (const l of labels) { const txt = fmtLabel(l.d), tw = o.measureText(txt).width + lf; const x = p2[0] + l.x * k, y = p2[1] + l.y * k - lf; o.fillStyle = 'rgba(0,0,0,.6)'; roundRect(o, x - tw / 2, y - lf * 0.8, tw, lf * 1.6, lf * 0.5); o.fill(); o.strokeStyle = '#ff6a00'; o.lineWidth = Math.max(1, k); o.stroke(); o.fillStyle = '#fff'; o.fillText(txt, x, y); } o.textAlign = 'left'; label(o, 'SANS la ligne', fs * 0.6, fs * 0.6, fs, 'rgba(0,0,0,.6)'); label(o, 'AVEC la ligne (simulation)', p2[0] + fs * 0.6, p2[1] + fs * 0.6, fs, 'rgba(200,70,0,.85)'); // Légende : date, position, cap, type de pylône, avertissement const d = new Date(); const when = `${pad2(d.getDate())}/${pad2(d.getMonth() + 1)}/${d.getFullYear()} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; const h = Math.round(cameraHeading()); const pos = me ? `${me.lat.toFixed(5)}, ${me.lon.toFixed(5)} (± ${Math.round(me.acc)} m)` : 'position inconnue'; const t = curType(); const lines = [ `Boucle du Hainaut (380 kV) – simulation en réalité augmentée ${APP_VERSION} · ${when}`, `Position ${pos} · regard vers ${h}° ${cardinal(h)} · pylônes ${t.label}, un tous les ${t.span} m`, 'Tracé : carte limonier.be/carte-bdh · emplacements estimés, pas officiels · relief : SPW 2021-2022' + (occlSrc === 'osm' ? ' · bâtiments OSM' : ' (LiDAR) + bâtiments OSM proches'), ]; const y0 = outH - capH; o.fillStyle = '#111'; o.fillRect(0, y0, outW, capH); o.fillStyle = '#e8edf1'; o.textBaseline = 'top'; lines.forEach((txt, i) => { o.font = `${i === 0 ? 600 : 400} ${Math.round(fs * (i === 0 ? 0.9 : 0.75))}px system-ui, sans-serif`; o.fillText(txt, fs * 0.6, y0 + fs * 0.5 + i * fs * 1.25, outW - fs * 1.2); }); shotName = `bdh-avant-apres-${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}.jpg`; shotBlob = await new Promise((res) => out.toBlob(res, 'image/jpeg', 0.9)); if (shotUrl) URL.revokeObjectURL(shotUrl); shotUrl = URL.createObjectURL(shotBlob); ui.shotImg.src = shotUrl; ui.shot.hidden = false; } ui.shotBtn.addEventListener('click', () => { capturePhoto().catch((e) => showRuntimeError(`photo : ${e.message}`)); }); ui.shotClose.addEventListener('click', () => { ui.shot.hidden = true; }); ui.shotSave.addEventListener('click', () => { if (!shotUrl) return; const a = document.createElement('a'); a.href = shotUrl; a.download = shotName; document.body.appendChild(a); a.click(); a.remove(); }); ui.shotShare.addEventListener('click', async () => { if (!shotBlob) return; const file = new File([shotBlob], shotName, { type: 'image/jpeg' }); try { if (navigator.canShare?.({ files: [file] })) { await navigator.share({ files: [file], title: 'Boucle du Hainaut – avant / après', text: 'Simulation de la ligne 380 kV dans le paysage' }); } else { ui.shotSave.click(); // partage de fichiers non supporté : on enregistre } } catch (e) { if (e.name !== 'AbortError') showRuntimeError(`partage : ${e.message}`); } }); const typeSel = document.getElementById('pylon-type'); for (const [k, t] of Object.entries(PYLON_TYPES)) typeSel.add(new Option(t.label, k)); typeSel.value = pylonType; typeSel.addEventListener('change', () => setPylonType(typeSel.value)); ui.color.addEventListener('click', () => { colorMode = colorMode === 'realiste' ? 'vive' : 'realiste'; savePref('bdh-color', colorMode); pylonMaterial.color.setHex(CONFIG.colors[colorMode]); cableMaterial.color.setHex(CONFIG.cableColors[colorMode]); ui.color.textContent = colorLabel(); }); ui.compass.value = compassOffset; ui.compassOut.textContent = compassOffset; ui.compass.addEventListener('input', () => setCompassOffset(+ui.compass.value)); function setCompassOffset(v) { compassOffset = Math.round(Math.max(-60, Math.min(60, v)) * 10) / 10; ui.compass.value = compassOffset; ui.compassOut.textContent = compassOffset; ui.calVal.textContent = fmtOffset(compassOffset); savePref('bdh-compass', compassOffset); } // --------------------------------------------------------------------------- // Mode « Caler la vue » : on fait glisser le paysage virtuel (bâtiments en bleu, pylônes) // à gauche ou à droite jusqu'à ce qu'il se superpose au réel → règle la correction de boussole. // --------------------------------------------------------------------------- let calMode = false, calLast = null; function setCalMode(on) { calMode = on; ui.cal.classList.toggle('on', on); ui.calInfo.hidden = !on; ui.calVal.textContent = fmtOffset(compassOffset); if (on && ui.settings) ui.settings.open = false; // Pendant le calage : bâtiments affichés en bleu (même si le masquage est désactivé) for (const o of occluders()) { o.setEnabled(on || occlOn); o.setVisible(on || occlShow); } groundOcc?.setEnabled(on || occlOn); } ui.cal.addEventListener('click', () => setCalMode(!calMode)); ui.calDone.addEventListener('click', () => setCalMode(false)); ui.calZero.addEventListener('click', () => setCompassOffset(0)); // Glisser sur la vue (pas sur les boutons, le bandeau ou la mini-carte) const calTarget = (e) => calMode && !e.target.closest('#bar, #hud, #minimap, #shot'); window.addEventListener('pointerdown', (e) => { if (calTarget(e)) { calLast = e.clientX; e.preventDefault(); } }); window.addEventListener('pointermove', (e) => { if (calLast === null || !app) return; const dx = e.clientX - calLast; calLast = e.clientX; // glisser vers la droite → le paysage virtuel suit le doigt vers la droite setCompassOffset(compassOffset - dx * hFovNow() / window.innerWidth); }); window.addEventListener('pointerup', () => { calLast = null; }); window.addEventListener('pointercancel', () => { calLast = null; }); // --------------------------------------------------------------------------- // Hors-ligne (PWA) : l'app et le tracé sont gardés automatiquement ; les bâtiments du couloir // peuvent être téléchargés en une fois pour travailler sans réseau. // --------------------------------------------------------------------------- registerServiceWorker(showRuntimeError); const fmtMB = (b) => (b < 1e6 ? `${Math.max(1, Math.round(b / 1e3))} Ko` : `${(b / 1e6).toFixed(b < 1e7 ? 1 : 0).replace('.', ',')} Mo`); let dlAbort = null; // À télécharger : la source choisie + le relief du terrain (+ les bâtiments OSM, utilisés près de soi avec le LiDAR) const offlineSources = () => (occlSrc === 'osm' ? [OCCL_SOURCES.osm, TERRAIN_SRC] : [OCCL_SOURCES[occlSrc], OCCL_SOURCES.osm, TERRAIN_SRC]); async function refreshOffline() { if (!offlineSupported()) { ui.offStatus.textContent = 'Hors-ligne non pris en charge par ce navigateur.'; ui.offDl.disabled = true; return; } try { const st = await offlineStatus(offlineSources()); ui.offStatus.textContent = `Hors-ligne (${OCCL_SOURCES[occlSrc].short}) : ${st.have} / ${st.total} dalles (total ${fmtMB(st.bytes)}).` + (st.used ? ` Espace utilisé par l'app : ${fmtMB(st.used)}.` : '') + (st.have === st.total ? ' ✔ Tout est disponible sans réseau.' : ''); ui.offDl.textContent = st.have === st.total ? 'Tout est téléchargé ✔' : `Télécharger tout pour hors-ligne (${fmtMB(st.bytes)})`; ui.offDl.disabled = st.have === st.total; } catch (e) { ui.offStatus.textContent = navigator.onLine ? `Hors-ligne : ${e.message}` : 'Pas de réseau : état du téléchargement inconnu.'; } } async function startDownload() { if (dlAbort) return; dlAbort = new AbortController(); ui.offDl.textContent = 'Arrêter le téléchargement'; const prog = $('dl-progress'); try { const { failed } = await downloadAll(offlineSources(), (done, total) => { const t = `Téléchargement (${OCCL_SOURCES[occlSrc].short}) : ${done} / ${total} dalles (${Math.round(done / total * 100)} %)…`; ui.offStatus.textContent = t; prog.textContent = t; }, dlAbort.signal); if (failed) showRuntimeError(`${failed} dalles non téléchargées (réseau ?) : réessaie plus tard.`); prog.textContent = dlAbort.signal.aborted ? 'Téléchargement arrêté.' : '✔ Téléchargement terminé : utilisable sans réseau.'; } catch (e) { showRuntimeError(`téléchargement : ${e.message}`); prog.textContent = ''; } dlAbort = null; $('dl-close').textContent = 'Fermer'; refreshOffline(); } ui.offDl.addEventListener('click', () => { if (dlAbort) dlAbort.abort(); else startDownload(); }); // second appui = arrêter // Bouton 🌳 activé alors que le couloir n'est pas entièrement téléchargé (seules les dalles déjà vues sont // gardées) : proposer les 3 précisions, une fois par session let dlAsked = false; async function maybeAskDownload() { if (dlAsked || dlAbort || !offlineSupported() || occlSrc === 'osm') return; try { const st = await offlineStatus(offlineSources()); if (st.have >= st.total) return; $('dl-have').textContent = `${st.have} / ${st.total} dalles`; } catch (e) { return; } dlAsked = true; for (const b of document.querySelectorAll('#dl-choices button')) { b.querySelector('.dl-size').textContent = `— ${document.getElementById(`size-${b.dataset.src}`)?.textContent || '…'}`; b.disabled = false; } $('dl-progress').textContent = ''; $('dl-close').textContent = 'Plus tard'; $('dl-ask').hidden = false; } for (const b of document.querySelectorAll('#dl-choices button')) { b.addEventListener('click', () => { setOcclSrc(b.dataset.src); for (const x of document.querySelectorAll('#dl-choices button')) x.disabled = true; $('dl-close').textContent = 'Continuer en arrière-plan'; startDownload(); }); } $('dl-close').addEventListener('click', () => { $('dl-ask').hidden = true; }); ui.offClear.addEventListener('click', async () => { await clearOffline(); refreshOffline(); }); ui.settings.addEventListener('toggle', () => { if (ui.settings.open && !dlAbort) refreshOffline(); }); ui.introOffline.textContent = offlineSupported() ? 'Hors-ligne : une fois ouverte, l’app fonctionne sans réseau. Pour le relief de tout le couloir : bouton 🌳, ou Réglages › Expert › Télécharger tout.' : ''; ui.occlChk.checked = occlOn; // Choix de la précision du masquage (simple) / de la source (expert), mémorisé function makeOccluders() { if (!app) return; for (const o of occluders()) o.dispose(); nearBld = null; const src = OCCL_SOURCES[occlSrc]; const opts = { scene: app.scene, projection: localProjection, terrain, onError: showRuntimeError }; buildings = occlSrc === 'osm' ? new BuildingOccluders({ ...opts, baseUrl: src.base, radius: 800 }) : new LidarOccluders({ ...opts, baseUrl: src.base, radius: 800 }); if (occlSrc !== 'osm') nearBld = new BuildingOccluders({ ...opts, baseUrl: OCCL_SOURCES.osm.base, radius: 150 }); for (const o of occluders()) { o.setEnabled(occlOn || calMode); o.setVisible(occlShow || calMode); if (me && locar) { o.setOrigin(locar, me.lon, me.lat); o.ready.then(() => o.update(me.lon, me.lat)); } } } function setOcclSrc(v) { if (!(v in OCCL_SOURCES) || v === occlSrc) return; occlSrc = v; savePref('bdh-occl-src', v); syncOcclUi(); makeOccluders(); if (ui.settings.open && !dlAbort) refreshOffline(); } const occlRadios = [...document.querySelectorAll('input[name="occl-prec"]')]; const occlSel = document.getElementById('occl-src'); for (const [k, s] of Object.entries(OCCL_SOURCES)) occlSel.add(new Option(s.label, k)); function syncOcclUi() { for (const r of occlRadios) r.checked = r.value === occlSrc; occlSel.value = occlSrc; } syncOcclUi(); occlRadios.forEach((r) => r.addEventListener('change', () => { if (r.checked) setOcclSrc(r.value); })); occlSel.addEventListener('change', () => setOcclSrc(occlSel.value)); const clearIn = document.getElementById('clear-r'), clearOut = document.getElementById('clear-out'); clearIn.value = clearOut.textContent = clearRadius; clearIn.addEventListener('input', () => { clearRadius = +clearIn.value; clearOut.textContent = clearRadius; savePref('bdh-clear2', clearRadius); }); // Tailles de téléchargement complet affichées à côté de chaque choix // (relief du terrain 3,8 Mo toujours compris ; avec le LiDAR, + bâtiments OSM) Promise.all([sourceSize(TERRAIN_SRC), ...Object.entries(OCCL_SOURCES).map(async ([k, s]) => [k, await sourceSize(s)])]).then(([tsz, ...list]) => { const osmBytes = list.find(([k]) => k === 'osm')?.[1]?.bytes || 0; for (const [k, sz] of list) { const txt = sz ? fmtMB(sz.bytes + (tsz?.bytes || 0) + (k === 'osm' ? 0 : osmBytes)) : 'indisponible'; const el = document.getElementById(`size-${k}`); if (el) el.textContent = txt; const opt = [...occlSel.options].find((o) => o.value === k); if (opt) opt.textContent = `${OCCL_SOURCES[k].label} — ${txt}`; } }); // Masquage par le relief, les bâtiments et les arbres : case (Expert) et bouton 🌳 de la barre function setOcclOn(v) { occlOn = v; ui.occlChk.checked = v; savePref('bdh-occl', v ? '1' : '0'); for (const o of occluders()) o.setEnabled(v || calMode); groundOcc?.setEnabled(v || calMode); ui.occlBtn.textContent = v ? '🌳 Derrière relief : oui' : '🌳 Derrière relief : non'; ui.occlBtn.classList.toggle('off', !v); } setOcclOn(occlOn); ui.occlChk.addEventListener('change', () => setOcclOn(ui.occlChk.checked)); ui.occlBtn.addEventListener('click', async () => { setOcclOn(!occlOn); if (occlOn) maybeAskDownload(); }); ui.occlShowChk.checked = occlShow; ui.occlShowChk.addEventListener('change', () => { occlShow = ui.occlShowChk.checked; for (const o of occluders()) o.setVisible(occlShow); }); ui.distChk.checked = showDist; ui.distChk.addEventListener('change', () => { showDist = ui.distChk.checked; savePref('bdh-dist', showDist ? '1' : '0'); }); ui.miniChk.checked = miniMapOn; ui.miniChk.addEventListener('change', () => setMiniMap(ui.miniChk.checked)); function setMiniMap(on) { miniMapOn = on; ui.miniChk.checked = on; ui.miniBtn.hidden = on; savePref('bdh-minimap', on ? '1' : '0'); drawMiniMap(); } ui.miniBtn.hidden = miniMapOn; // Bouton « Mini-carte » à droite de l'indication : réaffiche la carte (sans replier le bandeau) ui.miniBtn.addEventListener('click', (e) => { e.stopPropagation(); setMiniMap(true); }); // Toucher la mini-carte : 5 km → 1,5 km → 500 m → 100 m → cachée (bouton « Mini-carte » pour la rouvrir) ui.minimap.addEventListener('click', () => { const k = MINIMAP_RADII.indexOf(miniMapRadius); if (k === MINIMAP_RADII.length - 1) { miniMapRadius = MINIMAP_RADII[0]; setMiniMap(false); } else { miniMapRadius = MINIMAP_RADII[k + 1]; } savePref('bdh-minimap-r2', miniMapRadius); drawMiniMap(); }); // Bandeau d'infos réduit par défaut (version + « Tourne à… ») ; le toucher affiche le détail (GPS, cap…) et inversement ui.hud.classList.toggle('compact', hudCompact); ui.hud.addEventListener('click', () => { hudCompact = !hudCompact; ui.hud.classList.toggle('compact', hudCompact); savePref('bdh-hud-compact2', hudCompact ? '1' : '0'); }); ui.fov.addEventListener('input', () => { fovLong = +ui.fov.value; ui.fovOut.textContent = fovLong; savePref('bdh-fov-long', fovLong); applyFov(); }); // Bouton « Fermer les réglages » en bas du panneau (le titre en haut ferme aussi) document.getElementById('settings-close')?.addEventListener('click', () => { document.getElementById('settings').open = false; document.getElementById('bar').scrollTop = 0; }); // Réglages : ouvrir la page de réglages termine le calage ; section « Expert » mémorisée ui.settings.addEventListener('toggle', () => { if (ui.settings.open && calMode) setCalMode(false); }); const expertEl = document.getElementById('expert'); expertEl.open = loadPref('bdh-expert', '0', (v) => v === '0' || v === '1') === '1'; expertEl.addEventListener('toggle', () => savePref('bdh-expert', expertEl.open ? '1' : '0'));