rustial-renderer-bevy 1.0.0

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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
// ---------------------------------------------------------------------------
//! # Bevy plugin that integrates the rustial engine
//!
//! [`RustialBevyPlugin`] is the single entry point for the Bevy
//! renderer.  Adding it to a Bevy `App` registers all systems,
//! resources, and (optionally) the built-in HTTP raster tile source.
//!
//! ## Resources registered
//!
//! | Resource | Purpose |
//! |----------|---------|
//! | [`MapStateResource`] | Wraps the engine [`MapState`]; read by every sync system. |
//! | [`RustialBevyConfig`] | Initial center / zoom / viewport; consumed once by `setup_from_config`. |
//! | `TileFetchConfig` | (http-tiles) built-in HTTP tile-source configuration. |
//! | `ModelInstanceCache` | in-memory model instance cache. |
//!
//! ## System schedule
//!
//! ```text
//! Startup
//!   setup_from_config              build MapState from config, spawn camera
//!   [http-tiles]
//!     init_http_client             create reqwest + tokio runtime bridge
//!     setup_engine_http_tile_layer install engine-owned TileLayer
//!
//! PreUpdate
//!   sync_viewport                  window size -> engine viewport
//!   handle_default_input           mouse/keyboard -> InputEvent
//!   update_map_state               tick engine (after input)
//!   sync_camera                    engine camera -> Bevy Transform (after update)
//!   [http-tiles]
//!     sync_builtin_tile_layer_visibility   no-op compatibility hook
//!
//! Update
//!   sync_tiles                     tile quad entities
//!   sync_terrain                   terrain mesh entities
//!   sync_vectors                   vector geometry entities
//!   sync_models                    3D model entities
//!   sync_geo_entities              user MapEntity + GeoTransform
//!
//! PostUpdate
//!   upload_textures                decoded imagery -> tile materials
//!   sync_horizon_fade              pitch-based alpha fade on distant tiles
//! ```
//!
//! ## Engine-owned raster path
//!
//! With the `http-tiles` feature enabled, the Bevy renderer no longer computes
//! desired tiles or maintains a renderer-side tile image cache. Instead it:
//!
//! 1. creates a Bevy-backed [`rustial_engine::HttpClient`] adapter,
//! 2. installs a built-in engine [`rustial_engine::TileLayer`], and
//! 3. lets [`MapState::update`](rustial_engine::MapState::update) drive tile
//!    selection, fallback, overzoom, and polling exactly as the engine path
//!    intends.
//!
//! This keeps Bevy behavior aligned with the engine/WGPU tile pipeline.
//!
//! ## Zoom-to-distance formula
//!
//! `setup_from_config` converts the user's integer zoom level to a
//! camera `distance` (meters) using the standard slippy-map identity:
//!
//! ```text
//! tile_mpp  = C / (256 * 2^zoom)       -- meters per pixel at the equator
//! distance  = tile_mpp * vh / (2 * tan(fov_y / 2))
//! ```
//!
//! where `C = 2 * PI * 6 378 137` (WGS-84 equatorial circumference)
//! and `vh` is the viewport height in physical pixels.  The same
//! formula is used by [`MapState::fly_to`](rustial_engine::MapState::fly_to).
// ---------------------------------------------------------------------------

use bevy::prelude::*;
use bevy::asset::embedded_asset;
use bevy::pbr::MaterialPlugin;
use rustial_engine::{GeoCoord, MapState, MAX_ZOOM};

use crate::components::MapCamera;
use crate::components::DeferredAssetDrop;
use crate::grid_scalar_material::GridScalarMaterial;
use crate::hillshade_material::HillshadeMaterial;
use crate::painter::{
    update_painter_plan, update_terrain_interaction_buffers, PainterPlanResource, PainterSet,
    TerrainInteractionBuffersResource,
};
use crate::systems::camera_sync::sync_camera;
use crate::systems::column_sync::{sync_columns, CachedColumnAssets, ColumnSyncState};
use crate::systems::debug_hud;
use crate::systems::distance_fog::sync_horizon_fade;
use crate::systems::distance_fog::FogDirtyState;
use crate::systems::frame_change_detection::{
    update_frame_change_detection, FrameChangeDetection,
};
use crate::systems::geo_entity_sync::sync_geo_entities;
use crate::systems::grid_extrusion_sync::{sync_grid_extrusions, GridExtrusionSyncState};
use crate::systems::grid_scalar_sync::{sync_grid_scalars, GridScalarSyncState};
use crate::systems::map_input;
use crate::systems::model_sync::{sync_models, CachedModelAssets, ModelSyncState};
use crate::systems::placeholder_sync::sync_placeholders;
use crate::systems::point_cloud_sync::{sync_point_clouds, CachedPointCloudAssets, PointCloudSyncState};
use crate::systems::hillshade_sync::sync_hillshade;
use crate::systems::performance::{
    begin_post_update_stage_timing, begin_update_stage_timing, end_post_update_stage_timing,
    end_update_stage_timing, report_performance_trace, update_map_state_timed,
    PerformanceTraceState,
};
use crate::systems::terrain_sync;
use crate::systems::terrain_sync::{
    sync_terrain, SharedTerrainGridMeshes, UploadedTerrainHeightTextures,
};
use crate::systems::texture_upload::{upload_hillshade_textures, upload_textures, UploadedHillshadeTextures, UploadedTileTextures};
use crate::systems::tile_sync::{sync_tiles, CachedTileAssets};
use crate::systems::vector_sync::{sync_vectors, VectorSyncState};
use crate::systems::image_overlay_sync::{sync_image_overlays, ImageOverlaySyncState};
use crate::tile_fog_material::TileFogMaterial;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Earth's equatorial circumference in metres (2 * PI * WGS-84 semi-major axis).
///
/// Used by [`setup_from_config`] to convert a slippy-map zoom level to
/// a camera distance.  Matches the constant in
/// [`MapState::fly_to`](rustial_engine::MapState::fly_to).
const WGS84_CIRCUMFERENCE: f64 = 2.0 * std::f64::consts::PI * 6_378_137.0;

