mlt-core 0.20.1

MapLibre Tile library code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Geometry section writer for tag `0x02` (v2) layers.

use super::model::VertexBufferType;
use super::streams::{
    dict_may_be_beneficial, encode_hilbert_vertex_streams02, encode_hilbert_xyz_vertex_streams02,
    encode_level1_length_stream, encode_level1_without_ring_buffer_length_stream,
    encode_level2_length_stream, encode_morton_vertex_streams02, encode_rans_vertex_stream02,
    encode_ring_lengths_for_mixed, encode_root_length_stream, encode_vec2_delta2_vertex_stream02,
    encode_vec2_vertex_stream02, encode_vec3_vertex_stream02, normalize_geometry_offsets,
    normalize_part_offsets_for_rings, seed_curve_caches, xyz_dict_may_be_beneficial,
};
use crate::decoder::GeometryType::{LineString, Point, Polygon};
use crate::decoder::stream::header02::{Family, WordWidth};
use crate::decoder::{
    GeoLayout, GeometryType, GeometryValues, LengthType, Levels, OffsetType, StreamType, Topology,
    VertexStorage, decode_topology, run_offsets,
};
use crate::encoder::model::StreamCtx;
use crate::encoder::{Codecs, Encoder};
use crate::tile::ZStep;
use crate::{Decoder, MltError, MltResult};

/// Wrap a computed length stream: an empty stream is not written (and not
/// declared by the layout), matching the v1 writer's skip-empty behavior.
fn non_empty(data: Vec<u32>) -> Option<Vec<u32>> {
    if data.is_empty() { None } else { Some(data) }
}

/// The triangle streams of a tessellated layer, which precede its vertices.
struct Tessellation {
    triangles: Vec<u32>,
    index_buffer: Vec<u32>,
}

/// Whether a tessellated layer keeps the outline topology next to its triangles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outlines {
    /// Keep every topology stream, as a layer with anything but polygons must.
    Keep,
    /// Drop them when every feature is a polygon, so only the triangles are stored.
    DropForPolygons,
}

/// The streams of a v2 geometry section, before the layout byte that declares them is settled.
pub(crate) struct GeometrySection02 {
    types: Vec<GeometryType>,
    geo_lengths: Option<Vec<u32>>,
    topology: Topology,
    tessellation: Option<Tessellation>,
    vertices: Vec<i32>,
    /// The grid of each vertex's third word, or [`None`] when the vertices are `(x, y)` pairs.
    z_step: Option<ZStep>,
}

