bevy_map_scatter 0.5.0

Bevy plugin that integrates the `map_scatter` core crate for object scattering with field-graph evaluation and sampling
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#[cfg(feature = "ron")]
use std::collections::BTreeMap;
use std::result::Result;

use bevy::asset::io::Reader;
#[cfg(feature = "ron")]
use bevy::asset::io::{AsyncWriteExt, Writer};
#[cfg(feature = "ron")]
use bevy::asset::{saver::AssetSaver, saver::SavedAsset, AssetPath};
use bevy::asset::{AssetLoader, LoadContext, ReflectAsset};
use bevy::prelude::*;
use map_scatter::prelude::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Asset describing a complete scatter [`Plan`] for `map_scatter`.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Asset, Reflect, Clone, Debug)]
#[reflect(Asset)]
pub struct ScatterPlanAsset {
    /// Ordered list of layer definitions in the plan.
    pub layers: Vec<ScatterLayerDef>,
}

/// Layer definition within a [`ScatterPlanAsset`].
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Reflect)]
pub struct ScatterLayerDef {
    /// Unique identifier for this layer.
    pub id: String,
    /// Kinds evaluated in this layer.
    pub kinds: Vec<ScatterKindDef>,
    /// Sampling strategy used for candidate generation.
    pub sampling: SamplingDef,
    /// Optional overlay mask size in pixels (width, height).
    pub overlay_mask_size_px: Option<(u32, u32)>,
    /// Optional overlay brush radius in pixels.
    pub overlay_brush_radius_px: Option<i32>,
    /// Strategy for selecting a kind when multiple are valid.
    pub selection_strategy: SelectionStrategyDef,
}

/// Kind definition.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Reflect)]
pub struct ScatterKindDef {
    /// Unique identifier for this kind.
    pub id: String,
    /// Field graph specification for this kind.
    ///
    /// This remains serialized through serde/RON, but is skipped by Bevy reflection because the
    /// core `map_scatter` crate intentionally does not depend on Bevy.
    #[reflect(ignore)]
    pub spec: FieldGraphSpec,
}

/// Selection strategy for layers.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Debug, Reflect)]
pub enum SelectionStrategyDef {
    WeightedRandom,
    HighestProbability,
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Reflect)]
pub enum ParentDef {
    Count(
        /// Number of parent centers to generate.
        usize,
    ),
    Density(
        /// Parent density per unit area.
        f32,
    ),
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Reflect)]
pub enum SamplingDef {
    UniformRandom {
        /// Number of candidate points to generate.
        count: usize,
    },
    Halton {
        /// Number of candidate points to generate.
        count: usize,
        /// Bases for the 2D Halton sequence.
        bases: (u32, u32),
        /// Starting index in the Halton sequence.
        start_index: u32,
        /// Apply Cranley-Patterson rotation.
        rotate: bool,
    },
    FibonacciLattice {
        /// Number of candidate points to generate.
        count: usize,
        /// Apply Cranley-Patterson rotation.
        rotate: bool,
    },
    StratifiedMultiJitter {
        /// Number of candidate points to generate.
        count: usize,
        /// Apply Cranley-Patterson rotation.
        rotate: bool,
    },
    BestCandidate {
        /// Number of candidate points to generate.
        count: usize,
        /// Trials per point for best-candidate selection.
        k: usize,
    },
    PoissonDisk {
        /// Minimum distance between points in world units.
        radius: f32,
    },
    JitterGrid {
        /// Jitter amount in [0, 1].
        jitter: f32,
        /// Cell size for the base grid in world units.
        cell_size: f32,
    },
    HexJitterGrid {
        /// Jitter amount in [0, 1].
        jitter: f32,
        /// Base spacing along X in world units.
        cell_size: f32,
    },
    ClusteredThomas {
        /// Parent placement configuration.
        parents: ParentDef,
        /// Mean number of children per parent.
        mean_children: f32,
        /// Gaussian sigma for child offsets.
        sigma: f32,
        /// Clamp children inside the domain bounds.
        clamp_inside: bool,
    },
    ClusteredNeymanScott {
        /// Parent placement configuration.
        parents: ParentDef,
        /// Mean number of children per parent.
        mean_children: f32,
        /// Disk radius for child offsets.
        radius: f32,
        /// Clamp children inside the domain bounds.
        clamp_inside: bool,
    },
}