/// Standard raster tile edge length in pixels (universal slippy-map
/// convention).
const TILE_PX: f64 = 256.0;

/// Default viewport dimensions used when neither
/// [`RustialBevyConfig::viewport`] nor the Bevy window provide a
/// valid size (e.g. headless tests).
const FALLBACK_VIEWPORT: (u32, u32) = (1280, 720);

/// Default terrain cache budget used when no raster-source policy is available.
const DEFAULT_TERRAIN_CACHE_SIZE: usize = 768;

#[cfg(feature = "http-tiles")]
fn terrain_cache_size(
    tile_fetch_config: Option<&crate::systems::tile_fetch::TileFetchConfig>,
) -> usize {
    tile_fetch_config.map_or(DEFAULT_TERRAIN_CACHE_SIZE, |config| config.max_cached.max(1))
}

#[cfg(not(feature = "http-tiles"))]
const fn terrain_cache_size() -> usize {
    DEFAULT_TERRAIN_CACHE_SIZE
}

// ---------------------------------------------------------------------------
// Plugin
// ---------------------------------------------------------------------------

/// Bevy plugin for the rustial 2.5D map.
///
/// Adds all systems needed to render a map: viewport sync, default
/// input handling (pan / rotate / zoom), tile fetching (with
/// `http-tiles` feature), camera sync, and ECS entity management.
///
/// See the [module-level documentation](self) for the full system
/// schedule and resource table.
///
/// # Minimal usage
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use rustial_renderer_bevy::{RustialBevyPlugin, RustialBevyConfig};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(RustialBevyConfig {
///         center: (51.1, 17.0),
///         zoom: 10,
///         ..default()
///     })
///     .add_plugins(RustialBevyPlugin)
///     .run();
/// ```
pub struct RustialBevyPlugin;

impl Plugin for RustialBevyPlugin {
    fn build(&self, app: &mut App) {
        // Ensure config resource exists (user may or may not insert one).
        if !app.world().contains_resource::<RustialBevyConfig>() {
            app.insert_resource(RustialBevyConfig::default());
        }

        // Register the custom tile fog material plugin when the render
        // pipeline is available.  Headless test apps (no DefaultPlugins /
        // RenderPlugin) skip this -- they only exercise ECS logic.
        if app.is_plugin_added::<bevy::render::RenderPlugin>() {
            app.add_plugins(MaterialPlugin::<TileFogMaterial>::default());
            app.add_plugins(MaterialPlugin::<HillshadeMaterial>::default());
            app.add_plugins(MaterialPlugin::<GridScalarMaterial>::default());
            embedded_asset!(app, "shaders/tile_fog.wgsl");
            embedded_asset!(app, "shaders/hillshade_overlay.wgsl");
            embedded_asset!(app, "shaders/grid_scalar_overlay.wgsl");
        } else {
            // Headless: just register the asset store so systems can
            // query Assets<TileFogMaterial> without panicking.
            app.init_resource::<Assets<TileFogMaterial>>();
            app.init_resource::<Assets<HillshadeMaterial>>();
            app.init_resource::<Assets<GridScalarMaterial>>();
        }

        // Ensure input infrastructure exists.  DefaultPlugins registers
        // these via InputPlugin / bevy_winit; headless tests may not have
        // them.  Bevy's `init_resource` and `add_message` are idempotent.
        use bevy::input::mouse::{MouseMotion, MouseWheel};
        if !app.world().contains_resource::<ButtonInput<MouseButton>>() {
            app.init_resource::<ButtonInput<MouseButton>>();
        }
        if !app.world().contains_resource::<ButtonInput<KeyCode>>() {
            app.init_resource::<ButtonInput<KeyCode>>();
        }
        app.add_message::<CursorMoved>();
        app.add_message::<MouseMotion>();
        app.add_message::<MouseWheel>();

        app.insert_resource(MapStateResource(MapState::new()))
             .init_resource::<PainterPlanResource>()
             .init_resource::<TerrainInteractionBuffersResource>()
             .init_resource::<PerformanceTraceState>()
             .init_resource::<map_input::PrevCursorPos>()
             .init_resource::<map_input::MapInputEnabled>()
             .init_resource::<DeferredAssetDrop>()
             .init_resource::<UploadedTileTextures>()
             .init_resource::<UploadedHillshadeTextures>()
             .init_resource::<CachedTileAssets>()
             .init_resource::<SharedTerrainGridMeshes>()
             .init_resource::<UploadedTerrainHeightTextures>()
             .init_resource::<terrain_sync::LastSceneOrigin>()
             .init_resource::<CachedModelAssets>()
             .init_resource::<CachedColumnAssets>()
             .init_resource::<CachedPointCloudAssets>()
             .init_resource::<ColumnSyncState>()
             .init_resource::<PointCloudSyncState>()
             .init_resource::<ModelSyncState>()
             .init_resource::<FogDirtyState>()
             .init_resource::<VectorSyncState>()
             .init_resource::<ImageOverlaySyncState>()
             .init_resource::<GridExtrusionSyncState>()
             .init_resource::<GridScalarSyncState>()
             .init_resource::<debug_hud::DebugHudState>()
             .init_resource::<debug_hud::DebugFileTxtState>()
             .init_resource::<debug_hud::DebugFileCsvState>()
             .init_resource::<debug_hud::DebugFileJpgState>()
             .init_resource::<FrameChangeDetection>()
             .configure_sets(Update, (PainterSet::SkyAtmosphere, PainterSet::TerrainData, PainterSet::OpaqueScene, PainterSet::HillshadeOverlay).chain())
             .configure_sets(PostUpdate, (PainterSet::SkyAtmosphere, PainterSet::TerrainData, PainterSet::OpaqueScene, PainterSet::HillshadeOverlay).chain())
             .add_systems(Startup, (setup_from_config, terrain_sync::init_placeholder_texture))
             .add_systems(PreUpdate, map_input::sync_viewport)
             .add_systems(PreUpdate, map_input::handle_default_input.after(map_input::sync_viewport))
             .add_systems(
                 PreUpdate,
                 update_map_state_timed.after(map_input::handle_default_input),
             )
             .add_systems(PreUpdate, update_painter_plan.after(update_map_state_timed))
             .add_systems(PreUpdate, update_frame_change_detection.after(update_map_state_timed))
             .add_systems(PreUpdate, update_terrain_interaction_buffers.after(update_map_state_timed))
             .add_systems(PreUpdate, sync_camera.after(update_map_state_timed))
             .add_systems(Update, begin_update_stage_timing.before(PainterSet::SkyAtmosphere))
             .add_systems(Update, sync_background_clear_color.in_set(PainterSet::SkyAtmosphere))
              .add_systems(Update, sync_tiles.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_placeholders.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_terrain.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_vectors.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_grid_extrusions.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_grid_scalars.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_columns.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_point_clouds.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_models.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_image_overlays.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_geo_entities.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, debug_hud::update_debug_hud.in_set(PainterSet::OpaqueScene))
              .add_systems(Update, sync_hillshade.in_set(PainterSet::HillshadeOverlay))
              .add_systems(Update, end_update_stage_timing.after(PainterSet::HillshadeOverlay))
             .add_systems(PostUpdate, begin_post_update_stage_timing.before(PainterSet::SkyAtmosphere))
             .add_systems(PostUpdate, sync_horizon_fade.in_set(PainterSet::SkyAtmosphere))
              .add_systems(PostUpdate, upload_textures.in_set(PainterSet::OpaqueScene))
              .add_systems(PostUpdate, upload_hillshade_textures.in_set(PainterSet::HillshadeOverlay))
              .add_systems(PostUpdate, advance_deferred_drop.after(upload_hillshade_textures))
              .add_systems(PostUpdate, end_post_update_stage_timing.after(advance_deferred_drop))
              .add_systems(PostUpdate, report_performance_trace.after(end_post_update_stage_timing));

        // -- http-tiles feature: engine-owned HTTP tile layer ------------
        #[cfg(feature = "http-tiles")]
        {
            use crate::systems::tile_fetch;

            if !app
                .world()
                .contains_resource::<tile_fetch::TileFetchConfig>()
            {
                app.insert_resource(tile_fetch::TileFetchConfig::default());
            }
            app.add_systems(Startup, tile_fetch::init_http_client)
                .add_systems(Startup, tile_fetch::setup_engine_http_tile_layer.after(tile_fetch::init_http_client))
                .add_systems(
                    PreUpdate,
                    tile_fetch::sync_builtin_tile_layer_visibility.after(update_map_state_timed),
                );
        }
    }
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration resource for the initial map view.
///
/// Insert this **before** adding [`RustialBevyPlugin`] (or in the same
/// `App` builder) to control the starting centre, zoom, and viewport.
/// If not inserted, the plugin uses [`Default`] values (equator,
/// zoom 2, auto-detect window size).
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use rustial_renderer_bevy::{RustialBevyPlugin, RustialBevyConfig};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(RustialBevyConfig {
///         center: (51.1, 17.0),
///         zoom: 10,
///         ..default()
///     })
///     .add_plugins(RustialBevyPlugin)
///     .run();
/// ```
#[derive(Resource)]
pub struct RustialBevyConfig {
    /// Initial centre as `(latitude, longitude)` in WGS-84 degrees.
    pub center: (f64, f64),
    /// Initial slippy-map zoom level (0--22, clamped).
    pub zoom: u8,
    /// Initial viewport size `(width, height)` in **logical** pixels.
    ///
    /// `(0, 0)` (the default) means "read from the Bevy primary window
    /// at startup".  If no window is available either (e.g. headless
    /// tests), the plugin falls back to 1280 x 720.
    pub viewport: (u32, u32),
    /// Optional terrain configuration.
    ///
    /// When `Some`, terrain rendering is enabled at startup with the
    /// given configuration.  The pitch and max-pitch are automatically
    /// adjusted for 3D terrain viewing when not explicitly overridden.
    pub terrain: Option<rustial_engine::TerrainConfig>,
    /// Optional initial camera pitch in **degrees**.
    ///
    /// When `Some`, overrides the default zero-degree pitch. Useful for tilting
    /// the camera to see 3D terrain relief.
    pub pitch: Option<f64>,
    /// Optional maximum camera pitch in **degrees**.
    ///
    /// When `Some`, overrides the default max-pitch constraint.
    pub max_pitch: Option<f64>,
    /// Enable a debug HUD overlay in the top-left corner.
    ///
    /// When `true`, displays camera pitch, yaw, distance, zoom level,
    /// and tile/terrain mesh counts updated every frame.
    pub debug: bool,
    /// Enable periodic CPU-side stage timing logs for the Bevy path.
    pub performance_trace: bool,
    /// Export the debug HUD values to a single text file once per second.
    ///
    /// When enabled, the renderer appends the same snapshot shown by the
    /// on-screen debug HUD to `rustial_debug_values.txt` in the current
    /// working directory.  Each snapshot is separated by a blank line and
    /// prefixed with a monotonically increasing sample index.
    pub debug_file_txt: bool,
    /// Export the debug HUD values to a machine-comparable CSV file once per second.
    ///
    /// When enabled, the renderer appends a structured snapshot row to
    /// `rustial_debug_values.csv` in the current working directory. Each row
    /// corresponds to the same once-per-second sample cadence as the text and
    /// JPG debug exports so automated tooling can compare coverage, cache, and
    /// request-pipeline behavior across runs.
    pub debug_file_csv: bool,
    /// Export an application-window screenshot every second as JPG files.
    ///
    /// Screenshots are written into `docs/debug/` using monotonically
    /// increasing sample numbers.
    pub debug_file_jpg: bool,
}

impl Default for RustialBevyConfig {
    fn default() -> Self {
        Self {
            center: (0.0, 0.0),
            zoom: 2,
            viewport: (0, 0),
            terrain: None,
            pitch: None,
            max_pitch: None,
            debug: false,
            performance_trace: false,
            debug_file_txt: false,
            debug_file_csv: false,
            debug_file_jpg: false,
        }
    }
}

impl Clone for RustialBevyConfig {
    fn clone(&self) -> Self {
        Self {
            center: self.center,
            zoom: self.zoom,
            viewport: self.viewport,
            terrain: None,
            pitch: self.pitch,
            max_pitch: self.max_pitch,
            debug: self.debug,
            performance_trace: self.performance_trace,
            debug_file_txt: self.debug_file_txt,
            debug_file_csv: self.debug_file_csv,
            debug_file_jpg: self.debug_file_jpg,
        }
    }
}

impl std::fmt::Debug for RustialBevyConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RustialBevyConfig")
            .field("center", &self.center)
            .field("zoom", &self.zoom)
            .field("viewport", &self.viewport)
            .field("terrain", &self.terrain.is_some())
            .field("pitch", &self.pitch)
            .field("max_pitch", &self.max_pitch)
            .field("debug", &self.debug)
            .field("performance_trace", &self.performance_trace)
            .field("debug_file_txt", &self.debug_file_txt)
            .field("debug_file_csv", &self.debug_file_csv)
            .field("debug_file_jpg", &self.debug_file_jpg)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// MapStateResource
// ---------------------------------------------------------------------------

/// Bevy resource wrapping the engine's [`MapState`].
///
/// All sync systems read this resource each frame to obtain camera
/// position, visible tiles, terrain meshes, vector data, and model
/// instances.  The `update_map_state` system ticks it once per frame
/// in `PreUpdate`.

///
/// The inner field is `pub` so that host-application systems can read
/// or mutate the engine state directly (e.g. calling
/// [`MapState::fly_to`](rustial_engine::MapState::fly_to) or
/// injecting layers).  For the typical "display a map" workflow the
/// plugin manages the resource automatically and users never need to
/// touch it.
#[derive(Resource)]
pub struct MapStateResource(pub MapState);

// ---------------------------------------------------------------------------
// Startup system
// ---------------------------------------------------------------------------

/// Build a [`MapState`] from [`RustialBevyConfig`] and spawn the Bevy
/// 3D camera entity.
///
/// ## Viewport resolution
///
/// 1. If `config.viewport` is non-zero, use it directly.
/// 2. Otherwise read the Bevy primary window's **logical** size.
/// 3. Fall back to [`FALLBACK_VIEWPORT`] (headless / pre-window).
///
/// Logical pixels are used because the engine's `meters_per_pixel`
/// and the pan deltas from `CursorMoved` are both in logical pixels.
/// Keeping the same unit system makes the cursor track the map
/// exactly regardless of DPI scale factor.
///
/// ## Zoom-to-distance
///
/// See the [module-level docs](self) for the formula.  The camera's
/// default `fov_y` (PI/4) is used for perspective projection.
fn setup_from_config(
    mut commands: Commands,
    mut state: ResMut<MapStateResource>,
    mut config: ResMut<RustialBevyConfig>,
    mut perf: ResMut<PerformanceTraceState>,
    windows: Query<&Window>,
    #[cfg(feature = "http-tiles")]
    tile_fetch_config: Option<Res<crate::systems::tile_fetch::TileFetchConfig>>,
) {
    // -- Resolve viewport-------------------------------------------------
    let (vw, vh) = if config.viewport.0 > 0 && config.viewport.1 > 0 {
        config.viewport
    } else if let Ok(window) = windows.single() {
        let w = window.resolution.width() as u32;
        let h = window.resolution.height() as u32;
        if w > 0 && h > 0 {
            (w, h)
        } else {
            FALLBACK_VIEWPORT
        }
    } else {
        FALLBACK_VIEWPORT
    };

    // -- Apply config to the existing MapState ----------------------------
    // Only touch camera fields derived from the config.  Preserve
    // everything else (terrain, layers, constraints, animator) so that
    // user Startup systems that run before or after this one are not
    // clobbered.
    let fov_y = state.0.camera().fov_y();
    let z = config.zoom.min(MAX_ZOOM);
    let tile_mpp = WGS84_CIRCUMFERENCE / (TILE_PX * (1u64 << z) as f64);
    let distance = tile_mpp * vh.max(1) as f64 / (2.0 * (fov_y / 2.0).tan());

    state.0.set_camera_target(
        GeoCoord::from_lat_lon(config.center.0, config.center.1),
    );
    state.0.set_camera_distance(distance);
    state.0.set_viewport(vw, vh);

    // -- Apply terrain config if provided --------------------------------
    if let Some(terrain_config) = config.terrain.take() {
        let cache_size = {
            #[cfg(feature = "http-tiles")]
            {
                terrain_cache_size(tile_fetch_config.as_deref())
            }
            #[cfg(not(feature = "http-tiles"))]
            {
                terrain_cache_size()
            }
        };
        state.0.set_terrain(rustial_engine::TerrainManager::new(terrain_config, cache_size));

        // Default pitch for 3D terrain viewing (user can override).
        if config.pitch.is_none() {
            state.0.set_camera_pitch(60_f64.to_radians());
        }
        if config.max_pitch.is_none() {
            state.0.set_max_pitch(85_f64.to_radians());
        }
    }

    // -- Apply explicit camera overrides ---------------------------------
    if let Some(pitch_deg) = config.pitch {
        state.0.set_camera_pitch(pitch_deg.to_radians());
    }
    if let Some(max_pitch_deg) = config.max_pitch {
        state.0.set_max_pitch(max_pitch_deg.to_radians());
    }

    perf.set_enabled(config.performance_trace);

    log::info!(
        "setup_from_config: center=({:.4}, {:.4}), zoom={}, viewport={}x{}, distance={:.0}m, pitch={:.1}\u{00B0}, perf_trace={}",
        config.center.0,
        config.center.1,
        z,
        vw,
        vh,
        distance,
        state.0.camera().pitch().to_degrees(),
        config.performance_trace,
    );

    let clear = state.0.background_color().unwrap_or([1.0, 1.0, 1.0, 1.0]);

    // -- Spawn the Bevy 3D camera ----------------------------------------
    commands.spawn((
        Camera3d::default(),
        Camera {
            clear_color: ClearColorConfig::Custom(Color::srgba(clear[0], clear[1], clear[2], clear[3])),
            ..default()
        },
        Transform::default(),
        MapCamera,
    ));

    // -- Optionally spawn the debug HUD ----------------------------------
    if config.debug {
        debug_hud::spawn_debug_hud(commands);
    }
}

// ---------------------------------------------------------------------------
// Per-frame engine tick
// ---------------------------------------------------------------------------

/// Keep the Bevy camera clear colour aligned with the top-most visible
/// engine [`BackgroundLayer`](rustial_engine::BackgroundLayer).
fn sync_background_clear_color(
    state: Res<MapStateResource>,
    mut cameras: Query<&mut Camera, With<MapCamera>>,
) {
    let clear = state.0.computed_fog().clear_color;
    for mut camera in &mut cameras {
        camera.clear_color = ClearColorConfig::Custom(Color::srgba(clear[0], clear[1], clear[2], clear[3]));
    }
}

 /// Advance the deferred asset drop buffer by one frame.
///
/// Handles stashed during entity despawn are kept alive for one extra
/// frame so the GPU render pipeline can finish using the underlying
/// buffers before they are freed.
fn advance_deferred_drop(mut deferred: ResMut<DeferredAssetDrop>) {
    deferred.advance_frame();
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::{ModelEntity, TerrainEntity, TileEntity, VectorEntity};
    use crate::components::HillshadeEntity;
    use bevy::camera::Projection;
    use bevy::mesh::VertexAttributeValues;
    use glam::DVec3;
    use rustial_engine::{
        CameraMode, CameraProjection, Feature, FeatureCollection, Geometry, ModelLayer, Point,
        VectorLayer, VectorStyle,
    };
    use rustial_engine::rustial_math::GeoCoord;

    /// Build a minimal Bevy `App` with the plugin for headless testing.
    ///
    /// Inserts bare-minimum asset stores (`Mesh`, `StandardMaterial`,
    /// `Image`) and the `TaskPoolPlugin` so that
    /// systems requiring async task pools or frame tracking do not panic.
    /// Does **not** add the full `DefaultPlugins` -- there is no GPU,
    /// no window, and no render graph.  Systems that touch Bevy
    /// rendering internals beyond asset stores will fail; these tests
    /// only exercise the ECS + engine logic.
    fn test_app() -> App {
        let mut app = App::new();
        app.add_plugins(bevy::app::TaskPoolPlugin::default());
        app.add_plugins(bevy::time::TimePlugin::default());
        app.init_resource::<Assets<Mesh>>();
        app.init_resource::<Assets<StandardMaterial>>();
        app.init_resource::<Assets<Image>>();
        app.add_plugins(RustialBevyPlugin);
        app
    }

    #[test]
    fn plugin_inserts_map_state_and_spawns_camera() {
        let mut app = test_app();
        app.update();

        assert!(app.world().contains_resource::<MapStateResource>());
        let camera_count = {
            let world = app.world_mut();
            world.query::<&MapCamera>().iter(world).count()
        };
        assert_eq!(camera_count, 1);
    }

    #[test]
    fn plugin_sync_tiles_spawns_tile_entities() {
        let mut app = test_app();
        app.update();
        app.update();

        let tile_count = {
            let world = app.world_mut();
            world.query::<&TileEntity>().iter(world).count()
        };
        assert!(
            tile_count > 0,
            "expected at least one tile entity to be spawned"
        );
    }

    #[test]
    fn plugin_sync_terrain_with_enabled_terrain() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            use rustial_engine::{FlatElevationSource, TerrainConfig, TerrainManager};
            let config = TerrainConfig {
                enabled: true,
                mesh_resolution: 4,
                source: Box::new(FlatElevationSource::new(4, 4)),
                ..TerrainConfig::default()
            };
            state.0.set_terrain(TerrainManager::new(config, 100));
        }

        // Three frames: startup, request, data arrives.
        app.update();
        app.update();
        app.update();

        let terrain_count = {
            let world = app.world_mut();
            world.query::<&TerrainEntity>().iter(world).count()
        };
        assert!(terrain_count > 0, "expected at least one terrain entity");

        let hillshade_count = {
            let world = app.world_mut();
            world.query::<&HillshadeEntity>().iter(world).count()
        };
        assert_eq!(hillshade_count, 0, "no hillshade layer means no overlay entities");
    }

    #[test]
    fn plugin_sync_vectors_with_data() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.push_layer(Box::new(VectorLayer::new(
                "test_vector",
                FeatureCollection {
                    features: vec![Feature {
                        geometry: Geometry::Point(Point {
                            coord: GeoCoord::from_lat_lon(48.8566, 2.3522),
                        }),
                        properties: Default::default(),
                    }],
                },
                VectorStyle::default(),
            )));
        }

        app.update();
        app.update();

        let vec_count = {
            let world = app.world_mut();
            world.query::<&VectorEntity>().iter(world).count()
        };
        assert!(vec_count > 0, "expected at least one vector entity");
    }

    #[test]
    fn plugin_sync_models_with_data() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            use rustial_engine::{ModelInstance, ModelMesh};
            use rustial_engine::rustial_math::GeoCoord;
            let mesh = ModelMesh {
                positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
                normals: vec![[0.0, 0.0, 1.0]; 3],
                uvs: vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]],
                indices: vec![0, 1, 2],
            };
            let instance = ModelInstance::new(GeoCoord::from_lat_lon(48.8566, 2.3522), mesh);
            let mut layer = ModelLayer::new("test_models");
            layer.add(instance);
            state.0.push_layer(Box::new(layer));
        }

        app.update();
        app.update();

        let model_count = {
            let world = app.world_mut();
            world.query::<&ModelEntity>().iter(world).count()
        };
        assert!(model_count > 0, "expected at least one model entity");
    }

    #[test]
    fn disabled_terrain_produces_no_terrain_entities() {
        let mut app = test_app();
        app.update();
        app.update();

        let terrain_count = {
            let world = app.world_mut();
            world.query::<&TerrainEntity>().iter(world).count()
        };
        assert_eq!(terrain_count, 0);
    }

    #[test]
    fn config_sets_center_and_zoom() {
        let mut app = App::new();
        app.add_plugins(bevy::app::TaskPoolPlugin::default());
        app.add_plugins(bevy::time::TimePlugin::default());
        app.init_resource::<Assets<Mesh>>();
        app.init_resource::<Assets<StandardMaterial>>();
        app.init_resource::<Assets<Image>>();
        app.insert_resource(RustialBevyConfig {
            center: (51.1, 17.0),
            zoom: 10,
            viewport: (1280, 720),
            ..default()
        });
        app.add_plugins(RustialBevyPlugin);
        app.update();

        let state = app.world().resource::<MapStateResource>();
        assert!((state.0.camera().target().lat - 51.1).abs() < 0.01);
        assert!((state.0.camera().target().lon - 17.0).abs() < 0.01);
    }

    #[test]
    fn plugin_sync_tiles_rebuilds_for_equirectangular_projection() {
        let mut app = test_app();
        app.update();
        app.update();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_camera_projection(CameraProjection::Equirectangular);
        }

        app.update();
        app.update();

        let visible_count = app.world().resource::<MapStateResource>().0.visible_tiles().len();
        assert!(visible_count > 0, "expected visible tiles after projection switch");

        let world = app.world_mut();
        let mut query = world.query::<&TileEntity>();
        let tiles: Vec<_> = query.iter(world).collect();
        assert!(!tiles.is_empty(), "expected tile entities after projection switch");
        assert!(tiles.iter().all(|tile| tile.projection == CameraProjection::Equirectangular));
    }

    #[test]
    fn plugin_sync_camera_uses_orthographic_projection_component() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_camera_mode(CameraMode::Orthographic);
            state.0.set_camera_projection(CameraProjection::WebMercator);
        }

        app.update();
        app.update();

        let world = app.world_mut();
        let mut query = world.query::<(&MapCamera, &Projection)>();
        let (_, projection) = query.single(world).expect("map camera should exist");
        assert!(matches!(projection, Projection::Orthographic(_)));
    }

    #[test]
    fn plugin_sync_camera_uses_perspective_projection_for_equirectangular() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_camera_mode(CameraMode::Perspective);
            state.0.set_camera_projection(CameraProjection::Equirectangular);
        }

        app.update();
        app.update();

        {
            let world = app.world_mut();
            let mut query = world.query::<(&MapCamera, &Projection)>();
            let (_, projection) = query.single(world).expect("map camera should exist");
            assert!(matches!(projection, Projection::Perspective(_)));
        }

        let state = app.world().resource::<MapStateResource>();
        assert_eq!(state.0.camera().projection(), CameraProjection::Equirectangular);
    }

    #[test]
    fn plugin_sync_camera_uses_orthographic_projection_for_equirectangular() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_camera_mode(CameraMode::Orthographic);
            state.0.set_camera_projection(CameraProjection::Equirectangular);
        }

        app.update();
        app.update();

        {
            let world = app.world_mut();
            let mut query = world.query::<(&MapCamera, &Projection)>();
            let (_, projection) = query.single(world).expect("map camera should exist");
            assert!(matches!(projection, Projection::Orthographic(_)));
        }

        let state = app.world().resource::<MapStateResource>();
        assert_eq!(state.0.camera().projection(), CameraProjection::Equirectangular);
    }

    #[test]
    fn plugin_sync_tiles_places_projected_equirectangular_geometry() {
        let mut app = test_app();
        app.update();
        app.update();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_camera_projection(CameraProjection::Equirectangular);
        }

        app.update();
        app.update();

        let visible_count = app.world().resource::<MapStateResource>().0.visible_tiles().len();
        assert!(visible_count > 0, "expected visible tiles after switching to equirectangular projection");

        let tile_id = {
            let state = app.world().resource::<MapStateResource>();
            state
                .0
                .visible_tiles()
                .first()
                .map(|tile| tile.target)
                .expect("expected at least one visible tile")
        };

        let expected_sw = {
            let state = app.world().resource::<MapStateResource>();
            let camera_origin = state.0.scene_world_origin();
            DVec3::from_array(
                CameraProjection::Equirectangular.project_tile_corner(&tile_id, 0.0, 1.0),
            ) - camera_origin
        };

        let world = app.world_mut();
        let mut query = world.query::<(&TileEntity, &Mesh3d, &Transform)>();
        let (tile, mesh3d, transform) = query
            .iter(world)
            .find(|(tile, _, _)| tile.tile_id == tile_id)
            .expect("expected projected tile entity");

        assert_eq!(tile.projection, CameraProjection::Equirectangular);

        let meshes = world.resource::<Assets<Mesh>>();
        let mesh = meshes.get(&mesh3d.0).expect("tile mesh should exist");
        let positions = match mesh.attribute(Mesh::ATTRIBUTE_POSITION) {
            Some(VertexAttributeValues::Float32x3(values)) => values,
            other => panic!("unexpected tile position attribute: {other:?}"),
        };

        let actual_sw = [
            positions[0][0] + transform.translation.x,
            positions[0][1] + transform.translation.y,
            positions[0][2] + transform.translation.z,
        ];
        assert!((actual_sw[0] - expected_sw.x as f32).abs() < 1e-3);
        assert!((actual_sw[1] - expected_sw.y as f32).abs() < 1e-3);
        assert!((actual_sw[2] - expected_sw.z as f32).abs() < 1e-3);
    }

    #[test]
    fn plugin_sync_terrain_repositions_entities_when_scene_origin_changes() {
        let mut app = test_app();

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            use rustial_engine::{FlatElevationSource, TerrainConfig, TerrainManager};
            state.0.set_terrain(TerrainManager::new(
                TerrainConfig {
                    enabled: true,
                    mesh_resolution: 2,
                    source: Box::new(FlatElevationSource::new(2, 2)),
                    ..TerrainConfig::default()
                },
                16,
            ));
            state.0.set_camera_projection(CameraProjection::Equirectangular);
            state.0.set_camera_target(GeoCoord::from_lat_lon(10.0, 20.0));
            state.0.update_camera(1.0 / 60.0);
        }

        app.update();
        app.update();
        app.update();

        let terrain_mesh_count = app.world().resource::<MapStateResource>().0.terrain_meshes().len();
        assert!(terrain_mesh_count > 0, "expected terrain meshes after initial sync");

        let (tile_id, spawn_origin) = {
            let world = app.world_mut();
            let mut query = world.query::<&TerrainEntity>();
            query
                .iter(world)
                .map(|terrain| (terrain.tile_id, terrain.spawn_origin))
                .next()
                .expect("expected terrain entity after initial sync")
        };

        {
            let mut state = app.world_mut().resource_mut::<MapStateResource>();
            state.0.set_camera_target(GeoCoord::from_lat_lon(10.5, 20.5));
            state.0.update_camera(1.0 / 60.0);
        }

        app.update();

        let current_origin = app.world().resource::<MapStateResource>().0.scene_world_origin();
        let expected = spawn_origin - current_origin;
        let world = app.world_mut();
        let mut query = world.query::<(&TerrainEntity, &Transform, &MeshMaterial3d<TileFogMaterial>)>();
        let (terrain, transform, material_handle) = query
            .iter(world)
            .find(|(terrain, _, _)| terrain.tile_id == tile_id)
            .expect("expected terrain entity");

        assert_eq!(terrain.spawn_origin, spawn_origin);

        if terrain.gpu_displaced {
            assert!(transform.translation.length() < 1e-6);

            let materials = world.resource::<Assets<TileFogMaterial>>();
            let material = materials
                .get(&material_handle.0)
                .expect("terrain material should exist");
            assert!((material.terrain.scene_origin.x - current_origin.x as f32).abs() < 1e-3);
            assert!((material.terrain.scene_origin.y - current_origin.y as f32).abs() < 1e-3);
            assert!((material.terrain.scene_origin.z - current_origin.z as f32).abs() < 1e-3);
        } else {
            assert!((transform.translation.x - expected.x as f32).abs() < 1e-3);
            assert!((transform.translation.y - expected.y as f32).abs() < 1e-3);
            assert!((transform.translation.z - expected.z as f32).abs() < 1e-3);
        }
    }

    #[cfg(feature = "http-tiles")]
    #[test]
    fn terrain_cache_size_matches_tile_fetch_budget() {
        let config = crate::systems::tile_fetch::TileFetchConfig {
            max_cached: 1024,
            ..Default::default()
        };

        assert_eq!(terrain_cache_size(Some(&config)), 1024);
    }

    #[cfg(not(feature = "http-tiles"))]
    #[test]
    fn terrain_cache_size_uses_default_without_http_tiles() {
        assert_eq!(terrain_cache_size(), DEFAULT_TERRAIN_CACHE_SIZE);
    }
}