Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Valo-Plex iOS9// File : ValoPlex/Design/CarteGL.swift10// Description : la carte, comme sur le site (src/lib/cartegl.ts) :11// MapLibre Native, tuiles vectorielles d'OpenFreeMap (sans12// clé) reteintées au papier. Vue d'ensemble : pastilles à13// plat. De près : les vrais bâtiments du fond de carte, à14// leur hauteur, prennent la couleur de la valeur par porte ;15// en plan, les mêmes empreintes à plat et un point par16// immeuble. Sert à l'onglet Carte et à la carte d'une fiche.17// Module : ValoPlex18// Repository : https://git.spboucher.ai/valo-plex-ios19// Project Website : https://www.valo-plex.com20// Created : 2026-12-0121// Last Modified : 2026-12-0122//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495@preconcurrency import MapLibre96import SwiftUI9798enum ContenuCarte: Equatable {99 /// Tous les plex de la vue : cases agrégées ou immeubles un à un, selon la réponse du service.100 case parc(ReponseCarte?)101 /// Une fiche : l'immeuble (rôle 1) en brique, ses ventes comparables (rôle 2) en encre.102 case fiche([PlexGeo])103}104105struct CarteGL: UIViewRepresentable {106 let contenu: ContenuCarte107 let relief: Bool108 let depart: CibleCarte109 var cible: CibleCarte? = nil110 var surVue: (API.VueCarte) -> Void = { _ in }111 /// Clés des plex du bâtiment touché, le plus proche du doigt d'abord.112 var surGroupe: ([String]) -> Void = { _ in }113 var surPrete: () -> Void = {}114115 static let style = URL(string: "https://tiles.openfreemap.org/styles/positron")!116 static let inclinaison: CGFloat = 55117 static let cap: CLLocationDirection = 342 // −18°, comme le site118 static let clair = UIColor(Color(hex: 0xEBE5D6))119120 func makeCoordinator() -> Pilote { Pilote(self) }121122 func makeUIView(context: Context) -> MLNMapView {123 let carte = MLNMapView(frame: .zero, styleURL: Self.style)124 carte.delegate = context.coordinator125 carte.backgroundColor = UIColor(VX.papier2)126 carte.minimumZoomLevel = 5127 carte.maximumZoomLevel = 19128 carte.maximumPitch = 70129 carte.logoView.isHidden = true130 carte.compassView.isHidden = true131 carte.attributionButton.tintColor = UIColor(VX.encre2)132 carte.attributionButtonPosition = .bottomRight133 carte.showsUserLocation = false134 if case .fiche = contenu {135 // dans une page qui défile : un doigt fait défiler la page, deux doigts manient la carte136 carte.isScrollEnabled = false137 }138 carte.setCenter(CLLocationCoordinate2D(latitude: depart.lat, longitude: depart.lng), zoomLevel: depart.zoom, animated: false)139 let toucher = UITapGestureRecognizer(target: context.coordinator, action: #selector(Pilote.toucher(_:)))140 // le double toucher (zoom) passe d'abord ; le toucher simple de MapLibre et celui-ci se reconnaissent ensemble141 for g in carte.gestureRecognizers ?? [] {142 if let t = g as? UITapGestureRecognizer, t.numberOfTapsRequired > 1 { toucher.require(toFail: t) }143 }144 toucher.delegate = context.coordinator145 carte.addGestureRecognizer(toucher)146 context.coordinator.carte = carte147 return carte148 }149150 func updateUIView(_ carte: MLNMapView, context: Context) {151 let p = context.coordinator152 p.parent = self153 if p.relief != relief {154 p.relief = relief155 p.appliquerMode(anime: true)156 }157 if p.contenu != contenu {158 p.contenu = contenu159 p.dessiner()160 }161 if let cible, p.cible != cible {162 p.cible = cible163 carte.setCenter(CLLocationCoordinate2D(latitude: cible.lat, longitude: cible.lng), zoomLevel: cible.zoom, animated: true)164 }165 }166167 @MainActor168 final class Pilote: NSObject, MLNMapViewDelegate, UIGestureRecognizerDelegate {169 var parent: CarteGL170 weak var carte: MLNMapView?171 var relief: Bool172 var contenu: ContenuCarte173 var cible: CibleCarte?174 private var pret = false175 /// Plex à rattacher aux bâtiments (vide en vue d'ensemble), groupes du dernier rattachement, et sa signature.176 private var plex: [PlexGeo] = []177 private var groupes: [[PlexGeo]] = []178 private var signature = ""179 private var cadre = false180181 enum Couche {182 static let cases = "cases"183 static let batis = "batis"184 static let batisPlan = "batis-plan"185 static let pointsPlan = "points-plan"186 static let volumes = "fond-volumes"187 }188189 init(_ parent: CarteGL) {190 self.parent = parent191 relief = parent.relief192 contenu = parent.contenu193 }194195 /// Échelle du prix par porte : la même expression « step » que sur le site.196 static func teinte() -> [Any] {197 var e: [Any] = ["step", ["coalesce", ["get", "pp"], 0], UIColor(Color(hex: VX.teintesPorte[0]))]198 for (i, b) in VX.bornesPorte.enumerated() {199 e.append(b)200 e.append(UIColor(Color(hex: VX.teintesPorte[i + 1])))201 }202 return e203 }204205 /// Couleur d'un bâtiment : brique pour l'immeuble de la fiche, encre pour une vente comparable,206 /// vert-de-gris s'il abrite un plex à vendre, sinon l'échelle du prix par porte.207 static func couleurBati(clair: Bool) -> NSExpression {208 var e: [Any] = ["case"]209 if clair { e += [["==", ["get", "plex"], 0], CarteGL.clair] }210 e += [["==", ["get", "role"], 1], UIColor(VX.brique), ["==", ["get", "role"], 2], UIColor(VX.encre),211 ["==", ["get", "vendre"], 1], UIColor(VX.cuivre), ["!", ["has", "pp"]], UIColor(Color(hex: VX.teinteInconnue)), teinte()]212 return NSExpression(mglJSONObject: e)213 }214215 // MARK: style216217 nonisolated func mapView(_ mapView: MLNMapView, didFinishLoading style: MLNStyle) {218 MainActor.assumeIsolated { preparer(style) }219 }220221 private func preparer(_ style: MLNStyle) {222 // le fond reteinté au papier du site223 for couche in style.layers {224 let id = couche.identifier225 if let fond = couche as? MLNBackgroundStyleLayer {226 fond.backgroundColor = NSExpression(forConstantValue: UIColor(Color(hex: 0xEFE9DC)))227 } else if let aplat = couche as? MLNFillStyleLayer {228 if id.contains("water") {229 aplat.fillColor = NSExpression(forConstantValue: UIColor(Color(hex: 0xCDD6D2)))230 } else if ["park", "landcover", "wood", "grass"].contains(where: id.contains) {231 aplat.fillColor = NSExpression(forConstantValue: UIColor(Color(hex: 0xE2E2CF)))232 } else if id.contains("building") {233 aplat.fillColor = NSExpression(forConstantValue: UIColor(Color(hex: 0xE3DBC9)))234 aplat.fillOutlineColor = NSExpression(forConstantValue: UIColor(Color(hex: 0xD3C9B4)))235 }236 }237 }238 // bâtiments du fond en volume clair : en 3D, tant que les plex ne sont pas affichés un à un239 if let tuiles = style.sources.first(where: { $0 is MLNVectorTileSource }) {240 let volumes = MLNFillExtrusionStyleLayer(identifier: Couche.volumes, source: tuiles)241 volumes.sourceLayerIdentifier = "building"242 volumes.minimumZoomLevel = 14243 volumes.fillExtrusionColor = NSExpression(forConstantValue: CarteGL.clair)244 volumes.fillExtrusionHeight = NSExpression(mglJSONObject: ["coalesce", ["get", "render_height"], 6])245 volumes.fillExtrusionBase = NSExpression(mglJSONObject: ["coalesce", ["get", "render_min_height"], 0])246 volumes.fillExtrusionOpacity = NSExpression(forConstantValue: 0.9)247 style.addLayer(volumes)248 }249 let lumiere = MLNLight()250 lumiere.intensity = NSExpression(forConstantValue: 0.28)251 lumiere.color = NSExpression(forConstantValue: UIColor(Color(hex: 0xFFF7EA)))252 style.light = lumiere253254 let vide = MLNShapeCollectionFeature(shapes: [])255 let cases = MLNShapeSource(identifier: "cases", shape: vide, options: nil)256 let points = MLNShapeSource(identifier: "points", shape: vide, options: nil)257 let batis = MLNShapeSource(identifier: "batis", shape: vide, options: nil)258 for s in [cases, points, batis] { style.addSource(s) }259 let encre = UIColor(VX.encre)260261 // vue d'ensemble : pastilles posées à plat sur la carte262 let pastilles = MLNCircleStyleLayer(identifier: Couche.cases, source: cases)263 pastilles.circleRadius = NSExpression(forKeyPath: "r")264 pastilles.circleColor = NSExpression(mglJSONObject: Self.teinte())265 pastilles.circleOpacity = NSExpression(forConstantValue: 0.9)266 pastilles.circleStrokeColor = NSExpression(forConstantValue: encre)267 pastilles.circleStrokeWidth = NSExpression(forConstantValue: 0.6)268 pastilles.circlePitchAlignment = NSExpression(forConstantValue: "map")269 style.addLayer(pastilles)270271 // de près, en 3D : les vrais bâtiments, à leur hauteur, colorés selon la valeur par porte272 let volumes = MLNFillExtrusionStyleLayer(identifier: Couche.batis, source: batis)273 volumes.fillExtrusionColor = Self.couleurBati(clair: true)274 volumes.fillExtrusionHeight = NSExpression(forKeyPath: "h")275 volumes.fillExtrusionOpacity = NSExpression(forConstantValue: 1)276 volumes.fillExtrusionHasVerticalGradient = NSExpression(forConstantValue: true)277 style.addLayer(volumes)278279 // de près, en plan : les mêmes bâtiments à plat, et un point par immeuble280 let aplat = MLNFillStyleLayer(identifier: Couche.batisPlan, source: batis)281 aplat.predicate = NSPredicate(format: "plex == 1")282 aplat.fillColor = Self.couleurBati(clair: false)283 aplat.fillOutlineColor = NSExpression(forConstantValue: encre)284 style.addLayer(aplat)285 let petits = MLNCircleStyleLayer(identifier: Couche.pointsPlan, source: points)286 petits.circleRadius = NSExpression(forConstantValue: 2.2)287 petits.circleColor = NSExpression(forConstantValue: encre)288 petits.circleOpacity = NSExpression(forConstantValue: 0.55)289 style.addLayer(petits)290291 pret = true292 if case .fiche(let l) = contenu { cadrer(l) }293 appliquerMode(anime: false)294 dessiner()295 parent.surPrete()296 signalerVue()297 }298299 /// Fiche : la vue part de l'immeuble.300 private func cadrer(_ l: [PlexGeo]) {301 guard let carte, let sujet = l.first(where: { $0.role == 1 }) ?? l.first else { return }302 let centre = CLLocationCoordinate2D(latitude: sujet.lat, longitude: sujet.lng)303 guard carte.bounds.width > 0 else { return }304 cadre = true305 // centrée sur l'immeuble, assez près pour lire les bâtiments ; les comparables plus lointains306 // se rejoignent en éloignant la carte à deux doigts307 carte.setCenter(centre, zoomLevel: 16.5, animated: false)308 }309310 /// Plan : caméra à la verticale. 3D : caméra inclinée. Les couches suivent le mode et ce qui est affiché.311 func appliquerMode(anime: Bool) {312 guard pret, let carte else { return }313 couches()314 let camera = carte.camera315 camera.pitch = relief ? CarteGL.inclinaison : 0316 camera.heading = relief ? CarteGL.cap : 0317 if anime {318 carte.setCamera(camera, withDuration: 0.7, animationTimingFunction: CAMediaTimingFunction(name: .easeInEaseOut))319 } else {320 carte.setCamera(camera, animated: false)321 }322 }323324 private func couches() {325 guard let style = carte?.style else { return }326 let dePres = !plex.isEmpty327 style.layer(withIdentifier: Couche.batis)?.isVisible = relief328 style.layer(withIdentifier: Couche.batisPlan)?.isVisible = !relief329 style.layer(withIdentifier: Couche.pointsPlan)?.isVisible = !relief330 // deux extrusions superposées sur les mêmes murs se disputeraient chaque pixel : le fond s'efface331 // dès que les vrais bâtiments sont redessinés par la couche colorée332 style.layer(withIdentifier: Couche.volumes)?.isVisible = relief && !(dePres && !groupes.isEmpty)333 }334335 // MARK: données336337 func dessiner() {338 guard pret, let style = carte?.style else { return }339 var pastilles: [MLNShape] = [], petits: [MLNShape] = []340 plex = []341 switch contenu {342 case .parc(let d):343 if let d, d.parPoints {344 plex = d.points.map { PlexGeo(cle: $0.id, lat: $0.lat, lng: $0.lng, pp: $0.pp, vendre: $0.aVendre, logements: $0.n ?? 1) }345 } else if let d {346 let max = d.cases.map(\.n).max() ?? 1347 for k in d.cases {348 let f = MLNPointFeature()349 f.coordinate = CLLocationCoordinate2D(latitude: k.lat, longitude: k.lng)350 var attributs: [String: Any] = ["lat": k.lat, "lng": k.lng, "r": Appariement.rayonCase(n: k.n, max: max)]351 if let pp = k.pp { attributs["pp"] = pp }352 f.attributes = attributs353 pastilles.append(f)354 }355 }356 case .fiche(let l):357 plex = l358 }359 for p in plex {360 let f = MLNPointFeature()361 f.coordinate = CLLocationCoordinate2D(latitude: p.lat, longitude: p.lng)362 petits.append(f)363 }364 (style.source(withIdentifier: "cases") as? MLNShapeSource)?.shape = MLNShapeCollectionFeature(shapes: pastilles)365 (style.source(withIdentifier: "points") as? MLNShapeSource)?.shape = MLNShapeCollectionFeature(shapes: petits)366 signature = ""367 if plex.isEmpty {368 groupes = []369 (style.source(withIdentifier: "batis") as? MLNShapeSource)?.shape = MLNShapeCollectionFeature(shapes: [])370 couches()371 } else {372 colorer()373 }374 }375376 /// Empreintes des bâtiments chargés par le fond de carte (couche « building » des tuiles vectorielles).377 private func batiments() -> [Bati] {378 guard let tuiles = carte?.style?.sources.first(where: { $0 is MLNVectorTileSource }) as? MLNVectorTileSource else { return [] }379 var sortie: [Bati] = []380 let anneau = { (p: MLNPolygon) in Array(UnsafeBufferPointer(start: p.coordinates, count: Int(p.pointCount))) }381 for f in tuiles.features(sourceLayerIdentifiers: ["building"], predicate: nil) {382 let h = (f.attribute(forKey: "render_height") as? NSNumber)?.doubleValue383 let polygones: [MLNPolygon] = (f as? MLNMultiPolygonFeature)?.polygons ?? ((f as? MLNPolygonFeature).map { [$0] } ?? [])384 for p in polygones {385 if let b = Bati(anneaux: [anneau(p)] + (p.interiorPolygons ?? []).map(anneau), hauteurRendue: h) { sortie.append(b) }386 }387 }388 return sortie389 }390391 /// Colore les vrais bâtiments : rattache les plex de la vue aux empreintes chargées. Rejoué quand les tuiles392 /// finissent d'arriver ; la signature évite de refaire un calcul identique.393 func colorer() {394 guard pret, let carte, let style = carte.style, !plex.isEmpty else { return }395 if !cadre, case .fiche(let l) = contenu {396 // la carte n'avait pas encore de taille au chargement du style : cadrage à la première occasion397 cadrer(l)398 if cadre { appliquerMode(anime: false) }399 }400 let B = batiments()401 let c = carte.centerCoordinate402 let sig = "\(plex.count):\(plex[0].cle):\(B.count):" + String(format: "%.4f,%.4f,%.1f", c.latitude, c.longitude, carte.zoomLevel)403 guard sig != signature else { return }404 signature = sig405 let r = Appariement(batiments: B, plex: plex)406 groupes = r.groupes407 var formes: [MLNShape] = []408 formes.reserveCapacity(r.batis.count)409 for b in r.batis {410 var ext = b.anneaux[0]411 let trous = b.anneaux.dropFirst().map { t -> MLNPolygon in412 var a = t413 return MLNPolygon(coordinates: &a, count: UInt(a.count))414 }415 let f = MLNPolygonFeature(coordinates: &ext, count: UInt(ext.count), interiorPolygons: trous.isEmpty ? nil : trous)416 // le bâtiment de la fiche et ceux des comparables dépassent à peine leurs voisins, pour se détacher417 var attributs: [String: Any] = ["g": b.groupe, "plex": b.groupe >= 0 ? 1 : 0, "vendre": b.vendre ? 1 : 0, "role": b.role,418 "h": b.hauteur + (b.role == 1 ? 0.8 : b.role == 2 ? 0.4 : 0)]419 if let pp = b.pp { attributs["pp"] = pp }420 f.attributes = attributs421 formes.append(f)422 }423 (style.source(withIdentifier: "batis") as? MLNShapeSource)?.shape = MLNShapeCollectionFeature(shapes: formes)424 couches()425 }426427 nonisolated func mapViewDidBecomeIdle(_ mapView: MLNMapView) {428 MainActor.assumeIsolated { colorer() }429 }430431 nonisolated func mapViewDidFinishLoadingMap(_ mapView: MLNMapView) {432 MainActor.assumeIsolated { colorer() }433 }434435 // MARK: caméra et toucher436437 nonisolated func mapView(_ mapView: MLNMapView, regionDidChangeAnimated animated: Bool) {438 MainActor.assumeIsolated { signalerVue() }439 }440441 private func signalerVue() {442 guard pret, let carte, carte.bounds.width > 0 else { return }443 let b = carte.visibleCoordinateBounds444 parent.surVue(API.VueCarte(ouest: b.sw.longitude, sud: b.sw.latitude, est: b.ne.longitude, nord: b.ne.latitude, zoom: carte.zoomLevel))445 }446447 nonisolated func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith autre: UIGestureRecognizer) -> Bool { true }448449 @objc func toucher(_ geste: UITapGestureRecognizer) {450 guard pret, let carte else { return }451 let ou = geste.location(in: carte)452 let zone = CGRect(x: ou.x - 6, y: ou.y - 6, width: 12, height: 12)453 let batis = carte.visibleFeatures(in: zone, styleLayerIdentifiers: [Couche.batis, Couche.batisPlan])454 if let g = batis.compactMap({ ($0.attribute(forKey: "g") as? NSNumber)?.intValue }).first(where: { $0 >= 0 }), groupes.indices.contains(g) {455 // un même bâtiment peut abriter plusieurs plex (rangée d'un seul tenant) : le plus proche du doigt d'abord456 let doigt = carte.convert(ou, toCoordinateFrom: carte)457 let tri = groupes[g].sorted {458 hypot($0.lng - doigt.longitude, $0.lat - doigt.latitude) < hypot($1.lng - doigt.longitude, $1.lat - doigt.latitude)459 }460 parent.surGroupe(tri.map(\.cle))461 return462 }463 let large = CGRect(x: ou.x - 14, y: ou.y - 14, width: 28, height: 28)464 if let f = carte.visibleFeatures(in: large, styleLayerIdentifiers: [Couche.cases]).first,465 let lat = (f.attribute(forKey: "lat") as? NSNumber)?.doubleValue, let lng = (f.attribute(forKey: "lng") as? NSNumber)?.doubleValue {466 // toucher une case rapproche la carte467 carte.setCenter(CLLocationCoordinate2D(latitude: lat, longitude: lng), zoomLevel: min(16.5, carte.zoomLevel + 2), animated: true)468 }469 }470 }471}472