/// Turn a layer's geometries into the v2 stream set.
pub(crate) fn encode_geometry02(
    geometry: GeometryValues,
    outlines: Outlines,
) -> MltResult<GeometrySection02> {
    let GeometryValues {
        vector_types,
        geometry_offsets,
        part_offsets,
        ring_offsets,
        index_buffer,
        triangle_offsets,
        vertices,
        z_step,
    } = geometry;

    let geom_offsets = geometry_offsets.unwrap_or_default();
    let part_offsets = part_offsets.unwrap_or_default();
    let ring_offsets = ring_offsets.unwrap_or_default();
    let vertices = vertices.unwrap_or_default();
    let triangles = triangle_offsets
        .unwrap_or_default()
        .windows(2)
        .map(|w| w[1] - w[0])
        .collect();
    let index_buffer = index_buffer.unwrap_or_default();

    // Same part-offset normalization as the v1 writer.
    let part_offsets = if geom_offsets.is_empty()
        && !ring_offsets.is_empty()
        && !part_offsets.is_empty()
        && part_offsets.len() != vector_types.len() + 1
    {
        normalize_part_offsets_for_rings(&vector_types, &part_offsets, &ring_offsets)
    } else {
        part_offsets
    };

    // Compute the length streams with the same branch structure as the v1
    // writer (`GeometryValues::write_to`); see there for the reasoning behind
    // each case.
    let mut geo_lengths: Option<Vec<u32>> = None;
    let mut part_lengths: Option<Vec<u32>> = None;
    let mut ring_lengths: Option<Vec<u32>> = None;

    if !geom_offsets.is_empty() {
        let geom_offsets = if geom_offsets.len() == vector_types.len() + 1 {
            geom_offsets
        } else {
            normalize_geometry_offsets(&vector_types, &geom_offsets)
        };
        geo_lengths = non_empty(encode_root_length_stream(
            &vector_types,
            &geom_offsets,
            Polygon,
        ));

        if !part_offsets.is_empty() {
            if ring_offsets.is_empty() {
                part_lengths = non_empty(encode_level1_without_ring_buffer_length_stream(
                    &vector_types,
                    &geom_offsets,
                    &part_offsets,
                ));
            } else {
                part_lengths = non_empty(encode_level1_length_stream(
                    &vector_types,
                    &geom_offsets,
                    &part_offsets,
                    false,
                ));
                ring_lengths = non_empty(encode_level2_length_stream(
                    &vector_types,
                    &geom_offsets,
                    &part_offsets,
                    &ring_offsets,
                ));
            }
        }
    } else if !part_offsets.is_empty() {
        if ring_offsets.is_empty() {
            part_lengths = non_empty(encode_root_length_stream(
                &vector_types,
                &part_offsets,
                Point,
            ));
        } else {
            part_lengths = non_empty(encode_root_length_stream(
                &vector_types,
                &part_offsets,
                LineString,
            ));
            let has_line_string = vector_types
                .iter()
                .copied()
                .any(GeometryType::is_linestring);
            ring_lengths = non_empty(encode_ring_lengths_for_mixed(
                &vector_types,
                &part_offsets,
                &ring_offsets,
                has_line_string,
            ));
        }
    }

    let mut topology = match (part_lengths, ring_lengths) {
        (None, None) => Topology::Flat,
        (Some(parts), None) => Topology::Parts(parts),
        (Some(parts), Some(rings)) => Topology::PartsAndRings { parts, rings },
        (None, Some(_)) => return Err(MltError::RingLengthsWithoutPartLengths),
    };

    // An empty index buffer means no polygon tessellated into a triangle, so the layer
    // keeps a plain layout: dropping the streams is lossless.
    let tessellation = (!index_buffer.is_empty()).then_some(Tessellation {
        triangles,
        index_buffer,
    });
    // The tessellated layouts declare all three topology streams or none, so a layer
    // missing one fills the gap with an empty stream rather than dropping the others:
    // the decoder then rebuilds what the stream would have said.
    if tessellation.is_some() {
        let polygons_only = vector_types.iter().all(|t| t.is_polygon());
        if outlines == Outlines::DropForPolygons && polygons_only {
            topology = Topology::Flat;
            geo_lengths = None;
        } else {
            topology = topology.with_rings();
            geo_lengths.get_or_insert_with(Vec::new);
        }
    }

    Ok(GeometrySection02 {
        types: vector_types,
        geo_lengths,
        topology,
        tessellation,
        vertices,
        z_step,
    })
}

/// What a written geometry section puts in the layer's two header bytes.
pub(crate) struct GeometryHeader02 {
    pub(crate) layout: GeoLayout,
    /// The type every feature has, when the section wrote no types stream.
    pub(crate) uniform_type: Option<GeometryType>,
}

impl GeometrySection02 {
    /// The one type every feature has, when they share one.
    ///
    /// Such a types stream is a single run saying nothing the header byte's nibble
    /// cannot, so the section drops it and the nibble carries the type instead.
    fn uniform_type(&self) -> Option<GeometryType> {
        let (first, rest) = self.types.split_first()?;
        rest.iter().all(|t| t == first).then_some(*first)
    }

    /// Where the vertex runs start that the decoder will rebuild from these streams,
    /// which rANS vertices are coded over.
    fn run_offsets(&self) -> MltResult<Option<Vec<u32>>> {
        let (parts, rings) = self.topology.streams();
        let lengths = Levels {
            geometries: self.geo_lengths.clone(),
            parts: parts.map(<[u32]>::to_vec),
            rings: rings.map(<[u32]>::to_vec),
        };
        let levels = decode_topology(&self.types, lengths, &mut Decoder::with_max_size(u32::MAX))?;
        Ok(run_offsets(&levels).map(<[u32]>::to_vec))
    }

    /// The layout declaring these streams, once the vertex storage is known.
    fn layout(&self, vertices: VertexStorage) -> GeoLayout {
        if self.tessellation.is_some() {
            GeoLayout::tessellated(self.geo_lengths.is_some())
        } else {
            GeoLayout::from_topology(&self.topology, self.geo_lengths.is_some(), vertices)
        }
    }

