rustial-renderer-bevy 0.0.1

Bevy Engine renderer for the rustial 2.5D map engine
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
//! # Whole-frame change detection for Bevy sync systems
//!
//! Provides [`FrameChangeDetection`], a lightweight per-frame fingerprint
//! resource that allows all Bevy `Update` sync systems to skip work when
//! the engine state has not materially changed since the previous frame.
//!
//! ## Motivation
//!
//! Even with per-system dirty tracking (fingerprints in model_sync,
//! quantised origins in vector_sync, diff-based tile/terrain sync, and
//! fog parameter caching), every Bevy sync system still pays the cost of
//! running its ECS queries, reading `MapStateResource`, and computing
//! per-system fingerprints on every frame.  For a typical steady-state
//! frame where the camera is stationary and no data has arrived, this
//! work produces no visible effect but still contributes to Bevy's
//! frame-time overhead.
//!
//! `FrameChangeDetection` moves the "has anything changed?" check to a
//! single early system that runs before the `Update` sync stage.  When
//! the whole-frame fingerprint is unchanged, individual sync systems
//! can return immediately without touching any queries or assets.
//!
//! ## Fingerprint composition
//!
//! The fingerprint is a rolling hash of the engine state aspects that
//! drive Bevy entity sync:
//!
//! - camera origin (quantised)
//! - camera pitch / yaw / distance (quantised)
//! - camera projection + mode
//! - visible tile count + first/last tile IDs
//! - terrain mesh count + first/last tile IDs + generations
//! - vector mesh count + first/last vertex/index counts
//! - model instance count
//! - placed symbol count
//! - visualization overlay identities and generations
//! - background colour
//! - hillshade parameters
//! - terrain enabled flag
//!
//! This is intentionally coarse: it is designed to detect "nothing at
//! all changed" rather than to replace per-system fine-grained caches.
//! The per-system caches remain authoritative for partial-change cases
//! (e.g. camera moved but tile set is unchanged).

use bevy::prelude::*;

use crate::plugin::MapStateResource;

/// Whole-frame change detection resource.
///
/// Updated once per frame in `PreUpdate` (after `update_map_state`).
/// Sync systems read [`changed()`](Self::changed) to decide whether
/// to proceed or short-circuit.
#[derive(Resource)]
pub struct FrameChangeDetection {
    /// Fingerprint from the previous frame (or sentinel on first frame).
    prev_fingerprint: u64,
    /// Whether the engine state changed this frame (set once in `PreUpdate`).
    frame_changed: bool,
}

impl Default for FrameChangeDetection {
    fn default() -> Self {
        // Start with a sentinel that guarantees the first frame is
        // always treated as changed.
        Self {
            prev_fingerprint: u64::MAX,
            frame_changed: true,
        }
    }
}

impl FrameChangeDetection {
    /// Whether the engine state has changed since the last
    /// [`update_frame_change_detection`] call.
    ///
    /// Returns `true` on the first frame or after any material engine
    /// state change.  Returns `false` on steady-state frames where the
    /// camera, tile set, terrain, vectors, models, and style parameters
    /// are all unchanged.
    pub fn changed(&self) -> bool {
        self.frame_changed
    }
}

/// Bevy system that recomputes the whole-frame fingerprint from
/// `MapStateResource` and updates [`FrameChangeDetection`].
///
/// Runs in `PreUpdate` after `update_map_state_timed`.  Computes the
/// fingerprint exactly once per frame; sync systems then read the
/// pre-computed [`changed()`](FrameChangeDetection::changed) flag
/// via [`frame_unchanged()`] without recomputing the hash.
pub fn update_frame_change_detection(
    state: Res<MapStateResource>,
    mut detection: ResMut<FrameChangeDetection>,
) {
    let fp = compute_frame_fingerprint(&state.0);
    detection.frame_changed = fp != detection.prev_fingerprint;
    detection.prev_fingerprint = fp;
}

/// Check if sync systems can skip work this frame.
///
/// Returns `true` when the whole-frame fingerprint is unchanged
/// (computed once in `PreUpdate`).
///
/// Individual sync systems should call this at the top and return
/// early when `true`.
#[inline]
pub fn frame_unchanged(
    detection: &FrameChangeDetection,
    _current_state: &rustial_engine::MapState,
) -> bool {
    !detection.frame_changed
}

