use std::collections::HashMap;
use prost::Message;
use crate::layer::Layer;
use crate::tile::feature::{GeomType, PropValue, TILE_EXTENT, TileFeature};
pub mod proto {
include!(concat!(env!("OUT_DIR"), "/vector_tile.rs"));
}
#[must_use]
pub fn encode_tile(features: &[TileFeature]) -> Vec<u8> {
let mut by_layer: HashMap<Layer, Vec<&TileFeature>> = HashMap::new();
for f in features {
by_layer.entry(f.layer).or_default().push(f);
}
let mut layers: Vec<proto::tile::Layer> = Vec::with_capacity(by_layer.len());
for layer_id in Layer::ALL {
let Some(layer_features) = by_layer.get(&layer_id) else {
continue;
};
let mut keys: Vec<String> = Vec::with_capacity(8);
let mut values: Vec<proto::tile::Value> = Vec::with_capacity(16);
let mut key_index: HashMap<&str, u32> = HashMap::new();
let mut value_index: HashMap<PropValueKey<'_>, u32> = HashMap::new();
let mut mvt_features: Vec<proto::tile::Feature> = Vec::with_capacity(layer_features.len());
for feat in layer_features {
let mut tags: Vec<u32> = Vec::with_capacity(feat.properties.len() * 2);
for (k, v) in feat.properties.iter() {
let ki = *key_index.entry(k.as_str()).or_insert_with(|| {
let idx = keys.len() as u32;
keys.push(k.clone());
idx
});
let vk = PropValueKey::from(v);
let vi = *value_index.entry(vk).or_insert_with(|| {
let idx = values.len() as u32;
values.push(prop_to_mvt_value(v));
idx
});
tags.push(ki);
tags.push(vi);
}
mvt_features.push(proto::tile::Feature {
id: if feat.id != 0 { Some(feat.id) } else { None },
tags,
r#type: Some(geom_type_to_mvt(feat.geom_type) as i32),
geometry: feat.geometry.clone(),
});
}
layers.push(proto::tile::Layer {
version: 2,
name: layer_id.name().to_string(),
features: mvt_features,
keys,
values,
extent: Some(TILE_EXTENT),
});
}
let tile = proto::Tile { layers };
tile.encode_to_vec()
}
#[must_use]
pub fn encode_points(coords: &[(i32, i32)]) -> Vec<u32> {
if coords.is_empty() {
return Vec::new();
}
let mut cmds = Vec::with_capacity(1 + coords.len() * 2);
cmds.push(command(1, coords.len() as u32));
let mut cx = 0i32;
let mut cy = 0i32;
for &(x, y) in coords {
let dx = x - cx;
let dy = y - cy;
cmds.push(zigzag(dx));
cmds.push(zigzag(dy));
cx = x;
cy = y;
}
cmds
}
#[must_use]
pub fn encode_linestring(coords: &[(i32, i32)]) -> Vec<u32> {
if coords.len() < 2 {
return Vec::new();
}
let mut cmds = Vec::with_capacity(3 + (coords.len() - 1) * 2);
let mut cx = 0i32;
let mut cy = 0i32;
push_line_part(&mut cmds, &mut cx, &mut cy, coords);
cmds
}
#[must_use]
pub fn encode_multilinestring(parts: &[Vec<(i32, i32)>]) -> Vec<u32> {
let total_coords: usize = parts.iter().map(|p| p.len()).sum();
let mut cmds = Vec::with_capacity(total_coords * 2 + parts.len() * 2);
let mut cx = 0i32;
let mut cy = 0i32;
for part in parts {
if part.len() < 2 {
continue;
}
push_line_part(&mut cmds, &mut cx, &mut cy, part);
}
cmds
}
fn push_line_part(cmds: &mut Vec<u32>, cx: &mut i32, cy: &mut i32, coords: &[(i32, i32)]) {
cmds.push(command(1, 1));
let dx = coords[0].0 - *cx;
let dy = coords[0].1 - *cy;
cmds.push(zigzag(dx));
cmds.push(zigzag(dy));
*cx = coords[0].0;
*cy = coords[0].1;
cmds.push(command(2, (coords.len() - 1) as u32));
for &(x, y) in &coords[1..] {
let dx = x - *cx;
let dy = y - *cy;
cmds.push(zigzag(dx));
cmds.push(zigzag(dy));
*cx = x;
*cy = y;
}
}
#[must_use]
pub fn encode_polygon(rings: &[Vec<(i32, i32)>]) -> Vec<u32> {
let total_coords: usize = rings.iter().map(|r| r.len()).sum();
let mut cmds = Vec::with_capacity(total_coords * 2 + rings.len() * 3);
let mut cx = 0i32;
let mut cy = 0i32;
for ring in rings {
if ring.len() < 3 {
continue;
}
let points = if ring.first() == ring.last() {
&ring[..ring.len() - 1]
} else {
ring.as_slice()
};
if points.len() < 3 {
continue;
}
cmds.push(command(1, 1));
let dx = points[0].0 - cx;
let dy = points[0].1 - cy;
cmds.push(zigzag(dx));
cmds.push(zigzag(dy));
cx = points[0].0;
cy = points[0].1;
cmds.push(command(2, (points.len() - 1) as u32));
for &(x, y) in &points[1..] {
let dx = x - cx;
let dy = y - cy;
cmds.push(zigzag(dx));
cmds.push(zigzag(dy));
cx = x;
cy = y;
}
cmds.push(command(7, 1));
}
cmds
}
#[must_use]
pub fn decode_commands(commands: &[u32]) -> Vec<Vec<(i32, i32)>> {
let mut parts: Vec<Vec<(i32, i32)>> = Vec::new();
let mut current: Vec<(i32, i32)> = Vec::new();
let mut cx = 0i32;
let mut cy = 0i32;
let mut i = 0usize;
while i < commands.len() {
let cmd = commands[i] & 0x7;
let count = (commands[i] >> 3) as usize;
i += 1;
match cmd {
1 | 2 => {
for _ in 0..count {
if i >= commands.len() {
return parts_finish(parts, current);
}
let dx = zigzag_decode(commands[i]);
i += 1;
if i >= commands.len() {
return parts_finish(parts, current);
}
let dy = zigzag_decode(commands[i]);
i += 1;
cx += dx;
cy += dy;
if cmd == 1 {
if count > 1 {
parts.push(vec![(cx, cy)]);
} else {
if !current.is_empty() {
parts.push(std::mem::take(&mut current));
}
current.push((cx, cy));
}
} else {
current.push((cx, cy));
}
}
}
7 => {
if !current.is_empty() {
parts.push(std::mem::take(&mut current));
}
}
_ => {
return parts_finish(parts, current);
}
}
}
parts_finish(parts, current)
}
fn parts_finish(mut parts: Vec<Vec<(i32, i32)>>, current: Vec<(i32, i32)>) -> Vec<Vec<(i32, i32)>> {
if !current.is_empty() {
parts.push(current);
}
parts
}
#[inline]
const fn command(id: u32, count: u32) -> u32 {
(id & 0x7) | (count << 3)
}
#[inline]
const fn zigzag(n: i32) -> u32 {
((n << 1) ^ (n >> 31)) as u32
}
#[inline]
const fn zigzag_decode(v: u32) -> i32 {
((v >> 1) as i32) ^ -((v & 1) as i32)
}
const fn geom_type_to_mvt(gt: GeomType) -> proto::tile::GeomType {
match gt {
GeomType::Point => proto::tile::GeomType::Point,
GeomType::Line => proto::tile::GeomType::Linestring,
GeomType::Polygon => proto::tile::GeomType::Polygon,
}
}
fn prop_to_mvt_value(v: &PropValue) -> proto::tile::Value {
match v {
PropValue::Str(s) => proto::tile::Value {
string_value: Some(s.clone()),
..Default::default()
},
PropValue::F64(f) => proto::tile::Value {
double_value: Some(*f),
..Default::default()
},
PropValue::I64(i) => proto::tile::Value {
sint_value: Some(*i),
..Default::default()
},
PropValue::U64(u) => proto::tile::Value {
uint_value: Some(*u),
..Default::default()
},
PropValue::Bool(b) => proto::tile::Value {
bool_value: Some(*b),
..Default::default()
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum PropValueKey<'a> {
Str(&'a str),
F64(u64),
I64(i64),
U64(u64),
Bool(bool),
}
impl<'a> From<&'a PropValue> for PropValueKey<'a> {
fn from(v: &'a PropValue) -> Self {
match v {
PropValue::Str(s) => Self::Str(s),
PropValue::F64(f) => Self::F64(f.to_bits()),
PropValue::I64(i) => Self::I64(*i),
PropValue::U64(u) => Self::U64(*u),
PropValue::Bool(b) => Self::Bool(*b),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn decode_commands_reads_the_spec_examples() {
assert_eq!(decode_commands(&[9, 50, 34]), vec![vec![(25, 17)]]);
assert_eq!(
decode_commands(&[17, 10, 14, 3, 9]),
vec![vec![(5, 7)], vec![(3, 2)]]
);
assert_eq!(
decode_commands(&[9, 4, 4, 18, 0, 16, 16, 0]),
vec![vec![(2, 2), (2, 10), (10, 10)]]
);
assert_eq!(
decode_commands(&[9, 4, 4, 18, 0, 16, 16, 0, 9, 17, 17, 10, 4, 8]),
vec![vec![(2, 2), (2, 10), (10, 10)], vec![(1, 1), (3, 5)]]
);
assert_eq!(
decode_commands(&[9, 6, 12, 18, 10, 12, 24, 44, 15]),
vec![vec![(3, 6), (8, 12), (20, 34)]]
);
}
#[test]
fn encode_multilinestring_writes_the_spec_example() {
let parts = vec![vec![(2, 2), (2, 10), (10, 10)], vec![(1, 1), (3, 5)]];
assert_eq!(
encode_multilinestring(&parts),
[9, 4, 4, 18, 0, 16, 16, 0, 9, 17, 17, 10, 4, 8]
);
assert_eq!(encode_multilinestring(&[vec![(7, 7)]]), Vec::<u32>::new());
}
#[test]
fn decode_commands_stops_at_a_truncated_or_unknown_command() {
assert_eq!(
decode_commands(&[9, 4, 4, 18, 0, 16]),
vec![vec![(2, 2), (2, 10)]]
);
assert_eq!(decode_commands(&[9, 4]), Vec::<Vec<(i32, i32)>>::new());
assert_eq!(decode_commands(&[9, 4, 4, 3, 1, 1]), vec![vec![(2, 2)]]);
assert_eq!(decode_commands(&[10, 4, 4]), vec![vec![(2, 2)]]);
assert_eq!(decode_commands(&[9, 4, 4, 15, 15]), vec![vec![(2, 2)]]);
}
use std::sync::Arc;
use super::*;
#[test]
fn zigzag_encoding() {
assert_eq!(zigzag(0), 0);
assert_eq!(zigzag(-1), 1);
assert_eq!(zigzag(1), 2);
assert_eq!(zigzag(-2), 3);
assert_eq!(zigzag(2), 4);
}
#[test]
fn command_encoding() {
assert_eq!(command(1, 1), 9); assert_eq!(command(2, 3), 26); assert_eq!(command(7, 1), 15); }
#[test]
fn encode_single_point() {
let cmds = encode_points(&[(100, 200)]);
assert_eq!(cmds.len(), 3);
}
#[test]
fn encode_tile_basic() {
let features = vec![TileFeature {
layer: Layer::Buildings,
id: 1,
geom_type: GeomType::Polygon,
geometry: encode_polygon(&[vec![(0, 0), (100, 0), (100, 100), (0, 100), (0, 0)]]),
properties: Arc::new(vec![
("kind".to_string(), PropValue::Str("building".to_string())),
("height".to_string(), PropValue::F64(10.5)),
]),
sort_key: 0,
}];
let bytes = encode_tile(&features);
assert!(!bytes.is_empty());
let tile = proto::Tile::decode(bytes.as_slice()).expect("valid protobuf");
assert_eq!(tile.layers.len(), 1);
assert_eq!(tile.layers[0].name, "buildings");
assert_eq!(tile.layers[0].features.len(), 1);
assert_eq!(tile.layers[0].keys, vec!["kind", "height"]);
}
}