impl From<&ScatterKindDef> for Kind {
    fn from(value: &ScatterKindDef) -> Self {
        Kind::new(value.id.clone(), value.spec.clone())
    }
}

impl From<ScatterKindDef> for Kind {
    fn from(value: ScatterKindDef) -> Self {
        Kind::new(value.id, value.spec)
    }
}

impl From<SelectionStrategyDef> for SelectionStrategy {
    fn from(value: SelectionStrategyDef) -> Self {
        match value {
            SelectionStrategyDef::WeightedRandom => SelectionStrategy::WeightedRandom,
            SelectionStrategyDef::HighestProbability => SelectionStrategy::HighestProbability,
        }
    }
}

impl From<&ScatterLayerDef> for Layer {
    fn from(def: &ScatterLayerDef) -> Self {
        let kinds: Vec<Kind> = def.kinds.iter().map(|k| k.into()).collect();
        let sampling: Box<dyn PositionSampling> = sampling_runtime(&def.sampling);
        let mut layer = Layer::new(def.id.clone(), kinds, sampling);

        if let (Some(size), Some(radius)) = (
            def.overlay_mask_size_px.as_ref(),
            def.overlay_brush_radius_px,
        ) {
            layer = layer.with_overlay(*size, radius);
        }

        layer.with_selection_strategy(def.selection_strategy.into())
    }
}

impl From<&ScatterPlanAsset> for Plan {
    fn from(asset: &ScatterPlanAsset) -> Self {
        let layers: Vec<Layer> = asset.layers.iter().map(|l| l.into()).collect();
        Plan::new().with_layers(layers)
    }
}

impl From<ScatterPlanAsset> for Plan {
    fn from(asset: ScatterPlanAsset) -> Self {
        (&asset).into()
    }
}

/// Convert a `SamplingDef` into a boxed runtime sampler.
fn sampling_runtime(def: &SamplingDef) -> Box<dyn PositionSampling> {
    match def {
        SamplingDef::UniformRandom { count } => Box::new(UniformRandomSampling { count: *count }),
        SamplingDef::Halton {
            count,
            bases,
            start_index,
            rotate,
        } => Box::new(HaltonSampling {
            count: *count,
            bases: *bases,
            start_index: *start_index,
            rotate: *rotate,
        }),
        SamplingDef::FibonacciLattice { count, rotate } => Box::new(FibonacciLatticeSampling {
            count: *count,
            rotate: *rotate,
        }),
        SamplingDef::StratifiedMultiJitter { count, rotate } => {
            Box::new(StratifiedMultiJitterSampling {
                count: *count,
                rotate: *rotate,
            })
        }
        SamplingDef::BestCandidate { count, k } => Box::new(BestCandidateSampling {
            count: *count,
            k: *k,
        }),
        SamplingDef::PoissonDisk { radius } => Box::new(PoissonDiskSampling { radius: *radius }),
        SamplingDef::JitterGrid { jitter, cell_size } => {
            Box::new(JitterGridSampling::new(*jitter, *cell_size))
        }
        SamplingDef::HexJitterGrid { jitter, cell_size } => {
            Box::new(HexJitterGridSampling::new(*jitter, *cell_size))
        }
        SamplingDef::ClusteredThomas {
            parents,
            mean_children,
            sigma,
            clamp_inside,
        } => {
            let base = match parents {
                ParentDef::Count(n) => {
                    ClusteredSampling::thomas_with_count(*n, *mean_children, *sigma)
                }
                ParentDef::Density(d) => {
                    ClusteredSampling::thomas_with_density(*d, *mean_children, *sigma)
                }
            };
            Box::new(base.with_clamp_inside(*clamp_inside))
        }
        SamplingDef::ClusteredNeymanScott {
            parents,
            mean_children,
            radius,
            clamp_inside,
        } => {
            let base = match parents {
                ParentDef::Count(n) => {
                    ClusteredSampling::neyman_scott_with_count(*n, *mean_children, *radius)
                }
                ParentDef::Density(d) => {
                    ClusteredSampling::neyman_scott_with_density(*d, *mean_children, *radius)
                }
            };
            Box::new(base.with_clamp_inside(*clamp_inside))
        }
    }
}