fn compute_frame_fingerprint(state: &rustial_engine::MapState) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325; // FNV offset basis

    let cam = state.camera();
    let origin = state.scene_world_origin();

    // Camera origin (quantised to centimetres).
    hash_i64(&mut h, (origin.x * 100.0) as i64);
    hash_i64(&mut h, (origin.y * 100.0) as i64);
    hash_i64(&mut h, (origin.z * 100.0) as i64);

    // Camera orientation (quantised to milliradians).
    hash_i64(&mut h, (cam.pitch() * 1000.0) as i64);
    hash_i64(&mut h, (cam.yaw() * 1000.0) as i64);
    hash_i64(&mut h, (cam.distance() * 10.0) as i64);

    // Camera projection + mode.
    let proj_discriminant = match cam.projection() {
        rustial_engine::CameraProjection::WebMercator => 0u64,
        rustial_engine::CameraProjection::Equirectangular => 1,
        rustial_engine::CameraProjection::Globe => 2,
        rustial_engine::CameraProjection::VerticalPerspective { .. } => 3,
    };
    hash_u64(&mut h, proj_discriminant);
    hash_u64(&mut h, cam.mode() as u64);

    // Visible tiles.
    let tiles = state.visible_tiles();
    hash_u64(&mut h, tiles.len() as u64);
    if let Some(first) = tiles.first() {
        hash_u64(&mut h, first.target.zoom as u64);
        hash_u64(&mut h, first.target.x as u64);
        hash_u64(&mut h, first.target.y as u64);
    }
    if let Some(last) = tiles.last() {
        hash_u64(&mut h, last.target.zoom as u64);
        hash_u64(&mut h, last.target.x as u64);
        hash_u64(&mut h, last.target.y as u64);
    }

    // Terrain meshes.
    let terrain = state.terrain_meshes();
    hash_u64(&mut h, terrain.len() as u64);
    for mesh in terrain {
        hash_u64(&mut h, mesh.tile.zoom as u64);
        hash_u64(&mut h, mesh.tile.x as u64);
        hash_u64(&mut h, mesh.tile.y as u64);
        hash_u64(&mut h, mesh.generation);
    }

    // Vector meshes.
    let vectors = state.vector_meshes();
    hash_u64(&mut h, vectors.len() as u64);
    for vmesh in vectors {
        hash_u64(&mut h, vmesh.positions.len() as u64);
        hash_u64(&mut h, vmesh.indices.len() as u64);
    }

    // Model instances.
    hash_u64(&mut h, state.model_instances().len() as u64);

    // Symbols.
    hash_u64(&mut h, state.placed_symbols().len() as u64);

    // Visualization overlays.
    let frame = state.frame_output();
    hash_u64(&mut h, frame.visualization.len() as u64);
    for overlay in frame.visualization.iter() {
        match overlay {
            rustial_engine::VisualizationOverlay::GridScalar {
                layer_id,
                field,
                ramp,
                ..
            } => {
                hash_u64(&mut h, 10);
                hash_u64(&mut h, layer_id.as_u64());
                hash_u64(&mut h, field.generation);
                hash_u64(&mut h, field.value_generation);
                hash_u64(&mut h, ramp.stops.len() as u64);
            }
            rustial_engine::VisualizationOverlay::GridExtrusion {
                layer_id,
                field,
                params,
                ramp,
                ..
            } => {
                hash_u64(&mut h, 11);
                hash_u64(&mut h, layer_id.as_u64());
                hash_u64(&mut h, field.generation);
                hash_u64(&mut h, field.value_generation);
                hash_u64(&mut h, params.height_scale.to_bits());
                hash_u64(&mut h, params.base_meters.to_bits());
                hash_u64(&mut h, ramp.stops.len() as u64);
            }
            rustial_engine::VisualizationOverlay::Columns {
                layer_id,
                columns,
                ramp,
            } => {
                hash_u64(&mut h, 12);
                hash_u64(&mut h, layer_id.as_u64());
                hash_u64(&mut h, columns.generation);
                hash_u64(&mut h, columns.columns.len() as u64);
                hash_u64(&mut h, column_set_fingerprint(columns));
                hash_u64(&mut h, ramp.stops.len() as u64);
            }
            rustial_engine::VisualizationOverlay::Points {
                layer_id,
                points,
                ramp,
            } => {
                hash_u64(&mut h, 13);
                hash_u64(&mut h, layer_id.as_u64());
                hash_u64(&mut h, points.generation);
                hash_u64(&mut h, points.points.len() as u64);
                hash_u64(&mut h, point_set_fingerprint(points));
                hash_u64(&mut h, ramp.stops.len() as u64);
            }
        }
    }

    // Image overlays (count + data pointer identity for dynamic sources).
    let overlays = &frame.image_overlays;
    hash_u64(&mut h, overlays.len() as u64);
    for overlay in overlays.iter() {
        hash_u64(&mut h, overlay.layer_id.as_u64());
        hash_u64(&mut h, overlay.width as u64);
        hash_u64(&mut h, overlay.height as u64);
        // Use Arc data pointer as a proxy for content identity.
        hash_u64(&mut h, std::sync::Arc::as_ptr(&overlay.data) as u64);
    }

    // Background colour.
    if let Some(bg) = state.background_color() {
        hash_u64(&mut h, bg[0].to_bits() as u64);
        hash_u64(&mut h, bg[1].to_bits() as u64);
    }

    // Hillshade.
    if let Some(hs) = state.hillshade() {
        hash_u64(&mut h, hs.exaggeration.to_bits() as u64);
        hash_u64(&mut h, hs.opacity.to_bits() as u64);
    }

    // Terrain enabled.
    hash_u64(&mut h, state.terrain().enabled() as u64);

    h
}

