Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-maps/kmr/src/main.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//! kmr — outil du Studio et du service de manifeste.88//!89//! kmr validate entrée standard : {"theme": {...}, "brand": {...}?, "effective": bool?}90//! sortie : {"ok", "errors": [{scope, path, message}], "warnings", "effective"?, "summary"}91//! kmr render --out x.png entrée standard : tâche de rendu (voir `Job`)92//! kmr version93//!94//! La validation est celle du moteur (`Style::parse_with(…, Strict)`), pas une copie : ce que le95//! Studio accepte est exactement ce que les SDK savent lire.9697use km_core::camera::CameraState;98use km_core::geo::LngLat;99use km_core::style::{ParseMode, Style};100use km_shot::{Shot, ShotOptions, Source};101use serde_json::{json, Value};102use std::io::Read;103104static FONT: &[u8] = include_bytes!("../../../../engine/assets/fonts/Inter-Regular.ttf");105106fn read_stdin() -> Value {107 let mut s = String::new();108 if std::io::stdin().read_to_string(&mut s).is_err() {109 fail("entrée illisible");110 }111 serde_json::from_str(&s).unwrap_or_else(|e| fail(&format!("JSON invalide : {e}")))112}113114fn fail(msg: &str) -> ! {115 println!("{}", json!({ "ok": false, "errors": [{ "scope": "input", "path": "", "message": msg }] }));116 std::process::exit(1)117}118119/// Analyse stricte du thème, puis de la variante de marque. Rend le style et le rapport.120fn check(input: &Value) -> (Option<Style>, Value) {121 let Some(theme) = input.get("theme").filter(|t| t.is_object()) else {122 return (None, json!({ "ok": false, "errors": [{ "scope": "input", "path": "theme", "message": "objet « theme » requis" }], "warnings": [] }));123 };124 let style = match Style::parse_with(&theme.to_string(), ParseMode::Strict) {125 Ok(s) => s,126 Err(e) => return (None, json!({ "ok": false, "errors": [{ "scope": "theme", "path": e.path, "message": e.message }], "warnings": [] })),127 };128 let mut warnings: Vec<String> = style.warnings.clone();129 let style = match input.get("brand").filter(|b| b.is_object()) {130 Some(b) => match style.with_brand(&b.to_string()) {131 Ok(s) => {132 warnings.extend(s.warnings.iter().cloned());133 s134 }135 Err(e) => return (None, json!({ "ok": false, "errors": [{ "scope": "brand", "path": e.path, "message": e.message }], "warnings": warnings })),136 },137 None => style,138 };139 warnings.sort();140 warnings.dedup();141 let summary = json!({142 "layers": style.layers.len(),143 "sources": style.source_layers(),144 "shadows": style.wants_shadows(),145 });146 (Some(style), json!({ "ok": true, "errors": [], "warnings": warnings, "summary": summary }))147}148149fn cmd_validate() {150 let input = read_stdin();151 let (style, mut report) = check(&input);152 if let (Some(s), Some(true)) = (&style, input.get("effective").and_then(Value::as_bool)) {153 report["effective"] = s.document().clone();154 }155 println!("{report}");156 std::process::exit(if style.is_some() { 0 } else { 1 });157}158159fn f(v: &Value, key: &str, default: f64) -> f64 {160 v.get(key).and_then(Value::as_f64).unwrap_or(default)161}162163fn cmd_render(out: &str) {164 let job = read_stdin();165 let (style, report) = check(&job);166 let Some(style) = style else {167 println!("{report}");168 std::process::exit(1)169 };170 let center = job.get("center").and_then(Value::as_array).filter(|a| a.len() == 2).unwrap_or_else(|| fail("center : [lon, lat] requis"));171 let (lon, lat) = (center[0].as_f64().unwrap_or(f64::NAN), center[1].as_f64().unwrap_or(f64::NAN));172 if !(lon.is_finite() && lat.is_finite() && lon.abs() <= 180.0 && lat.abs() <= 85.06) {173 fail("center hors limites");174 }175 let zoom = f(&job, "zoom", 14.0).clamp(0.0, 20.0);176 let pitch = f(&job, "pitch", 0.0).clamp(0.0, 72.0);177 let bearing = f(&job, "bearing", 0.0);178 let scale = f(&job, "scale", 1.0).clamp(1.0, 3.0) as f32;179 let width = f(&job, "width", 800.0).clamp(16.0, 2048.0) as u32;180 let height = f(&job, "height", 600.0).clamp(16.0, 2048.0) as u32;181 let tiles = job.get("tiles").and_then(Value::as_str).unwrap_or("http://127.0.0.1:8901").to_string();182 let timeout = f(&job, "timeout", 20.0).clamp(1.0, 120.0);183184 let mut o = ShotOptions::default();185 o.theme = "signature".into();186 o.camera = CameraState::new(LngLat::new(lon, lat), zoom, bearing, pitch);187 o.width = width;188 o.height = height;189 o.pixel_ratio = scale;190 o.source = Source::Http(tiles);191 if let Some(d) = job.get("cache").and_then(Value::as_str) {192 o.cache_dir = Some(d.into());193 }194 let mut shot = Shot::new(o).unwrap_or_else(|e| fail(&format!("GPU : {e}")));195 // Le document effectif (thème + marque) vient de l'analyse stricte ci-dessus.196 let r = shot.map.command(&json!({ "op": "setThemeDocument", "document": style.document() }));197 if r["ok"] != true {198 fail(&format!("thème refusé par le moteur : {}", r["error"]));199 }200 let three_d = match job.get("mode").and_then(Value::as_str) {201 Some("3d") => true,202 Some("2d") => false,203 _ => pitch > 0.0,204 };205 shot.map.set_extrusion_factor(if three_d { 1.0 } else { 0.0 });206207 let mut errors: Vec<String> = Vec::new();208 if let Some(markers) = job.get("markers").and_then(Value::as_array) {209 let (mut pills, mut points) = (Vec::new(), Vec::new());210 for (i, m) in markers.iter().enumerate() {211 let (Some(mlon), Some(mlat)) = (m.get("lon").and_then(Value::as_f64), m.get("lat").and_then(Value::as_f64)) else { continue };212 match m.get("label").and_then(Value::as_str).filter(|l| !l.is_empty()) {213 Some(l) => pills.push(json!({ "id": format!("m{i}"), "lon": mlon, "lat": mlat, "label": l, "nature": "observe" })),214 None => points.push(json!({ "id": format!("p{i}"), "lon": mlon, "lat": mlat })),215 }216 }217 let mut cmds = Vec::new();218 if !points.is_empty() {219 cmds.push(json!({ "op": "addLayer", "id": "static-points", "type": "points",220 "options": { "radius": 7.5, "color": "@accent", "strokeColor": "@accent-ink", "strokeWidth": 2.5 }, "data": points }));221 }222 if !pills.is_empty() {223 cmds.push(json!({ "op": "addLayer", "id": "static-pills", "type": "markers", "options": {}, "data": pills }));224 }225 for c in &cmds {226 let r = shot.map.command(c);227 if r["ok"] != true {228 errors.push(format!("marqueurs : {}", r["error"]));229 }230 }231 }232 if let Some(cmds) = job.get("commands").and_then(Value::as_array) {233 for c in cmds {234 let r = shot.map.command(c);235 if r["ok"] != true {236 errors.push(format!("commande {} : {}", c.get("op").unwrap_or(&Value::Null), r["error"]));237 }238 }239 }240241 let t0 = std::time::Instant::now();242 shot.settle(timeout);243 shot.settle(3.0);244 let settled = shot.map.is_settled();245 let mut img = shot.capture().unwrap_or_else(|e| fail(&format!("lecture de l'image : {e}")));246 let (w, h) = (shot.target.width, shot.target.height);247 let mut attribution = String::new();248 for e in shot.map.take_events() {249 match e["type"].as_str() {250 Some("error") => errors.push(e.to_string()),251 Some("load") => attribution = e["attribution"].as_str().unwrap_or("").to_string(),252 _ => {}253 }254 }255 if let Some(a) = job.get("attribution") {256 match a {257 Value::String(s) => attribution = s.clone(),258 Value::Bool(false) => attribution.clear(),259 _ => {}260 }261 }262 if !attribution.is_empty() {263 stamp(&mut img, w, h, &attribution, scale);264 }265 if let Err(e) = write_png(out, w, h, &img) {266 fail(&format!("écriture : {e}"));267 }268 let p = shot.map.perf();269 println!(270 "{}",271 json!({ "ok": true, "width": w, "height": h, "settled": settled, "ms": (t0.elapsed().as_secs_f64() * 1000.0).round(),272 "tiles": p.tiles, "warnings": report["warnings"], "errors": errors, "attribution": attribution })273 );274}275276/// Mention de source en bas à droite : cartouche clair, texte sombre (Inter).277fn stamp(img: &mut [u8], w: u32, h: u32, text: &str, scale: f32) {278 let font = match fontdue::Font::from_bytes(FONT, fontdue::FontSettings::default()) {279 Ok(f) => f,280 Err(_) => return,281 };282 let px = 10.5 * scale;283 let glyphs: Vec<(fontdue::Metrics, Vec<u8>)> = text.chars().map(|c| font.rasterize(c, px)).collect();284 let tw: f32 = glyphs.iter().map(|g| g.0.advance_width).sum();285 let (pad_x, pad_y) = ((5.0 * scale) as i32, (3.0 * scale) as i32);286 let box_w = tw.ceil() as i32 + 2 * pad_x;287 let box_h = (px * 1.25).ceil() as i32 + 2 * pad_y;288 if box_w >= w as i32 || box_h >= h as i32 {289 return;290 }291 let (x0, y0) = (w as i32 - box_w, h as i32 - box_h);292 let mut blend = |x: i32, y: i32, rgb: [u8; 3], a: f32| {293 if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 {294 return;295 }296 let i = ((y as u32 * w + x as u32) * 4) as usize;297 for k in 0..3 {298 img[i + k] = (img[i + k] as f32 * (1.0 - a) + rgb[k] as f32 * a).round() as u8;299 }300 img[i + 3] = 255;301 };302 for y in y0..h as i32 {303 for x in x0..w as i32 {304 blend(x, y, [255, 255, 255], 0.78);305 }306 }307 let baseline = y0 + pad_y + (px * 1.0).round() as i32;308 let mut pen = (x0 + pad_x) as f32;309 for (m, bitmap) in &glyphs {310 for gy in 0..m.height {311 for gx in 0..m.width {312 let a = bitmap[gy * m.width + gx] as f32 / 255.0;313 if a > 0.0 {314 let x = pen.round() as i32 + m.xmin + gx as i32;315 let y = baseline - m.ymin - m.height as i32 + gy as i32;316 blend(x, y, [42, 40, 37], a);317 }318 }319 }320 pen += m.advance_width;321 }322}323324fn write_png(path: &str, w: u32, h: u32, rgba: &[u8]) -> Result<(), String> {325 // Une carte rendue est opaque : RGB suffit et pèse moins.326 let rgb: Vec<u8> = rgba.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();327 let file = std::fs::File::create(path).map_err(|e| e.to_string())?;328 let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w, h);329 enc.set_color(png::ColorType::Rgb);330 enc.set_depth(png::BitDepth::Eight);331 enc.set_compression(png::Compression::Balanced);332 let mut wr = enc.write_header().map_err(|e| e.to_string())?;333 wr.write_image_data(&rgb).map_err(|e| e.to_string())?;334 wr.finish().map_err(|e| e.to_string())335}336337fn main() {338 let args: Vec<String> = std::env::args().skip(1).collect();339 match args.first().map(String::as_str) {340 Some("validate") => cmd_validate(),341 Some("render") => match (args.get(1).map(String::as_str), args.get(2)) {342 (Some("--out"), Some(out)) => cmd_render(out),343 _ => fail("usage : kmr render --out image.png < tâche.json"),344 },345 Some("version") => println!("{}", json!({ "kmr": env!("CARGO_PKG_VERSION"), "kastyle": km_core::style::KASTYLE_VERSION })),346 _ => {347 eprintln!("usage : kmr validate | render --out image.png | version (JSON sur l'entrée standard)");348 std::process::exit(2)349 }350 }351}352