/// Asset loader for [`ScatterPlanAsset`] using RON files with `.scatter` extension.
#[derive(TypePath)]
pub struct ScatterPlanAssetLoader;

impl AssetLoader for ScatterPlanAssetLoader {
    type Asset = ScatterPlanAsset;
    type Settings = ();
    type Error = anyhow::Error;

    fn extensions(&self) -> &[&str] {
        &["scatter"]
    }

    async fn load(
        &self,
        reader: &mut dyn Reader,
        _settings: &Self::Settings,
        _context: &mut LoadContext<'_>,
    ) -> Result<Self::Asset, Self::Error> {
        let mut bytes = Vec::new();
        reader.read_to_end(&mut bytes).await?;
        #[cfg(feature = "ron")]
        {
            let asset: ScatterPlanAsset =
                ron::de::from_bytes(&bytes).map_err(|e| anyhow::anyhow!(e))?;
            Ok(asset)
        }
        #[cfg(not(feature = "ron"))]
        {
            let _ = bytes;
            Err(anyhow::anyhow!(
                "bevy_map_scatter: enable the `ron` feature to load .scatter assets"
            ))
        }
    }
}

impl FromWorld for ScatterPlanAssetLoader {
    fn from_world(_: &mut World) -> Self {
        ScatterPlanAssetLoader
    }
}

/// Asset saver for [`ScatterPlanAsset`] RON files with `.scatter` extension.
#[cfg(feature = "ron")]
#[derive(Default, TypePath)]
pub struct ScatterPlanAssetSaver;

#[cfg(feature = "ron")]
impl AssetSaver for ScatterPlanAssetSaver {
    type Asset = ScatterPlanAsset;
    type Settings = ();
    type OutputLoader = ScatterPlanAssetLoader;
    type Error = anyhow::Error;

    async fn save(
        &self,
        writer: &mut Writer,
        asset: SavedAsset<'_, '_, Self::Asset>,
        _settings: &Self::Settings,
        _asset_path: AssetPath<'_>,
    ) -> Result<(), Self::Error> {
        let ron = to_scatter_plan_ron(asset.get())?;
        writer.write_all(ron.as_bytes()).await?;
        Ok(())
    }
}

#[cfg(feature = "ron")]
fn to_scatter_plan_ron(asset: &ScatterPlanAsset) -> Result<String, ron::Error> {
    let stable = SerializableScatterPlanAsset::from(asset);
    let pretty = ron::ser::PrettyConfig::new()
        .new_line("\n")
        .indentor("  ")
        .struct_names(false);
    let mut ron = ron::ser::to_string_pretty(&stable, pretty)?;
    ron.push('\n');
    Ok(ron)
}

#[cfg(feature = "ron")]
#[derive(Serialize)]
struct SerializableScatterPlanAsset<'a> {
    layers: Vec<SerializableScatterLayerDef<'a>>,
}

#[cfg(feature = "ron")]
impl<'a> From<&'a ScatterPlanAsset> for SerializableScatterPlanAsset<'a> {
    fn from(asset: &'a ScatterPlanAsset) -> Self {
        Self {
            layers: asset.layers.iter().map(Into::into).collect(),
        }
    }
}

#[cfg(feature = "ron")]
#[derive(Serialize)]
struct SerializableScatterLayerDef<'a> {
    id: &'a str,
    kinds: Vec<SerializableScatterKindDef<'a>>,
    sampling: &'a SamplingDef,
    overlay_mask_size_px: &'a Option<(u32, u32)>,
    overlay_brush_radius_px: &'a Option<i32>,
    selection_strategy: &'a SelectionStrategyDef,
}

