From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id EB89D1FF0B4 for ; Fri, 27 Nov 2026 17:14:09 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 2F06021914; Fri, 27 Nov 2026 17:13:16 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH yew-widget-toolkit 17/38] widget: charts: world map: split the map into one path per region Date: Fri, 27 Nov 2026 17:12:14 +0100 Message-ID: <20261127161241.3713494-18-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261127161241.3713494-1-d.csapak@proxmox.com> References: <20261127161241.3713494-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.247 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: S3BKPSNNNSA2G6ILYG3UTMYVGGJIAFWV X-Message-ID-Hash: S3BKPSNNNSA2G6ILYG3UTMYVGGJIAFWV X-MailFrom: d.csapak@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Datacenter Manager development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: instead of drawing all areas and all lines of a feature with one path each. A browser draws in tiles, and for each tile it has to go through the whole path, even if only a small part of it is visible there. With the tens of thousands of points of our world map, that made panning and zooming slow, and also every other change on the map, since the map below is drawn again then too. Paths that are completely outside of what has to be drawn are skipped cheaply though, so collect the shapes in one path per region (a twelfth of the width of the map). A hole only cuts out of the shapes of its own path, so all rings of a polygon go into the path of the region its outline is in. The shapes are rendered by a component of their own that compares them by reference. The Map renders for every step of a pan or zoom, and yew would compare all of the paths each time otherwise. Signed-off-by: Dominik Csapak --- src/widget/charts/world_map.rs | 261 +++++++++++++++++++++++++-------- 1 file changed, 203 insertions(+), 58 deletions(-) diff --git a/src/widget/charts/world_map.rs b/src/widget/charts/world_map.rs index c5a68e4..a73d279 100644 --- a/src/widget/charts/world_map.rs +++ b/src/widget/charts/world_map.rs @@ -1,9 +1,12 @@ +use std::collections::BTreeMap; +use std::fmt::Write; use std::marker::PhantomData; use std::rc::Rc; use derivative::Derivative; use geojson::{Feature, GeoJson, Geometry}; use yew::prelude::*; +use yew::virtual_dom::{VComp, VNode}; use crate::prelude::*; use crate::widget::canvas::{Group, Path}; @@ -19,6 +22,10 @@ const WIDTH: f64 = 3600.0; // use 10 units per longitude const WIDTH_RATIO: f64 = 1.65; const HEIGHT: f64 = WIDTH / WIDTH_RATIO; +// The side length of the regions that the shapes of the map are split into. A browser skips the +// paths outside of the area it has to draw, which is much cheaper than clipping one huge path. +const REGION_SIZE: f64 = WIDTH / 12.0; + /// Represents a Location in the world using the geographic coordinate system. #[derive(Clone, Copy, PartialEq)] pub struct Location { @@ -113,29 +120,29 @@ impl WorldMap { } pub struct WorldMapComp { - shapes: Vec, + shapes: Rc>, _phantom_data: PhantomData, } -/// The shapes of a GeoJSON feature as SVG path commands. +/// The shapes of a GeoJSON feature as SVG path commands, with one path per region of the map. struct FeatureShapes { /// The `kind` property of the feature, so that a style sheet can tell the features apart. kind: Option, /// The polygons of the feature. - areas: AttrValue, + areas: Vec, /// The line strings of the feature, which are not filled. - lines: AttrValue, + lines: Vec, } impl FeatureShapes { fn new(kind: Option<&str>, geometry: &Geometry) -> Self { - let mut areas = Vec::new(); - let mut lines = Vec::new(); - parse_geometry(geometry, &mut areas, &mut lines); + let mut areas = RegionPaths::default(); + let mut lines = RegionPaths::default(); + add_geometry(geometry, &mut areas, &mut lines); Self { kind: kind.map(|kind| kind.to_owned().into()), - areas: areas.join(" ").into(), - lines: lines.join(" ").into(), + areas: areas.into_paths(), + lines: lines.into_paths(), } } @@ -145,6 +152,87 @@ impl FeatureShapes { } } +/// Collects path commands, grouped by the region of the map they draw in. +#[derive(Default)] +struct RegionPaths(BTreeMap<(i32, i32), String>); + +impl RegionPaths { + /// Adds lines to the path of the region that the first one is in. + /// + /// The rings of a polygon have to stay together that way, since a hole only cuts out of the + /// shapes of its own path. + fn add(&mut self, lines: &[Vec>], close: bool) { + let lines: Vec> = lines + .iter() + .map(|line| { + line.iter() + .filter(|position| position.len() >= 2) + .map(|position| project(Location::new(position[0], position[1]))) + .collect() + }) + .collect(); + let Some(first) = lines.iter().find(|line| !line.is_empty()) else { + return; + }; + + let (mut min, mut max) = (first[0], first[0]); + for point in first { + min = Coordinates { + x: min.x.min(point.x), + y: min.y.min(point.y), + }; + max = Coordinates { + x: max.x.max(point.x), + y: max.y.max(point.y), + }; + } + let region = ( + ((min.x + max.x) / 2.0 / REGION_SIZE) as i32, + ((min.y + max.y) / 2.0 / REGION_SIZE) as i32, + ); + + let path = self.0.entry(region).or_default(); + for line in lines.iter().filter(|line| !line.is_empty()) { + let mut command = 'M'; + for point in line { + // writing to a String never fails + let _ = write!(path, "{command}{:.2},{:.2}", point.x, point.y); + command = 'L'; + } + if close { + path.push('Z'); + } + } + } + + fn into_paths(self) -> Vec { + self.0.into_values().map(AttrValue::from).collect() + } +} + +fn add_geometry(geometry: &Geometry, areas: &mut RegionPaths, lines: &mut RegionPaths) { + match &geometry.value { + geojson::Value::Polygon(rings) => areas.add(rings, true), + geojson::Value::MultiPolygon(polygons) => { + for rings in polygons { + areas.add(rings, true); + } + } + geojson::Value::LineString(line) => lines.add(std::slice::from_ref(line), false), + geojson::Value::MultiLineString(multi_line) => { + for line in multi_line { + lines.add(std::slice::from_ref(line), false); + } + } + geojson::Value::GeometryCollection(geometries) => { + for geometry in geometries { + add_geometry(geometry, areas, lines); + } + } + geojson::Value::Point(_) | geojson::Value::MultiPoint(_) => {} + } +} + fn calculate_shapes(geojson: &GeoJson) -> Vec { match geojson { GeoJson::Geometry(geometry) => vec![FeatureShapes::new(None, geometry)], @@ -156,29 +244,74 @@ fn calculate_shapes(geojson: &GeoJson) -> Vec { } } +/// The background of a [WorldMap]. +/// +/// The shapes are big, and a [Map] renders a lot while it is panned and zoomed. Comparing them +/// by reference lets yew skip them then. +#[derive(Properties, Clone, Derivative)] +#[derivative(PartialEq)] +struct WorldMapShapes { + #[derivative(PartialEq(compare_with = "Rc::ptr_eq"))] + shapes: Rc>, +} + +struct WorldMapShapesComp; + +impl Component for WorldMapShapesComp { + type Message = (); + type Properties = WorldMapShapes; + + fn create(_ctx: &Context) -> Self { + Self + } + + fn view(&self, ctx: &Context) -> Html { + let props = ctx.props(); + let features = props.shapes.iter().map(|feature| { + Group::new() + .class("pwt-world-map-feature") + .attribute("data-kind", feature.kind.clone()) + .children( + feature + .areas + .iter() + .map(|path| Path::new().d(path.clone()).into()), + ) + .children( + feature + .lines + .iter() + .map(|path| Path::new().d(path.clone()).fill("none").into()), + ) + .into() + }); + + Group::new().children(features).into() + } +} + +impl From for VNode { + fn from(val: WorldMapShapes) -> Self { + VComp::new::(Rc::new(val), None).into() + } +} + impl yew::Component for WorldMapComp { type Message = (); type Properties = WorldMap; fn create(ctx: &Context) -> Self { Self { - shapes: calculate_shapes(&ctx.props().map_data), + shapes: Rc::new(calculate_shapes(&ctx.props().map_data)), _phantom_data: PhantomData::, } } fn view(&self, ctx: &Context) -> Html { let props = ctx.props(); - let features = self.shapes.iter().map(|feature| { - Group::new() - .class("pwt-world-map-feature") - .attribute("data-kind", feature.kind.clone()) - .with_child(Path::new().d(feature.areas.clone())) - .with_child(Path::new().d(feature.lines.clone()).fill("none")) - .into() - }); + let shapes = Rc::clone(&self.shapes); - Map::new(Group::new().children(features)) + Map::new(WorldMapShapes { shapes }) .with_std_props(&props.std_props) .listeners(&props.listeners) .class("pwt-world-map") @@ -193,7 +326,7 @@ impl yew::Component for WorldMapComp { fn changed(&mut self, ctx: &Context, old_props: &Self::Properties) -> bool { let props = ctx.props(); if !Rc::ptr_eq(&props.map_data, &old_props.map_data) { - self.shapes = calculate_shapes(&props.map_data); + self.shapes = Rc::new(calculate_shapes(&props.map_data)); } true } @@ -208,46 +341,58 @@ fn project(location: Location) -> Coordinates { } } -fn ring_to_path(coordinates: &[Vec]) -> String { - let mut path = line_to_path(coordinates); - path.push('Z'); - path -} +#[cfg(test)] +mod test { + use geojson::{Geometry, Value}; -fn line_to_path(coordinates: &[Vec]) -> String { - let mut path = String::new(); - let mut prefix = "M"; - for list in coordinates { - if list.len() < 2 { - continue; - } - let Coordinates { x, y } = project(Location::new(list[0], list[1])); - path.push_str(&format!("{prefix}{:.2},{:.2}", x, y)); - prefix = "L"; + use super::FeatureShapes; + + // a square with the given corner and side length in degrees + fn square(longitude: f64, latitude: f64, size: f64) -> Vec> { + vec![ + vec![longitude, latitude], + vec![longitude + size, latitude], + vec![longitude + size, latitude + size], + vec![longitude, latitude + size], + vec![longitude, latitude], + ] } - path -} -fn parse_geometry(geometry: &Geometry, areas: &mut Vec, lines: &mut Vec) { - match &geometry.value { - geojson::Value::Polygon(polygon) => { - areas.append(&mut polygon.iter().map(|ring| ring_to_path(ring)).collect()); - } - geojson::Value::MultiPolygon(items) => { - for poly in items { - areas.append(&mut poly.iter().map(|ring| ring_to_path(ring)).collect()) - } - } - geojson::Value::LineString(line) => lines.push(line_to_path(line)), - geojson::Value::MultiLineString(line) => { - lines.append(&mut line.iter().map(|ring| line_to_path(ring)).collect()) - } - geojson::Value::GeometryCollection(items) => { - for geom in items { - parse_geometry(geom, areas, lines); - } - } - geojson::Value::Point(_) => {} - geojson::Value::MultiPoint(_) => {} + fn shapes(value: Value) -> (Vec, Vec) { + let shapes = FeatureShapes::new(None, &Geometry::new(value)); + let strings = |paths: &[yew::AttrValue]| -> Vec { + paths.iter().map(|path| path.to_string()).collect() + }; + (strings(&shapes.areas), strings(&shapes.lines)) + } + + #[test] + fn test_split_by_region() { + let europe = square(10.0, 40.0, 10.0); + let australia = square(130.0, -30.0, 10.0); + let europe_path = + "M1900.00,606.06L2000.00,606.06L2000.00,484.85L1900.00,484.85L1900.00,606.06"; + + // far apart, so they end up in a path each + let polygons = vec![vec![europe.clone()], vec![australia.clone()]]; + let (areas, lines) = shapes(Value::MultiPolygon(polygons)); + assert_eq!(areas.len(), 2); + assert_eq!(areas[0], format!("{europe_path}Z")); + assert!(lines.is_empty()); + + // a hole has to be in the path of its polygon, even if it is in another region + let hole = square(-170.0, -80.0, 1.0); + let polygons = vec![vec![europe.clone(), hole], vec![australia.clone()]]; + let (with_hole, _) = shapes(Value::MultiPolygon(polygons)); + assert_eq!(with_hole.len(), 2); + assert!(with_hole[0].starts_with(&areas[0])); + assert!(with_hole[0].len() > areas[0].len() && with_hole[0].ends_with('Z')); + assert_eq!(with_hole[1], areas[1]); + + // lines are not closed and each one is on its own + let (areas, lines) = shapes(Value::MultiLineString(vec![europe, australia])); + assert!(areas.is_empty()); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0], europe_path); } } -- 2.47.3