SPB Git

Repository Public

ktr.rs 10.7 KB 294 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : server/km-terrain/src/ktr.rs10// Module           : server11// 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// =============================================================================8687//! Format `.ktr` (relief) — codec de référence côté serveur.88//!89//! ```text90//! octets 0..4   "KTR1"91//! octets 4..6   largeur u16 petit-boutiste (257)92//! octets 6..8   drapeaux u16 petit-boutiste — bit 0 : valeurs en mètres (sinon décimètres)93//! octets 8..    flux DEFLATE brut (RFC 1951) de largeur² entiers i16 petit-boutistes, codés en delta94//! ```95//! Delta, ligne par ligne, arithmétique modulo 2^16 : `d[r][0] = v[r][0] - v[r-1][0]` (avec `v[-1][0] = 0`),96//! `d[r][c] = v[r][c] - v[r][c-1]`. `-32768` = absence de donnée. La ligne 0 est le bord nord, la colonne 097//! le bord ouest ; le nœud (c, r) est le coin de pixel (x·256 + c, y·256 + r) de la pyramide XYZ au zoom z,98//! donc la colonne 256 d'une tuile est la colonne 0 de sa voisine de l'est (idem ligne 256 / voisine du sud).99100pub const MAGIC: &[u8; 4] = b"KTR1";101pub const WIDTH: usize = 257;102pub const NODATA: i16 = i16::MIN;103pub const FLAG_METRES: u16 = 1;104/// Borne de sécurité à la décompression : 257² × 2 octets.105const RAW_LEN: usize = WIDTH * WIDTH * 2;106107#[derive(Debug, Clone, PartialEq, Eq)]108pub struct Tile {109    pub width: u16,110    pub flags: u16,111    /// Valeurs brutes (décimètres, ou mètres si `FLAG_METRES`), ligne par ligne depuis le nord.112    pub data: Vec<i16>,113}114115#[derive(Debug, PartialEq, Eq)]116pub enum KtrError {117    TooShort,118    BadMagic,119    BadWidth(u16),120    Inflate,121    BadLength(usize),122}123124impl std::fmt::Display for KtrError {125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {126        write!(f, "ktr: {self:?}")127    }128}129impl std::error::Error for KtrError {}130131impl Tile {132    /// Mètres par unité brute.133    pub fn unit(&self) -> f64 {134        if self.flags & FLAG_METRES != 0 { 1.0 } else { 0.1 }135    }136    /// Altitude en mètres au nœud (col, row), `None` si absence de donnée.137    pub fn metres(&self, col: usize, row: usize) -> Option<f64> {138        let v = self.data[row * self.width as usize + col];139        if v == NODATA {140            None141        } else if self.flags & FLAG_METRES != 0 {142            Some(v as f64)143        } else {144            Some(v as f64 / 10.0)145        }146    }147    /// Interpolation bilinéaire ; `fx`, `fy` dans [0, 256] (fraction de tuile × 256).148    pub fn sample(&self, fx: f64, fy: f64) -> Option<f64> {149        let n = (self.width - 1) as f64;150        let fx = fx.clamp(0.0, n);151        let fy = fy.clamp(0.0, n);152        let c0 = (fx.floor() as usize).min(self.width as usize - 2);153        let r0 = (fy.floor() as usize).min(self.width as usize - 2);154        let (tx, ty) = (fx - c0 as f64, fy - r0 as f64);155        let a = self.metres(c0, r0)?;156        let b = self.metres(c0 + 1, r0)?;157        let c = self.metres(c0, r0 + 1)?;158        let d = self.metres(c0 + 1, r0 + 1)?;159        Some((a * (1.0 - tx) + b * tx) * (1.0 - ty) + (c * (1.0 - tx) + d * tx) * ty)160    }161}162163/// Encode une grille `width × width` de valeurs brutes.164pub fn encode(data: &[i16], width: u16, flags: u16, level: u8) -> Vec<u8> {165    let w = width as usize;166    assert_eq!(data.len(), w * w, "grille carrée attendue");167    let mut raw = Vec::with_capacity(w * w * 2);168    let mut above = 0i16;169    for r in 0..w {170        let row = &data[r * w..(r + 1) * w];171        let mut prev = above;172        for &v in row {173            raw.extend_from_slice(&v.wrapping_sub(prev).to_le_bytes());174            prev = v;175        }176        above = row[0];177    }178    let mut out = Vec::with_capacity(8 + raw.len() / 4);179    out.extend_from_slice(MAGIC);180    out.extend_from_slice(&width.to_le_bytes());181    out.extend_from_slice(&flags.to_le_bytes());182    out.extend_from_slice(&miniz_oxide::deflate::compress_to_vec(&raw, level));183    out184}185186/// Décode une tuile `.ktr`. Refuse toute largeur autre que 257 (borne mémoire).187pub fn decode(buf: &[u8]) -> Result<Tile, KtrError> {188    if buf.len() < 8 {189        return Err(KtrError::TooShort);190    }191    if &buf[0..4] != MAGIC {192        return Err(KtrError::BadMagic);193    }194    let width = u16::from_le_bytes([buf[4], buf[5]]);195    let flags = u16::from_le_bytes([buf[6], buf[7]]);196    if width as usize != WIDTH {197        return Err(KtrError::BadWidth(width));198    }199    let raw = miniz_oxide::inflate::decompress_to_vec_with_limit(&buf[8..], RAW_LEN)200        .map_err(|_| KtrError::Inflate)?;201    if raw.len() != RAW_LEN {202        return Err(KtrError::BadLength(raw.len()));203    }204    let w = WIDTH;205    let mut data = Vec::with_capacity(w * w);206    let mut above = 0i16;207    for r in 0..w {208        let mut prev = above;209        for c in 0..w {210            let i = (r * w + c) * 2;211            let v = prev.wrapping_add(i16::from_le_bytes([raw[i], raw[i + 1]]));212            data.push(v);213            prev = v;214        }215        above = data[r * w];216    }217    Ok(Tile { width, flags, data })218}219220#[cfg(test)]221mod tests {222    use super::*;223224    fn synth(seed: u32) -> Vec<i16> {225        let mut s = seed;226        let mut v = Vec::with_capacity(WIDTH * WIDTH);227        for r in 0..WIDTH {228            for c in 0..WIDTH {229                s = s.wrapping_mul(1664525).wrapping_add(1013904223);230                let noise = ((s >> 24) as i32) - 128;231                v.push(((r as i32 * 37 + c as i32 * 11) % 9000 - 500 + noise) as i16);232            }233        }234        v235    }236237    #[test]238    fn round_trip() {239        let mut g = synth(7);240        g[0] = NODATA;241        g[300] = i16::MAX;242        g[301] = -32767;243        g[WIDTH * WIDTH - 1] = NODATA;244        for level in [1u8, 6, 9] {245            let buf = encode(&g, 257, 0, level);246            let t = decode(&buf).unwrap();247            assert_eq!(t.data, g);248            assert_eq!(t.flags, 0);249            assert_eq!(t.metres(0, 0), None);250            assert_eq!(t.metres(43, 1), Some(3276.7));251        }252    }253254    #[test]255    fn metres_flag() {256        let g = vec![8848i16; WIDTH * WIDTH];257        let t = decode(&encode(&g, 257, FLAG_METRES, 6)).unwrap();258        assert_eq!(t.metres(10, 10), Some(8848.0));259        assert_eq!(t.sample(12.5, 99.25), Some(8848.0));260    }261262    #[test]263    fn flat_tile_is_tiny() {264        let g = vec![0i16; WIDTH * WIDTH];265        assert!(encode(&g, 257, 0, 9).len() < 400);266    }267268    #[test]269    fn bilinear() {270        let mut g = vec![0i16; WIDTH * WIDTH];271        g[1] = 100; // nœud (1, 0) = 10 m272        let t = decode(&encode(&g, 257, 0, 6)).unwrap();273        assert!((t.sample(0.5, 0.0).unwrap() - 5.0).abs() < 1e-9);274        assert!((t.sample(1.0, 0.5).unwrap() - 5.0).abs() < 1e-9);275        assert_eq!(t.sample(256.0, 256.0), Some(0.0));276    }277278    #[test]279    fn rejects_garbage() {280        assert_eq!(decode(b"KTR"), Err(KtrError::TooShort));281        assert_eq!(decode(b"XXXX\x01\x01\x00\x00abc"), Err(KtrError::BadMagic));282        assert_eq!(decode(b"KTR1\x00\x10\x00\x00abc"), Err(KtrError::BadWidth(4096)));283        assert_eq!(decode(b"KTR1\x01\x01\x00\x00\xff\xff\xff"), Err(KtrError::Inflate));284        // flux valide mais trop court285        let mut b = b"KTR1\x01\x01\x00\x00".to_vec();286        b.extend_from_slice(&miniz_oxide::deflate::compress_to_vec(&[0u8; 100], 6));287        assert_eq!(decode(&b), Err(KtrError::BadLength(100)));288        // bombe : plus de 257² × 2 octets289        let mut b = b"KTR1\x01\x01\x00\x00".to_vec();290        b.extend_from_slice(&miniz_oxide::deflate::compress_to_vec(&vec![0u8; RAW_LEN + 1], 6));291        assert_eq!(decode(&b), Err(KtrError::Inflate));292    }293}294
Files main
Menu

Theme