    /// Write the geometry streams to `enc` and return what the header bytes must say.
    ///
    /// The layout is only known once the vertex streams are written, since the
    /// dictionary layouts are picked by writing them and keeping the shortest, so
    /// the caller patches the layout byte it reserved before this call.
    ///
    /// Expects `enc.count_context` to hold the layer's `feature_count`.
    pub(crate) fn write_to(
        self,
        enc: &mut Encoder,
        codecs: &mut Codecs,
    ) -> MltResult<GeometryHeader02> {
        // Types and length streams are integer streams, only the vertex streams have their own family.
        enc.family_context = Family::Int(WordWidth::W32);

        // Types stream: implicit count = feature_count (the current count context).
        // A layer whose features share a type writes the header byte's nibble instead.
        let uniform_type = self.uniform_type();
        if uniform_type.is_none() {
            let types: Vec<u32> = self.types.iter().map(|t| *t as u32).collect();
            let ctx = StreamCtx::geom(StreamType::Length(LengthType::VarBinary), "meta");
            codecs.write_int_stream(&types, &ctx, enc)?;
        }

        let (part_lengths, ring_lengths) = self.topology.streams();
        let lengths = [
            (
                self.geo_lengths.as_deref(),
                LengthType::Geometries,
                "geometries",
            ),
            (part_lengths, LengthType::Parts, "parts"),
            (ring_lengths, LengthType::Rings, "rings"),
        ];
        for (stream, length_type, name) in lengths {
            if let Some(data) = stream {
                let ctx = StreamCtx::geom(StreamType::Length(length_type), name);
                codecs.write_int_stream(data, &ctx, enc)?;
            }
        }

        if let Some(tess) = &self.tessellation {
            let ctx = StreamCtx::geom(StreamType::Length(LengthType::Triangles), "triangles");
            codecs.write_int_stream(&tess.triangles, &ctx, enc)?;
            let ctx = StreamCtx::geom(StreamType::Offset(OffsetType::Index), "triangles_indexes");
            codecs.write_int_stream(&tess.index_buffer, &ctx, enc)?;
        }

        let tessellated = self.tessellation.is_some();
        let vertices = match self.z_step {
            Some(step) => write_xyz_vertices(&self.vertices, step, tessellated, enc, codecs)?,
            None => write_vertices(
                &self.vertices,
                &|| self.run_offsets(),
                tessellated,
                enc,
                codecs,
            )?,
        };
        Ok(GeometryHeader02 {
            layout: self.layout(vertices),
            uniform_type,
        })
    }
}

/// Write the vertex streams and report the storage they used.
///
/// Tessellated layers keep their vertices plain: no layout code pairs a triangle
/// buffer with a vertex dictionary, so a forced dictionary falls back to [`VertexBufferType::Vec2`].
fn write_vertices(
    vertices: &[i32],
    runs: &dyn Fn() -> MltResult<Option<Vec<u32>>>,
    tessellated: bool,
    enc: &mut Encoder,
    codecs: &mut Codecs,
) -> MltResult<VertexStorage> {
    seed_curve_caches(enc, vertices);
    enc.family_context = Family::Vertex;

    match (enc.override_vertex_buffer_type(), tessellated) {
        (Some(VertexBufferType::Rans), _) => {
            encode_rans_vertex_stream02(vertices, runs()?.as_deref(), enc)?;
            return Ok(VertexStorage::Plain);
        }
        (Some(_), true) | (Some(VertexBufferType::Vec2), false) => {
            encode_vec2_vertex_stream02(vertices, enc, codecs)?;
            return Ok(VertexStorage::Plain);
        }
        (None, true) => {
            write_plain_vertices(vertices, runs, enc, codecs)?;
            return Ok(VertexStorage::Plain);
        }
        (Some(VertexBufferType::Morton), false) => {
            encode_morton_vertex_streams02(vertices, enc, codecs)?;
            return Ok(VertexStorage::Dict);
        }
        (Some(VertexBufferType::Hilbert), false) => {
            encode_hilbert_vertex_streams02(vertices, enc, codecs)?;
            return Ok(VertexStorage::Dict);
        }
        (None, false) => {}
    }

    if !dict_may_be_beneficial(vertices, enc) {
        write_plain_vertices(vertices, runs, enc, codecs)?;
        return Ok(VertexStorage::Plain);
    }

    // Morton fits (the gate above ensures it), so race all three layouts and keep
    // the shortest, as the v1 writer does.
    keep_shortest(
        enc,
        codecs,
        &[
            (VertexStorage::Plain, &|enc, codecs| {
                write_plain_vertices(vertices, runs, enc, codecs)
            }),
            (VertexStorage::Dict, &|enc, codecs| {
                encode_hilbert_vertex_streams02(vertices, enc, codecs)
            }),
            (VertexStorage::Dict, &|enc, codecs| {
                encode_morton_vertex_streams02(vertices, enc, codecs)
            }),
        ],
    )
}

