SPB Git

Repository Public

DemoModel.swift 10.5 KB 262 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : sdk/ios/Example/App/DemoModel.swift10// Module           : sdk11// Repository       : https://git.spboucher.ai/ka-maps-engine12// Created          : 2026-12-0113// Last Modified    : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import CoreLocation88import Foundation89import KAMaps90import Observation9192/// Empreinte mémoire du processus (`phys_footprint`, la mesure que Xcode et Jetsam utilisent), en octets.93func physFootprint() -> UInt64 {94    var info = task_vm_info_data_t()95    var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)96    let kr = withUnsafeMutablePointer(to: &info) { p in97        p.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) }98    }99    return kr == KERN_SUCCESS ? info.phys_footprint : 0100}101102/// Tas du processus : octets réellement alloués (vivants) et octets réservés par l'allocateur.103func heapStats() -> (inUse: UInt64, allocated: UInt64) {104    var st = malloc_statistics_t()105    malloc_zone_statistics(nil, &st)106    return (UInt64(st.size_in_use), UInt64(st.size_allocated))107}108109struct LoggedEvent {110    let time: Date111    let event: KAMapEvent112}113114@MainActor115@Observable116final class DemoModel {117    let map = KAMapController()118119    var camera = KACamera(center: DemoPlace.montreal.coordinate, zoom: DemoPlace.montreal.zoom)120    var brand: KABrand? = .louka121    var theme: KATheme = .signature122    var mode: KAMapMode = .flat123    var place: DemoPlace = .montreal124    var enabledLayers: Set<KALayerKind> = [.markers]125    var selection: KASelection?126    var userLocation: KAUserLocation?127    var networkEnabled = true128    var followsInterfaceStyle = false129    var interaction: KAInteraction = .all130131    var themes: [KATheme] = [.signature, .midnight, .city3d]132    var perf: KAPerf?133    var lastEventLine = ""134    var drawLine = ""135    var isDrawing = false136    var regions: [KAOfflineRegion] = []137    var usageLine = ""138    var searchText = ""139    var searchResults: [KAGeoResult] = []140    var reverseLine = ""141    /// État lu par les essais d'interface (`accessibilityIdentifier` « status »).142    var status = "READY"143    var selectedLabel: String?144145    /// Vues d'annotation de démonstration (0 : seulement la bulle de la sélection).146    var annotationCount = 0147    var annotationsCollide = false148    var annotationsHideBehindBuildings = false149    var annotationSpread = 0.012150    var showsSelectionCallout = true151152    struct DemoAnnotation: Identifiable {153        let id: String154        let coordinate: CLLocationCoordinate2D155        let title: String156        let priority: Int157    }158159    var demoAnnotations: [DemoAnnotation] {160        guard annotationCount > 0 else { return [] }161        var r = SeededRandom(seed: 5)162        let c = place.coordinate163        return (0..<annotationCount).map { i in164            DemoAnnotation(id: "a\(i)", coordinate: CLLocationCoordinate2D(latitude: c.latitude + (r.next() - 0.5) * annotationSpread, longitude: c.longitude + (r.next() - 0.5) * annotationSpread * 1.5), title: "Vue \(i + 1)", priority: i % 5)165        }166    }167168    /// Coordonnée de la pastille sélectionnée (pour sa bulle).169    var selectedCoordinate: CLLocationCoordinate2D? {170        guard let s = selection, s.layer == "markers" else { return nil }171        return DemoData.layer(.markers, around: place.coordinate, brand: brand).markers.first { $0.id == s.id }?.coordinate172    }173174    @ObservationIgnored var log: [LoggedEvent] = []175    @ObservationIgnored private var token: UUID?176177    init() {178        // Essai : démarrer en 3D avec une caméra liée à plat (`-startMode 3d`).179        if let i = ProcessInfo.processInfo.arguments.firstIndex(of: "-startMode"), ProcessInfo.processInfo.arguments.dropFirst(i + 1).first == "3d" { mode = .volumes }180        token = map.addEventHandler { [weak self] ev in self?.handle(ev) }181    }182183    var layers: [KALayer] {184        // Ordre de dessin : surfaces et zones dessous, pastilles dessus.185        let order: [KALayerKind] = [.surface, .heat, .polygons, .lines, .buildings, .columns, .points, .markers]186        return order.filter(enabledLayers.contains).map { DemoData.layer($0, around: place.coordinate, brand: brand) }187    }188189    private func handle(_ ev: KAMapEvent) {190        log.append(LoggedEvent(time: Date(), event: ev))191        if log.count > 4000 { log.removeFirst(2000) }192        switch ev {193        case .move: return194        case .perf(let p): perf = p195        case .load:196            if let t = try? map.embeddedThemes(), !t.isEmpty { themes = t }197            lastEventLine = "load"198        case .select(let f):199            selectedLabel = f.label ?? f.id.map { id in200                DemoData.layer(.markers, around: place.coordinate, brand: brand).markers.first { $0.id == id }?.label ?? id201            }202            if let b = f.building { selectedLabel = "Bâtiment — hauteur \(b.height.map { String(format: "%.0f m", $0) } ?? "?") (\(b.heightSource.rawValue))" }203            lastEventLine = "select \(f.layer ?? "") \(f.id ?? "")"204        case .click(let c):205            if c.features.first(where: { $0.source == .app }) == nil { selectedLabel = nil }206            if let b = c.features.first(where: { $0.building != nil })?.building, c.features.first?.source != .app {207                selectedLabel = "Bâtiment — hauteur \(b.height.map { String(format: "%.0f m", $0) } ?? "?") (\(b.heightSource.rawValue))"208            }209            lastEventLine = "click \(c.features.count) entité(s)"210        case .drawUpdate(let d), .drawDone(let d):211            if let a = d.area, a > 0 {212                drawLine = String(format: "%d sommets — %.0f m², périmètre %.0f m", d.points, a, d.perimeter ?? 0)213            } else if let l = d.length {214                drawLine = String(format: "%d sommets — %.0f m", d.points, l)215            } else {216                drawLine = "\(d.points) sommet(s)"217            }218            if case .drawDone = ev { isDrawing = false }219            lastEventLine = ev.name220        case .drawCancel:221            isDrawing = false222            drawLine = ""223        case .offlineProgress, .offlineDone:224            refreshOffline()225            lastEventLine = ev.name226        case .error(let m): lastEventLine = "erreur : \(m)"227        default: lastEventLine = ev.name228        }229    }230231    func go(_ p: DemoPlace) {232        place = p233        map.flyTo(KACameraUpdate(center: p.coordinate, zoom: p.zoom, bearing: 0))234    }235236    func refreshOffline() {237        regions = (try? map.offlineRegions()) ?? []238        if let u = try? map.tileStoreUsage() {239            let f = ByteCountFormatter()240            usageLine = "Stock : \(f.string(fromByteCount: Int64(u.bytes))) (\(u.tiles) tuiles), épinglé \(f.string(fromByteCount: Int64(u.pinnedBytes))), plafond ambiant \(f.string(fromByteCount: Int64(u.capBytes)))"241        }242    }243244    func search() async {245        do {246            searchResults = try await KAGeoClient().search(searchText, near: camera.center, limit: 6)247        } catch {248            searchResults = []249            lastEventLine = "recherche : \(error)"250        }251    }252253    func reverseAtCenter() async {254        do {255            let r = try await KAGeoClient().reverse(map.camera.center)256            reverseLine = r.label ?? r.municipality?.name ?? "—"257        } catch {258            reverseLine = "\(error)"259        }260    }261}262
Files main
Menu

Theme