1use std::any::Any;
10use std::marker::PhantomData;
11use std::sync::Arc;
12
13use mln_style::Source;
14use mln_style::bitmap::PremultipliedImage;
15use mln_style::crs::WorldMapping;
16use mln_style::error::Error;
17use mln_style::layer::SourceKind;
18use mln_style::source::dynamic::DynamicStyleSourceType;
19use mln_style::source::{ErasedDescription, ErasedStyleSourceType};
20use mln_style::tileset::{RasterEncoding, Tileset};
21
22use crate::exec::pool::Pool;
23use crate::query::FeatureExtensionValue;
24use crate::source::erased::{DescribeImageJob, DescribeJob, ErasedOrigin, ErasedSourceType, UpdateParts};
25use crate::source::{
26 Cover, Described, Load, MapSettings, OfflineResources, Replier, Respond, SourceSummary, Supplied, TileNecessity,
27 TileOperation, TileTimes,
28};
29use crate::storage::Data;
30use crate::storage::resource::RequestOrder;
31use crate::tile::{OverscaledTileID, TileData};
32use crate::tile_store::tile_mut::{CopyAnswer, TileMut};
33
34pub enum DynamicTileItem {
36 Geometry(TileData),
37 Raster(Data),
38 Dem(Data),
39}
40
41pub struct DynamicOriginUpdate<'a> {
43 parts: UpdateParts<'a>,
44 kind: SourceKind,
45}
46
47impl<'a> DynamicOriginUpdate<'a> {
48 #[must_use]
49 pub fn source(&self) -> &'a Source {
50 self.parts.source
51 }
52
53 #[must_use]
54 pub fn map(&self) -> &MapSettings {
55 self.parts.map
56 }
57
58 #[must_use]
59 pub fn pool(&self) -> &Pool {
60 self.parts.ctx.pool.pool()
61 }
62
63 #[must_use]
64 pub fn needs_relayout(&self) -> bool {
65 self.parts.needs_relayout
66 }
67
68 pub fn clear_tiles(&mut self) {
69 self.parts.tiles.clear_all(self.parts.ctx);
70 }
71
72 pub fn clear_cache(&mut self) {
73 self.parts.tiles.reduce_memory_use(self.parts.ctx);
74 }
75
76 pub fn set_encoding(&mut self, encoding: RasterEncoding) {
78 self.parts.tiles.info.dem_encoding = encoding;
79 }
80
81 pub fn update_tiles(
83 &mut self,
84 filter: impl Fn(&OverscaledTileID) -> bool,
85 mut f: impl FnMut(&mut dyn Any, &mut DynamicLoadContext<'_, '_>),
86 ) {
87 let kind = self.kind;
88 self.parts.tiles.update_each(
89 self.parts.ctx,
90 |slot| !slot.place().is_cached() && filter(&slot.tile.id),
91 |tile| {
92 tile.with_state(|state, tile| {
93 let mut cx = DynamicLoadContext::new(tile, kind);
94 f(state, &mut cx);
95 });
96 },
97 );
98 }
99}
100
101pub struct DynamicLoadContext<'a, 't> {
103 tile: &'a mut TileMut<'t>,
104 kind: SourceKind,
105}
106
107impl<'a, 't> DynamicLoadContext<'a, 't> {
108 fn new(tile: &'a mut TileMut<'t>, kind: SourceKind) -> Self {
109 DynamicLoadContext { tile, kind }
110 }
111
112 #[must_use]
113 pub fn id(&self) -> &OverscaledTileID {
114 &self.tile.tile().id
115 }
116
117 #[must_use]
118 pub fn necessity(&self) -> TileNecessity {
119 self.tile.tile().load.necessity
120 }
121
122 #[must_use]
123 pub fn order(&self) -> RequestOrder {
124 self.tile.tile().load.order.clone()
125 }
126
127 #[must_use]
128 pub fn is_renderable(&self) -> bool {
129 self.tile.tile().is_renderable()
130 }
131
132 pub fn set_times(&mut self, times: TileTimes) {
133 self.tile.tile_mut().load.times = times;
134 }
135
136 pub fn begin_load(&mut self) -> Replier<Box<dyn Any + Send>> {
139 let load = self.tile.next();
140 let tile = self.tile.tile_mut();
141 tile.load.current = Some(load);
142 tile.load.failed = false;
143 let tile = self.tile.key();
144 Replier { inbox: self.tile.store().inbox.clone(), tile, load, reply: PhantomData }
145 }
146
147 pub fn deliver(&mut self, item: Option<DynamicTileItem>) {
150 self.tile.tile_mut().load.failed = false;
151 match (self.kind, item) {
152 (SourceKind::Geometry, Some(DynamicTileItem::Geometry(data))) => self.tile.take_data(Some(data), false),
153 (SourceKind::Geometry, None) => self.tile.take_data(None, false),
154 (SourceKind::Raster, Some(DynamicTileItem::Raster(data)))
155 | (SourceKind::RasterDem, Some(DynamicTileItem::Dem(data))) => self.tile.take_image(Some(data), false),
156 (SourceKind::Raster | SourceKind::RasterDem, None) => self.tile.take_image(None, false),
157 _ => {
158 self.tile.fail(Error::failed("dynamic source delivered a tile item of the wrong source kind"));
159 }
160 }
161 }
162
163 pub fn missing(&mut self) {
164 self.tile.tile_mut().load.failed = false;
165 self.tile.take_missing();
166 }
167
168 pub fn fail(&mut self, error: Error) {
169 self.tile.fail(error);
170 }
171
172 pub fn fail_retrying(&mut self, error: Error) {
173 self.tile.tile_mut().load.failed = true;
174 self.tile.fail(error);
175 }
176
177 pub fn keep_data(&mut self) {
178 self.tile.tile_mut().load.failed = false;
179 self.tile.keep_data();
180 }
181
182 pub fn tried_optional(&mut self) {
183 self.tile.tile_mut().load.tried_optional = true;
184 }
185
186 pub fn report(&mut self, op: TileOperation) {
189 if matches!(
190 op,
191 TileOperation::RequestedFromCache
192 | TileOperation::RequestedFromNetwork
193 | TileOperation::LoadFromCache
194 | TileOperation::LoadFromNetwork
195 ) {
196 self.tile.action(op);
197 }
198 }
199
200 pub fn changed(&mut self) {
201 self.tile.store_mut().changed();
202 }
203
204 pub fn reset(&mut self) {
206 if self.kind == SourceKind::Geometry {
207 self.tile.reset();
208 }
209 }
210}
211
212pub struct DynamicWorldCopy<'a> {
214 state: &'a dyn Any,
215 answer: Option<CopyAnswer>,
216}
217
218impl<'a> DynamicWorldCopy<'a> {
219 #[must_use]
220 pub fn state(&self) -> &'a dyn Any {
221 self.state
222 }
223
224 pub fn take_into(self, cx: &mut DynamicLoadContext<'_, '_>) -> bool {
225 let Some(answer) = self.answer else {
226 return false;
227 };
228 cx.tile.take_copy(answer);
229 true
230 }
231}
232
233pub trait DynamicOrigin: 'static {
235 fn kind(&self) -> SourceKind;
236
237 fn update(&mut self, update: &mut DynamicOriginUpdate<'_>) -> Option<Cover>;
238
239 fn start(&mut self, cx: &mut DynamicLoadContext<'_, '_>, copy: Option<DynamicWorldCopy<'_>>) -> Box<dyn Any>;
240
241 fn receive(&mut self, _tile: &mut dyn Any, _reply: Box<dyn Any + Send>, _cx: &mut DynamicLoadContext<'_, '_>) {}
242
243 fn set_necessity(&mut self, _tile: &mut dyn Any, _previous: TileNecessity, _cx: &mut DynamicLoadContext<'_, '_>) {}
244
245 fn retry(&mut self, _tile: &mut dyn Any, _cx: &mut DynamicLoadContext<'_, '_>) {}
246
247 fn failed(&mut self, _tile: &mut dyn Any, _cx: &mut DynamicLoadContext<'_, '_>) {}
248}
249
250struct DynamicOriginAdapter(Box<dyn DynamicOrigin>);
251
252impl ErasedOrigin for DynamicOriginAdapter {
253 fn kind(&self) -> SourceKind {
254 self.0.kind()
255 }
256
257 fn update(&mut self, parts: UpdateParts<'_>) -> Option<Cover> {
258 let kind = self.0.kind();
259 self.0.update(&mut DynamicOriginUpdate { parts, kind })
260 }
261
262 fn start(&mut self, copy: Option<(&dyn Any, Option<CopyAnswer>)>, tile: &mut TileMut<'_>) -> Box<dyn Any> {
263 let kind = self.0.kind();
264 let copy = copy.map(|(state, answer)| DynamicWorldCopy { state, answer });
265 self.0.start(&mut DynamicLoadContext::new(tile, kind), copy)
266 }
267
268 fn receive(&mut self, state: &mut dyn Any, reply: Box<dyn Any + Send>, tile: &mut TileMut<'_>) {
269 let kind = self.0.kind();
270 let reply = match reply.downcast::<Box<dyn Any + Send>>() {
274 Ok(inner) => *inner,
275 Err(other) => other,
276 };
277 self.0.receive(state, reply, &mut DynamicLoadContext::new(tile, kind));
278 }
279
280 fn set_necessity(&mut self, state: &mut dyn Any, previous: TileNecessity, tile: &mut TileMut<'_>) {
281 let kind = self.0.kind();
282 self.0.set_necessity(state, previous, &mut DynamicLoadContext::new(tile, kind));
283 }
284
285 fn retry(&mut self, state: &mut dyn Any, tile: &mut TileMut<'_>) {
286 let kind = self.0.kind();
287 self.0.retry(state, &mut DynamicLoadContext::new(tile, kind));
288 }
289
290 fn failed(&mut self, state: &mut dyn Any, tile: &mut TileMut<'_>) {
291 let kind = self.0.kind();
292 self.0.failed(state, &mut DynamicLoadContext::new(tile, kind));
293 }
294}
295
296pub trait DynamicSourceHandler: Send + Sync + 'static {
298 fn supply(&self, source: &Source) -> Box<dyn DynamicOrigin>;
299
300 fn attribution(&self, _source: &Source) -> Option<String> {
301 None
302 }
303
304 fn summary(&self, _source: &Source) -> SourceSummary {
305 SourceSummary::default()
306 }
307
308 fn load(&self, _source: &Source) -> Load<ErasedDescription> {
309 Load::Done
310 }
311
312 fn describes_in_background(&self) -> bool {
313 false
314 }
315
316 fn describes_in_world(&self) -> bool {
317 false
318 }
319
320 fn describe(
321 &self,
322 _source: &Source,
323 _world: &WorldMapping,
324 _data: Option<Data>,
325 respond: Respond<Described<ErasedDescription>>,
326 ) {
327 respond(Err(Error::failed("this dynamic source fetches nothing")));
328 }
329
330 fn describe_image(&self, _source: &Source, _image: PremultipliedImage) -> Described<ErasedDescription> {
331 Err(Error::failed("this dynamic source fetches no image"))
332 }
333
334 fn metadata_changed(&self, _previous: &Source, _source: &Source) -> bool {
335 false
336 }
337}
338
339#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
341pub enum DynamicSourceTypeError {
342 #[error("dynamic source type '{0}' must feed layers of one source kind")]
343 InvalidSourceKind(String),
344}
345
346pub struct DynamicSourceType {
348 style: &'static DynamicStyleSourceType,
349 handler: Arc<dyn DynamicSourceHandler>,
350}
351
352impl std::fmt::Debug for DynamicSourceType {
353 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354 f.debug_struct("DynamicSourceType").field("style", &self.style).finish_non_exhaustive()
355 }
356}
357
358impl DynamicSourceType {
359 pub fn leak(
362 style: &'static DynamicStyleSourceType,
363 handler: Arc<dyn DynamicSourceHandler>,
364 ) -> Result<&'static Self, DynamicSourceTypeError> {
365 if matches!(style.info().layer_kind, SourceKind::None | SourceKind::Any) {
366 return Err(DynamicSourceTypeError::InvalidSourceKind(style.info().name.to_owned()));
367 }
368 Ok(Box::leak(Box::new(DynamicSourceType { style, handler })))
369 }
370
371 #[must_use]
372 pub fn style_type(&self) -> &'static DynamicStyleSourceType {
373 self.style
374 }
375}
376
377impl ErasedSourceType for DynamicSourceType {
378 fn style(&self) -> &'static dyn ErasedStyleSourceType {
379 self.style
380 }
381
382 fn supply(&self, source: &Source) -> Supplied {
383 Supplied::Tiles(Box::new(DynamicOriginAdapter(self.handler.supply(source))))
384 }
385
386 fn plan_load(&self, source: &Source) -> Load<ErasedDescription> {
387 self.handler.load(source)
388 }
389
390 fn describes_in_background(&self) -> bool {
391 self.handler.describes_in_background()
392 }
393
394 fn describes_in_world(&self) -> bool {
395 self.handler.describes_in_world()
396 }
397
398 fn describe_job(&self, source: &Source, world: &WorldMapping, data: Option<Data>) -> DescribeJob {
399 let handler = Arc::clone(&self.handler);
400 let source = source.clone();
401 let world = world.clone();
402 Box::new(move |respond| {
403 handler.describe(&source, &world, data, respond);
404 })
405 }
406
407 fn describe_image_job(&self, source: &Source) -> DescribeImageJob {
408 let handler = Arc::clone(&self.handler);
409 let source = source.clone();
410 Box::new(move |image| handler.describe_image(&source, image))
411 }
412
413 fn metadata_changed(&self, previous: &Source, source: &Source) -> bool {
414 self.handler.metadata_changed(previous, source)
415 }
416
417 fn attribution(&self, source: &Source) -> Option<String> {
418 self.handler.attribution(source)
419 }
420
421 fn summary(&self, source: &Source) -> SourceSummary {
422 self.handler.summary(source)
423 }
424
425 fn offline(&self, _source: &Source) -> OfflineResources {
426 OfflineResources::None
427 }
428
429 fn offline_tileset(&self, _source: &Source, _tilejson: &[u8]) -> Result<Tileset, String> {
430 Err(format!("a {} source has no TileJSON", self.style.info().name))
431 }
432
433 fn query_feature_extension(
434 &self,
435 _source: &Source,
436 _feature: &crate::tile::feature::Feature,
437 _extension: &str,
438 _field: &str,
439 _args: Option<&mln_style::feature::PropertyMap>,
440 ) -> Result<FeatureExtensionValue, Error> {
441 Ok(FeatureExtensionValue::default())
442 }
443}