#[cfg(feature = "ron")]
impl<'a> From<&'a ScatterLayerDef> for SerializableScatterLayerDef<'a> {
    fn from(layer: &'a ScatterLayerDef) -> Self {
        Self {
            id: &layer.id,
            kinds: layer.kinds.iter().map(Into::into).collect(),
            sampling: &layer.sampling,
            overlay_mask_size_px: &layer.overlay_mask_size_px,
            overlay_brush_radius_px: &layer.overlay_brush_radius_px,
            selection_strategy: &layer.selection_strategy,
        }
    }
}

#[cfg(feature = "ron")]
#[derive(Serialize)]
struct SerializableScatterKindDef<'a> {
    id: &'a str,
    spec: SerializableFieldGraphSpec<'a>,
}

#[cfg(feature = "ron")]
impl<'a> From<&'a ScatterKindDef> for SerializableScatterKindDef<'a> {
    fn from(kind: &'a ScatterKindDef) -> Self {
        Self {
            id: &kind.id,
            spec: SerializableFieldGraphSpec::from(&kind.spec),
        }
    }
}

#[cfg(feature = "ron")]
#[derive(Serialize)]
struct SerializableFieldGraphSpec<'a> {
    nodes: BTreeMap<&'a str, &'a NodeSpec>,
    semantics: BTreeMap<&'a str, &'a FieldSemantics>,
}

#[cfg(feature = "ron")]
impl<'a> From<&'a FieldGraphSpec> for SerializableFieldGraphSpec<'a> {
    fn from(spec: &'a FieldGraphSpec) -> Self {
        Self {
            nodes: spec
                .nodes
                .iter()
                .map(|(id, node)| (id.as_str(), node))
                .collect(),
            semantics: spec
                .semantics
                .iter()
                .map(|(id, semantics)| (id.as_str(), semantics))
                .collect(),
        }
    }
}

#[cfg(all(test, feature = "ron"))]
mod tests {
    use super::*;

    #[test]
    fn serializes_simple_scatter_plan_asset_as_readable_ron() {
        let asset = simple_plan_asset();

        let ron = to_scatter_plan_ron(&asset).expect("scatter plan should serialize");

        assert!(ron.contains("layers"));
        assert!(ron.contains("JitterGrid"));
        assert!(ron.contains("\"probability\""));
        assert!(ron.ends_with('\n'));
    }

    #[test]
    fn serialized_scatter_plan_asset_loads_through_ron_parser() {
        let asset = simple_plan_asset();
        let ron = to_scatter_plan_ron(&asset).expect("scatter plan should serialize");

        let parsed: ScatterPlanAsset =
            ron::de::from_str(&ron).expect("serialized plan should parse through RON");

        assert_eq!(parsed.layers.len(), 1);
        let layer = &parsed.layers[0];
        assert_eq!(layer.id, "dots");
        assert_eq!(layer.kinds.len(), 1);
        assert_eq!(layer.kinds[0].id, "dot");
        assert!(matches!(
            layer.sampling,
            SamplingDef::JitterGrid {
                jitter: 1.0,
                cell_size: 1.0
            }
        ));
        assert!(matches!(
            layer.kinds[0].spec.semantics.get("probability"),
            Some(FieldSemantics::Probability)
        ));
        assert!(matches!(
            layer.kinds[0].spec.nodes.get("probability"),
            Some(NodeSpec::Constant { .. })
        ));
    }

    #[test]
    fn scatter_plan_asset_saver_type_is_available_with_ron_feature() {
        let _saver = ScatterPlanAssetSaver;
    }

    fn simple_plan_asset() -> ScatterPlanAsset {
        let mut spec = FieldGraphSpec::default();
        spec.add_with_semantics(
            "probability",
            NodeSpec::constant(1.0),
            FieldSemantics::Probability,
        );

        ScatterPlanAsset {
            layers: vec![ScatterLayerDef {
                id: "dots".to_string(),
                kinds: vec![ScatterKindDef {
                    id: "dot".to_string(),
                    spec,
                }],
                sampling: SamplingDef::JitterGrid {
                    jitter: 1.0,
                    cell_size: 1.0,
                },
                overlay_mask_size_px: None,
                overlay_brush_radius_px: None,
                selection_strategy: SelectionStrategyDef::WeightedRandom,
            }],
        }
    }
}