fn point_set_fingerprint(points: &rustial_engine::PointInstanceSet) -> u64 {
    let mut h = points.points.len() as u64;
    for point in &points.points {
        hash_u64(&mut h, point.position.lat.to_bits());
        hash_u64(&mut h, point.position.lon.to_bits());
        hash_u64(&mut h, point.position.alt.to_bits());
        hash_u64(&mut h, point.radius.to_bits());
        hash_u64(&mut h, point.intensity.to_bits() as u64);
        hash_u64(&mut h, point.pick_id);
        hash_u64(
            &mut h,
            match point.altitude_mode {
                rustial_engine::AltitudeMode::ClampToGround => 0,
                rustial_engine::AltitudeMode::RelativeToGround => 1,
                rustial_engine::AltitudeMode::Absolute => 2,
            },
        );
        if let Some(color) = point.color {
            hash_u64(&mut h, color[0].to_bits() as u64);
            hash_u64(&mut h, color[1].to_bits() as u64);
            hash_u64(&mut h, color[2].to_bits() as u64);
            hash_u64(&mut h, color[3].to_bits() as u64);
        }
    }
    h
}

#[inline(always)]
fn hash_u64(state: &mut u64, value: u64) {
    *state ^= value;
    *state = state.wrapping_mul(0x0100_0000_01b3);
}

#[inline(always)]
fn hash_i64(state: &mut u64, value: i64) {
    hash_u64(state, value as u64);
}