/// A way of writing a layer's vertex streams, and the storage it declares.
type VertexCandidate<'a> = (
    VertexStorage,
    &'a dyn Fn(&mut Encoder, &mut Codecs) -> MltResult<()>,
);

/// Write every candidate, keep the one that stores the fewest bytes, and report its storage.
fn keep_shortest(
    enc: &mut Encoder,
    codecs: &mut Codecs,
    candidates: &[VertexCandidate<'_>],
) -> MltResult<VertexStorage> {
    let mut winner = VertexStorage::Plain;
    let mut winner_size = usize::MAX;
    let mut alt = enc.try_alternatives();
    for &(storage, write) in candidates {
        alt.with(|enc| {
            let (data, meta) = (enc.data().len(), enc.meta().len());
            enc.family_context = Family::Vertex;
            write(enc, codecs)?;
            let size = (enc.data().len() - data) + (enc.meta().len() - meta);
            if size < winner_size {
                winner = storage;
                winner_size = size;
            }
            Ok(())
        })?;
    }
    drop(alt);
    Ok(winner)
}

/// Write `(x, y, z)` vertex streams and report the storage they used.
///
/// A Morton code spans only `x` and `y`, so the plain triples race only the Hilbert dictionary.
fn write_xyz_vertices(
    vertices: &[i32],
    step: ZStep,
    tessellated: bool,
    enc: &mut Encoder,
    codecs: &mut Codecs,
) -> MltResult<VertexStorage> {
    if enc.hilbert_cache.is_none() || enc.morton_cache.is_none() {
        let xy: Vec<i32> = vertices
            .as_chunks::<3>()
            .0
            .iter()
            .flat_map(|&[x, y, _]| [x, y])
            .collect();
        seed_curve_caches(enc, &xy);
    }
    enc.family_context = Family::Vertex;

    if tessellated {
        encode_vec3_vertex_stream02(vertices, step, enc, codecs)?;
        return Ok(VertexStorage::Plain);
    }

    if let Some(forced) = enc.override_vertex_buffer_type() {
        return match forced {
            VertexBufferType::Vec2 => {
                encode_vec3_vertex_stream02(vertices, step, enc, codecs)?;
                Ok(VertexStorage::Plain)
            }
            VertexBufferType::Hilbert => {
                encode_hilbert_xyz_vertex_streams02(vertices, step, enc, codecs)?;
                Ok(VertexStorage::Dict)
            }
            VertexBufferType::Morton => Err(MltError::NotImplemented(
                "Morton vertices with z coordinates, since a Morton code spans only x and y",
            )),
            VertexBufferType::Rans => Err(MltError::NotImplemented(
                "rANS vertices with z coordinates, since its tables are defined over pairs",
            )),
        };
    }

    if !xyz_dict_may_be_beneficial(vertices, enc) {
        encode_vec3_vertex_stream02(vertices, step, enc, codecs)?;
        return Ok(VertexStorage::Plain);
    }

    keep_shortest(
        enc,
        codecs,
        &[
            (VertexStorage::Plain, &|enc, codecs| {
                encode_vec3_vertex_stream02(vertices, step, enc, codecs)
            }),
            (VertexStorage::Dict, &|enc, codecs| {
                encode_hilbert_xyz_vertex_streams02(vertices, step, enc, codecs)
            }),
        ],
    )
}

/// The plain vertex stream the encoder picks itself: componentwise delta, raced against second-order deltas and rANS when the config allows them.
fn write_plain_vertices(
    vertices: &[i32],
    runs: &dyn Fn() -> MltResult<Option<Vec<u32>>>,
    enc: &mut Encoder,
    codecs: &mut Codecs,
) -> MltResult<()> {
    let allow_delta2 = enc.config().allow_delta2();
    let allow_rans = enc.config().allow_rans_vertices();
    if vertices.is_empty() || !(allow_delta2 || allow_rans) {
        return encode_vec2_vertex_stream02(vertices, enc, codecs);
    }
    let offsets = if allow_rans { runs()? } else { None };
    let mut alt = enc.try_alternatives();
    alt.with(|enc| encode_vec2_vertex_stream02(vertices, enc, codecs))?;
    if allow_delta2 {
        alt.with(|enc| encode_vec2_delta2_vertex_stream02(vertices, enc, codecs))?;
    }
    if allow_rans {
        alt.with(|enc| encode_rans_vertex_stream02(vertices, offsets.as_deref(), enc))?;
    }
    Ok(())
}