fn column_set_fingerprint(columns: &rustial_engine::ColumnInstanceSet) -> u64 {
    let mut h = columns.columns.len() as u64;
    for column in &columns.columns {
        hash_u64(&mut h, column.position.lat.to_bits());
        hash_u64(&mut h, column.position.lon.to_bits());
        hash_u64(&mut h, column.position.alt.to_bits());
        hash_u64(&mut h, column.height.to_bits());
        hash_u64(&mut h, column.base.to_bits());
        hash_u64(&mut h, column.width.to_bits());
        hash_u64(&mut h, column.pick_id);
        hash_u64(
            &mut h,
            match column.altitude_mode {
                rustial_engine::AltitudeMode::ClampToGround => 0,
                rustial_engine::AltitudeMode::RelativeToGround => 1,
                rustial_engine::AltitudeMode::Absolute => 2,
            },
        );
        if let Some(color) = column.color {
            hash_u64(&mut h, color[0].to_bits() as u64);
            hash_u64(&mut h, color[1].to_bits() as u64);
            hash_u64(&mut h, color[2].to_bits() as u64);
            hash_u64(&mut h, color[3].to_bits() as u64);
        }
    }
    h
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustial_engine::{GeoCoord, MapState};

    #[test]
    fn identical_state_produces_identical_fingerprint() {
        let state = MapState::new();
        let fp1 = compute_frame_fingerprint(&state);
        let fp2 = compute_frame_fingerprint(&state);
        assert_eq!(fp1, fp2);
    }

    #[test]
    fn moved_camera_produces_different_fingerprint() {
        let mut state = MapState::new();
        state.set_viewport(800, 600);
        state.update();
        let fp1 = compute_frame_fingerprint(&state);

        state.set_camera_distance(5_000_000.0);
        state.update();
        let fp2 = compute_frame_fingerprint(&state);

        assert_ne!(fp1, fp2);
    }

    #[test]
    fn frame_unchanged_returns_true_for_steady_state() {
        let state = MapState::new();
        let mut detection = FrameChangeDetection::default();
        // First frame: always changed.
        assert!(detection.changed());

        // Simulate PreUpdate computing the fingerprint.
        let fp = compute_frame_fingerprint(&state);
        detection.frame_changed = fp != detection.prev_fingerprint;
        detection.prev_fingerprint = fp;

        // First real frame: changed (sentinel -> real fingerprint).
        assert!(detection.changed());

        // Second frame with same state: unchanged.
        let fp2 = compute_frame_fingerprint(&state);
        detection.frame_changed = fp2 != detection.prev_fingerprint;
        detection.prev_fingerprint = fp2;

        assert!(!detection.changed());
        assert!(frame_unchanged(&detection, &state));
    }

    #[test]
    fn visualization_value_update_changes_fingerprint() {
        let mut state = MapState::new();
        state.set_grid_extrusion(
            "surface",
            rustial_engine::GeoGrid::new(GeoCoord::from_lat_lon(0.0, 0.0), 1, 1, 10.0, 10.0),
            rustial_engine::ScalarField2D::from_data(1, 1, vec![1.0]),
            rustial_engine::ColorRamp::new(vec![
                rustial_engine::ColorStop {
                    value: 0.0,
                    color: [0.0, 0.0, 1.0, 0.5],
                },
                rustial_engine::ColorStop {
                    value: 1.0,
                    color: [1.0, 0.0, 0.0, 0.8],
                },
            ]),
            rustial_engine::ExtrusionParams {
                height_scale: 2.0,
                base_meters: 1.0,
            },
        );
        state.update();
        let fp1 = compute_frame_fingerprint(&state);

        let mut field = rustial_engine::ScalarField2D::from_data(1, 1, vec![1.0]);
        field.update_values(vec![3.0]);
        state.set_grid_extrusion(
            "surface",
            rustial_engine::GeoGrid::new(GeoCoord::from_lat_lon(0.0, 0.0), 1, 1, 10.0, 10.0),
            field,
            rustial_engine::ColorRamp::new(vec![
                rustial_engine::ColorStop {
                    value: 0.0,
                    color: [0.0, 0.0, 1.0, 0.5],
                },
                rustial_engine::ColorStop {
                    value: 1.0,
                    color: [1.0, 0.0, 0.0, 0.8],
                },
            ]),
            rustial_engine::ExtrusionParams {
                height_scale: 2.0,
                base_meters: 1.0,
            },
        );
        state.update();
        let fp2 = compute_frame_fingerprint(&state);

        assert_ne!(fp1, fp2);
    }

    #[test]
    fn column_overlay_value_update_changes_fingerprint() {
        let mut state = MapState::new();
        state.set_instanced_columns(
            "columns",
            rustial_engine::ColumnInstanceSet::new(vec![rustial_engine::ColumnInstance::new(
                GeoCoord::from_lat_lon(0.0, 0.0),
                10.0,
                5.0,
            )
            .with_pick_id(7)]),
            rustial_engine::ColorRamp::new(vec![
                rustial_engine::ColorStop {
                    value: 0.0,
                    color: [0.0, 0.0, 1.0, 0.5],
                },
                rustial_engine::ColorStop {
                    value: 1.0,
                    color: [1.0, 0.0, 0.0, 0.8],
                },
            ]),
        );
        state.update();
        let fp1 = compute_frame_fingerprint(&state);

        state.set_instanced_columns(
            "columns",
            rustial_engine::ColumnInstanceSet::new(vec![rustial_engine::ColumnInstance::new(
                GeoCoord::from_lat_lon(0.0, 0.0),
                25.0,
                5.0,
            )
            .with_pick_id(7)]),
            rustial_engine::ColorRamp::new(vec![
                rustial_engine::ColorStop {
                    value: 0.0,
                    color: [0.0, 0.0, 1.0, 0.5],
                },
                rustial_engine::ColorStop {
                    value: 1.0,
                    color: [1.0, 0.0, 0.0, 0.8],
                },
            ]),
        );
        state.update();
        let fp2 = compute_frame_fingerprint(&state);

        assert_ne!(fp1, fp2);
    }
}