eldiron-shared 0.9.1

Shared code and common types for the Eldiron applications.
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
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
use crate::prelude::*;
use rusterix::Surface;
pub use rusterix::{Value, VertexBlendPreset, map::*};
use scenevm::GeoId;
use theframework::prelude::*;

/// Identifies which texture is currently being edited by editor tools.
/// This abstraction allows the same draw/fill/pick tools to work on
/// any paintable texture source (tiles, avatar frames, future types).
/// Each variant also determines how colors are resolved for painting.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum PixelEditingContext {
    /// No active editing target.
    None,
    /// Editing a tile texture: (tile_id, frame_index).
    Tile(Uuid, usize),
    /// Editing an avatar animation frame: (avatar_id, anim_id, perspective_index, frame_index).
    AvatarFrame(Uuid, Uuid, usize, usize),
}

impl Default for PixelEditingContext {
    fn default() -> Self {
        Self::None
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum AvatarAnchorEditSlot {
    None,
    Main,
    Off,
}

impl Default for AvatarAnchorEditSlot {
    fn default() -> Self {
        Self::None
    }
}

impl PixelEditingContext {
    /// Returns the [r, g, b, a] color to paint with for this context.
    /// For tiles: uses the palette color with opacity applied.
    /// For avatar frames: uses the selected body marker color.
    pub fn get_draw_color(
        &self,
        palette: &ThePalette,
        opacity: f32,
        body_marker_color: Option<[u8; 4]>,
    ) -> Option<[u8; 4]> {
        match self {
            PixelEditingContext::None => None,
            PixelEditingContext::Tile(..) => {
                if let Some(color) = palette.get_current_color() {
                    let mut arr = color.to_u8_array();
                    arr[3] = (arr[3] as f32 * opacity) as u8;
                    Some(arr)
                } else {
                    None
                }
            }
            PixelEditingContext::AvatarFrame(..) => body_marker_color,
        }
    }

    /// Returns the number of animation frames for this context.
    pub fn get_frame_count(&self, project: &Project) -> usize {
        match self {
            PixelEditingContext::None => 0,
            PixelEditingContext::Tile(tile_id, _) => {
                project.tiles.get(tile_id).map_or(0, |t| t.textures.len())
            }
            PixelEditingContext::AvatarFrame(avatar_id, anim_id, persp_index, _) => project
                .avatars
                .get(avatar_id)
                .and_then(|a| a.animations.iter().find(|anim| anim.id == *anim_id))
                .and_then(|anim| anim.perspectives.get(*persp_index))
                .map_or(0, |p| p.frames.len()),
        }
    }

    /// Returns a copy of this context with the frame index replaced.
    pub fn with_frame(&self, frame_index: usize) -> Self {
        match *self {
            PixelEditingContext::None => PixelEditingContext::None,
            PixelEditingContext::Tile(tile_id, _) => {
                PixelEditingContext::Tile(tile_id, frame_index)
            }
            PixelEditingContext::AvatarFrame(avatar_id, anim_id, persp_index, _) => {
                PixelEditingContext::AvatarFrame(avatar_id, anim_id, persp_index, frame_index)
            }
        }
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum GizmoMode {
    XZ,
    XY,
    YZ,
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum EditorViewMode {
    D2,
    Orbit,
    Iso,
    FirstP,
}

impl EditorViewMode {
    pub fn to_index(&self) -> i32 {
        match self {
            EditorViewMode::D2 => 0,
            EditorViewMode::Orbit => 1,
            EditorViewMode::Iso => 2,
            EditorViewMode::FirstP => 3,
        }
    }
    pub fn from_index(idx: i32) -> Self {
        match idx {
            1 => EditorViewMode::Orbit,
            2 => EditorViewMode::Iso,
            3 => EditorViewMode::FirstP,
            _ => EditorViewMode::D2,
        }
    }

    pub fn is_3d(&self) -> bool {
        match self {
            EditorViewMode::D2 => false,
            _ => true,
        }
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum ContentContext {
    Unknown,
    CharacterInstance(Uuid),
    ItemInstance(Uuid),
    Sector(Uuid),
    CharacterTemplate(Uuid),
    ItemTemplate(Uuid),
    Shader(Uuid),
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum ProjectContext {
    Unknown,
    Region(Uuid),
    RegionSettings(Uuid),
    RegionCharacterInstance(Uuid, Uuid),
    RegionItemInstance(Uuid, Uuid),
    Character(Uuid),
    CharacterVisualCode(Uuid),
    CharacterCode(Uuid),
    CharacterData(Uuid),
    CharacterPreviewRigging(Uuid),
    Item(Uuid),
    ItemVisualCode(Uuid),
    ItemCode(Uuid),
    ItemData(Uuid),
    Tilemap(Uuid),
    Screen(Uuid),
    ScreenWidget(Uuid, Uuid),
    Asset(Uuid),
    Avatar(Uuid),
    AvatarAnimation(Uuid, Uuid, usize),
    ProjectSettings,
    GameRules,
    GameLocales,
    GameAudioFx,
    DebugLog,
    Console,
}

impl ProjectContext {
    pub fn id(self) -> Option<Uuid> {
        match self {
            ProjectContext::Unknown
            | ProjectContext::ProjectSettings
            | ProjectContext::GameRules
            | ProjectContext::GameLocales
            | ProjectContext::GameAudioFx
            | ProjectContext::DebugLog
            | ProjectContext::Console => None,
            ProjectContext::Region(id)
            | ProjectContext::RegionSettings(id)
            | ProjectContext::RegionCharacterInstance(id, _)
            | ProjectContext::RegionItemInstance(id, _)
            | ProjectContext::Character(id)
            | ProjectContext::CharacterVisualCode(id)
            | ProjectContext::CharacterCode(id)
            | ProjectContext::CharacterData(id)
            | ProjectContext::CharacterPreviewRigging(id)
            | ProjectContext::Item(id)
            | ProjectContext::ItemVisualCode(id)
            | ProjectContext::ItemCode(id)
            | ProjectContext::ItemData(id)
            | ProjectContext::Tilemap(id)
            | ProjectContext::Screen(id)
            | ProjectContext::ScreenWidget(id, _)
            | ProjectContext::Asset(id)
            | ProjectContext::Avatar(id)
            | ProjectContext::AvatarAnimation(id, _, _) => Some(id),
        }
    }

    pub fn is_region(&self) -> bool {
        match self {
            ProjectContext::Region(_)
            | ProjectContext::RegionSettings(_)
            | ProjectContext::RegionCharacterInstance(_, _)
            | ProjectContext::RegionItemInstance(_, _) => true,
            _ => false,
        }
    }

    pub fn get_region_character_instance_id(&self) -> Option<Uuid> {
        match self {
            ProjectContext::RegionCharacterInstance(_, instance_id) => Some(*instance_id),
            _ => None,
        }
    }

    pub fn get_region_item_instance_id(&self) -> Option<Uuid> {
        match self {
            ProjectContext::RegionItemInstance(_, instance_id) => Some(*instance_id),
            _ => None,
        }
    }

    pub fn is_character(&self) -> bool {
        match self {
            ProjectContext::Character(_)
            | ProjectContext::CharacterVisualCode(_)
            | ProjectContext::CharacterCode(_)
            | ProjectContext::CharacterData(_)
            | ProjectContext::CharacterPreviewRigging(_) => true,
            _ => false,
        }
    }

    pub fn is_item(&self) -> bool {
        match self {
            ProjectContext::Item(_)
            | ProjectContext::ItemVisualCode(_)
            | ProjectContext::ItemCode(_)
            | ProjectContext::ItemData(_) => true,
            _ => false,
        }
    }

    pub fn is_tilemap(&self) -> bool {
        match self {
            ProjectContext::Tilemap(_) => true,
            _ => false,
        }
    }

    pub fn is_screen(&self) -> bool {
        match self {
            ProjectContext::Screen(_) | ProjectContext::ScreenWidget(_, _) => true,
            _ => false,
        }
    }

    pub fn get_screen_widget_id(&self) -> Option<Uuid> {
        match self {
            ProjectContext::ScreenWidget(_, widget_id) => Some(*widget_id),
            _ => None,
        }
    }

    pub fn is_asset(&self) -> bool {
        match self {
            ProjectContext::Asset(_) => true,
            _ => false,
        }
    }

    pub fn is_project_settings(&self) -> bool {
        match self {
            ProjectContext::ProjectSettings => true,
            _ => false,
        }
    }

    pub fn is_game_rules(&self) -> bool {
        match self {
            ProjectContext::GameRules => true,
            _ => false,
        }
    }

    pub fn is_game_locales(&self) -> bool {
        match self {
            ProjectContext::GameLocales => true,
            _ => false,
        }
    }

    pub fn is_game_audio_fx(&self) -> bool {
        match self {
            ProjectContext::GameAudioFx => true,
            _ => false,
        }
    }

    pub fn has_custom_map(&self) -> bool {
        match self {
            ProjectContext::Screen(_) => true,
            _ => false,
        }
    }
}

#[derive(PartialEq, Clone, Copy, Debug)]
pub enum MapContext {
    Region,
    Screen,
    Character,
    Item,
}

/// This gives context to the server of the editing state for live highlighting.
pub struct ServerContext {
    // Tree Ids
    pub tree_regions_id: Uuid,
    pub tree_characters_id: Uuid,
    pub tree_items_id: Uuid,
    pub tree_tilemaps_id: Uuid,
    pub tree_screens_id: Uuid,
    pub tree_avatars_id: Uuid,
    pub tree_assets_id: Uuid,
    pub tree_assets_fonts_id: Uuid,
    pub tree_assets_audio_id: Uuid,
    pub tree_palette_id: Uuid,
    pub tree_settings_id: Uuid,

    /// The currently selected region in the editor.
    pub curr_region: Uuid,

    /// The current region content.
    pub curr_region_content: ContentContext,

    /// The currently selected character in the editor.
    pub curr_character: ContentContext,

    /// The currently selected item in the editor.
    pub curr_item: ContentContext,

    /// The current content context.
    pub cc: ContentContext,

    /// The current project context.
    pub pc: ProjectContext,

    /// The currently selected codegrid in the code editor.
    pub curr_grid_id: Option<Uuid>,

    /// The currently selected screen.
    pub curr_screen: Uuid,

    /// The logged interactions of the characters.
    pub interactions: FxHashMap<Uuid, Vec<Interaction>>,

    /// The currently selected tile
    pub curr_tile_id: Option<Uuid>,

    /// The current frame/texture index being edited in tile editor
    pub curr_tile_frame_index: usize,

    /// The palette opacity for drawing tools
    pub palette_opacity: f32,

    /// The currently selected model
    pub curr_model_id: Option<Uuid>,

    /// The currently selected material
    pub curr_material_id: Option<Uuid>,

    /// The screen editor drawing mode.
    pub screen_editor_mode_foreground: bool,

    /// Hover geometry info
    pub hover: (Option<u32>, Option<u32>, Option<u32>),

    /// The current grid hover position
    pub hover_cursor: Option<Vec2<f32>>,

    /// The current 3d hover position
    pub hover_cursor_3d: Option<Vec3<f32>>,

    /// The current grid hover height
    pub hover_height: Option<f32>,

    /// Current Tool Type
    pub curr_map_tool_type: MapToolType,

    /// Current Map Context
    curr_map_context: MapContext,

    /// A click on map content originated from the map
    pub content_click_from_map: bool,

    /// Dont show rect based geometry on map
    pub no_rect_geo_on_map: bool,

    /// Show wall profile in linedef mode.
    pub profile_view: Option<u32>,

    /// The current editing surface
    pub editing_surface: Option<Surface>,

    /// The currently selected action
    pub curr_action_id: Option<Uuid>,

    /// Automatially apply actions
    pub auto_action: bool,

    /// Pending entity position changes: (from, to)
    pub moved_entities: FxHashMap<Uuid, (Vec3<f32>, Vec3<f32>)>,

    /// Pending item position changes: (from, to)
    pub moved_items: FxHashMap<Uuid, (Vec3<f32>, Vec3<f32>)>,

    /// Pending character orientation changes: (from, to)
    pub rotated_entities: FxHashMap<Uuid, (Vec2<f32>, Vec2<f32>)>,

    /// Selected wall row, set by the linedef Hud
    pub selected_wall_row: Option<i32>,

    /// View mode of the editor
    pub editor_view_mode: EditorViewMode,

    /// World mode is active
    pub world_mode: bool,

    /// Game server is running
    pub game_mode: bool,

    /// Map clipboard
    pub clipboard: Map,

    /// Map clipboard which is currently being pasted
    pub paste_clipboard: Option<Map>,

    /// Background Progress Text
    pub background_progress: Option<String>,

    /// Character Region Override
    pub character_region_override: bool,

    /// Item Region Override
    pub item_region_override: bool,

    /// Animation counter for tile previews
    pub animation_counter: usize,

    /// The current 3D hover hit
    pub geo_hit: Option<GeoId>,

    /// The current geometry hover hit position
    pub geo_hit_pos: Vec3<f32>,

    /// Temporary storage for the editing positon
    pub editing_pos_buffer: Option<Vec3<f32>>,
    /// Per-map, per-3D-view camera anchor (editing position).
    pub editing_view_pos_by_map: FxHashMap<(Uuid, i32), Vec3<f32>>,
    /// Per-map, per-3D-view look target.
    pub editing_view_look_by_map: FxHashMap<(Uuid, i32), Vec3<f32>>,
    /// Per-map 2D camera state: (offset, grid_size).
    pub editing_view_2d_by_map: FxHashMap<Uuid, (Vec2<f32>, f32)>,
    /// Per-map Iso camera scale.
    pub editing_view_iso_scale_by_map: FxHashMap<Uuid, f32>,

    /// The index of the selected icon in the hud
    pub selected_hud_icon_index: i32,

    ///Switch for showing 3D editing geometry
    pub show_editing_geometry: bool,

    /// Position of the 2D editing slice.
    pub editing_slice: f32,
    /// Height/thickness of the 2D editing slice.
    pub editing_slice_height: f32,

    /// The current plane for 3D movement
    pub gizmo_mode: GizmoMode,

    // For the Rect tool, identify the current sector and tile for preview
    pub rect_sector_id_3d: Option<u32>,
    pub rect_tile_id_3d: (i32, i32),
    pub rect_terrain_id: Option<(i32, i32)>,
    pub rect_blend_preset: VertexBlendPreset,

    /// Game input mode
    pub game_input_mode: bool,

    /// Help mode state
    pub help_mode: bool,

    /// The current editing context for texture editor tools.
    pub editing_ctx: PixelEditingContext,

    /// The selected body marker color for avatar painting.
    pub body_marker_color: Option<[u8; 4]>,
    /// Active avatar anchor edit slot for pixel editor clicks.
    pub avatar_anchor_slot: AvatarAnchorEditSlot,
}

impl Default for ServerContext {
    fn default() -> Self {
        Self::new()
    }
}

impl ServerContext {
    pub fn new() -> Self {
        Self {
            curr_region: Uuid::nil(),

            tree_regions_id: Uuid::new_v4(),
            tree_characters_id: Uuid::new_v4(),
            tree_items_id: Uuid::new_v4(),
            tree_tilemaps_id: Uuid::new_v4(),
            tree_screens_id: Uuid::new_v4(),
            tree_avatars_id: Uuid::new_v4(),
            tree_assets_id: Uuid::new_v4(),
            tree_assets_fonts_id: Uuid::new_v4(),
            tree_assets_audio_id: Uuid::new_v4(),
            tree_palette_id: Uuid::new_v4(),
            tree_settings_id: Uuid::new_v4(),

            curr_region_content: ContentContext::Unknown,
            curr_character: ContentContext::Unknown,
            curr_item: ContentContext::Unknown,
            cc: ContentContext::Unknown,

            pc: ProjectContext::Unknown,

            curr_grid_id: None,

            curr_screen: Uuid::nil(),

            interactions: FxHashMap::default(),

            curr_tile_id: None,
            curr_tile_frame_index: 0,

            palette_opacity: 1.0,

            curr_model_id: None,
            curr_material_id: None,

            screen_editor_mode_foreground: false,

            hover: (None, None, None),
            hover_cursor: None,
            hover_cursor_3d: None,
            hover_height: None,

            curr_map_tool_type: MapToolType::Linedef,
            curr_map_context: MapContext::Region,

            content_click_from_map: false,
            no_rect_geo_on_map: true,
            profile_view: None,

            editing_surface: None,
            curr_action_id: None,
            auto_action: true,

            moved_entities: FxHashMap::default(),
            moved_items: FxHashMap::default(),
            rotated_entities: FxHashMap::default(),

            selected_wall_row: Some(0),

            editor_view_mode: EditorViewMode::D2,

            world_mode: false,
            game_mode: false,

            clipboard: Map::default(),
            paste_clipboard: None,

            background_progress: None,

            character_region_override: true,
            item_region_override: true,

            animation_counter: 0,

            geo_hit: None,
            geo_hit_pos: Vec3::zero(),

            editing_pos_buffer: None,
            editing_view_pos_by_map: FxHashMap::default(),
            editing_view_look_by_map: FxHashMap::default(),
            editing_view_2d_by_map: FxHashMap::default(),
            editing_view_iso_scale_by_map: FxHashMap::default(),

            selected_hud_icon_index: 0,
            show_editing_geometry: true,

            gizmo_mode: GizmoMode::XZ,

            editing_slice: 0.0,
            editing_slice_height: 2.0,
            rect_sector_id_3d: None,
            rect_tile_id_3d: (0, 0),
            rect_terrain_id: None,
            rect_blend_preset: VertexBlendPreset::Solid,

            game_input_mode: false,
            help_mode: false,

            editing_ctx: PixelEditingContext::None,
            body_marker_color: None,
            avatar_anchor_slot: AvatarAnchorEditSlot::None,
        }
    }

    /// Checks if the PolyView has focus.
    pub fn polyview_has_focus(&self, ctx: &TheContext) -> bool {
        if let Some(focus) = &ctx.ui.focus {
            if focus.name == "PolyView" {
                return true;
            }
        }
        false
    }

    /// Returns the current map context
    pub fn get_map_context(&self) -> MapContext {
        if self.pc.is_screen() {
            return MapContext::Screen;
        }

        MapContext::Region

        /*
        if (self.curr_map_context == MapContext::Character && self.character_region_override)
            || (self.curr_map_context == MapContext::Item && self.item_region_override)
            || (self.curr_map_context == MapContext::Shader)
        {
            MapContext::Region
        } else {
            self.curr_map_context
        }*/
    }

    pub fn set_map_context(&mut self, map_context: MapContext) {
        self.curr_map_context = map_context;
    }

    #[inline]
    fn view_key(map_id: Uuid, mode: EditorViewMode) -> (Uuid, i32) {
        (map_id, mode.to_index())
    }

    pub fn store_edit_view_for_map(
        &mut self,
        map_id: Uuid,
        mode: EditorViewMode,
        pos: Vec3<f32>,
        look: Vec3<f32>,
    ) {
        if mode == EditorViewMode::D2 {
            return;
        }
        let key = Self::view_key(map_id, mode);
        self.editing_view_pos_by_map.insert(key, pos);
        self.editing_view_look_by_map.insert(key, look);
    }

    pub fn load_edit_view_for_map(
        &self,
        map_id: Uuid,
        mode: EditorViewMode,
    ) -> Option<(Vec3<f32>, Vec3<f32>)> {
        if mode == EditorViewMode::D2 {
            return None;
        }
        let key = Self::view_key(map_id, mode);
        let pos = self.editing_view_pos_by_map.get(&key).copied()?;
        let look = self.editing_view_look_by_map.get(&key).copied()?;
        Some((pos, look))
    }

    pub fn store_edit_view_2d_for_map(&mut self, map_id: Uuid, offset: Vec2<f32>, grid_size: f32) {
        self.editing_view_2d_by_map
            .insert(map_id, (offset, grid_size));
    }

    pub fn load_edit_view_2d_for_map(&self, map_id: Uuid) -> Option<(Vec2<f32>, f32)> {
        self.editing_view_2d_by_map.get(&map_id).copied()
    }

    pub fn store_edit_view_iso_scale_for_map(&mut self, map_id: Uuid, scale: f32) {
        self.editing_view_iso_scale_by_map.insert(map_id, scale);
    }

    pub fn load_edit_view_iso_scale_for_map(&self, map_id: Uuid) -> Option<f32> {
        self.editing_view_iso_scale_by_map.get(&map_id).copied()
    }

    /// Clears all state data.
    pub fn clear(&mut self) {
        self.curr_region_content = ContentContext::Unknown;
        self.curr_character = ContentContext::Unknown;
        self.curr_item = ContentContext::Unknown;
        self.cc = ContentContext::Unknown;

        self.curr_region = Uuid::nil();
        self.curr_grid_id = None;
        self.curr_screen = Uuid::nil();
        self.interactions.clear();
        self.moved_entities.clear();
        self.moved_items.clear();
        self.editing_view_pos_by_map.clear();
        self.editing_view_look_by_map.clear();
        self.editing_view_2d_by_map.clear();
        self.editing_view_iso_scale_by_map.clear();
    }

    pub fn clear_interactions(&mut self) {
        self.interactions.clear();
    }

    /// Convert local screen position to a map grid position
    pub fn local_to_map_grid(
        &self,
        screen_size: Vec2<f32>,
        coord: Vec2<f32>,
        map: &Map,
        subdivisions: f32,
    ) -> Vec2<f32> {
        let grid_space_pos = coord - screen_size / 2.0 - Vec2::new(map.offset.x, -map.offset.y);
        let snapped = grid_space_pos / map.grid_size;
        let rounded = snapped.map(|x| x.round());

        if subdivisions > 1.0 {
            let subdivision_size = 1.0 / subdivisions;
            // Calculate fractional part of the snapped position
            let fractional = snapped - rounded;
            // Snap the fractional part to the nearest subdivision
            rounded + fractional.map(|x| (x / subdivision_size).round() * subdivision_size)
        } else {
            rounded
        }
    }

    /// Snap to a grid cell
    pub fn local_to_map_cell(
        &self,
        screen_size: Vec2<f32>,
        coord: Vec2<f32>,
        map: &Map,
        subdivisions: f32,
    ) -> Vec2<f32> {
        let grid_space_pos = coord - screen_size / 2.0 - Vec2::new(map.offset.x, -map.offset.y);
        let grid_cell = (grid_space_pos / map.grid_size).map(|x| x.floor());

        if subdivisions > 1.0 {
            let sub_cell_size = map.grid_size / subdivisions;
            let sub_index = grid_space_pos
                .map(|x| x.rem_euclid(map.grid_size) / sub_cell_size)
                .map(|x| x.floor());
            grid_cell + sub_index / subdivisions
        } else {
            grid_cell
        }
    }

    /// Convert a map grid position to a local screen position
    pub fn map_grid_to_local(screen_size: Vec2<f32>, grid_pos: Vec2<f32>, map: &Map) -> Vec2<f32> {
        let grid_space_pos = grid_pos * map.grid_size;
        grid_space_pos + Vec2::new(map.offset.x, -map.offset.y) + screen_size / 2.0
    }

    /// Centers the map at the given grid position.
    pub fn center_map_at_grid_pos(
        &mut self,
        _screen_size: Vec2<f32>,
        grid_pos: Vec2<f32>,
        map: &mut Map,
    ) {
        let pixel_pos = grid_pos * map.grid_size;
        map.offset.x = -(pixel_pos.x);
        map.offset.y = pixel_pos.y;
    }

    /// Returns the geometry at the given screen_position
    pub fn geometry_at(
        &self,
        screen_size: Vec2<f32>,
        screen_pos: Vec2<f32>,
        map: &Map,
    ) -> (Option<u32>, Option<u32>, Option<u32>) {
        let mut selection: (Option<u32>, Option<u32>, Option<u32>) = (None, None, None);
        let hover_threshold = 6.0;

        // Check the vertices
        for vertex in &map.vertices {
            if vertex.intersects_vertical_slice(self.editing_slice, self.editing_slice_height) {
                if let Some(vertex_pos) = map.get_vertex(vertex.id) {
                    let vertex_pos = Self::map_grid_to_local(screen_size, vertex_pos, map);
                    if (screen_pos - vertex_pos).magnitude() <= hover_threshold {
                        selection.0 = Some(vertex.id);
                        break;
                    }
                }
            }
        }

        // Check the lines
        for linedef in &map.linedefs {
            if linedef.intersects_vertical_slice(map, self.editing_slice, self.editing_slice_height)
            {
                if self.no_rect_geo_on_map && map.is_linedef_in_rect(linedef.id) {
                    continue;
                }

                let start_vertex = map.get_vertex(linedef.start_vertex);
                let end_vertex = map.get_vertex(linedef.end_vertex);

                if let Some(start_vertex) = start_vertex {
                    if let Some(end_vertex) = end_vertex {
                        let start_pos = Self::map_grid_to_local(screen_size, start_vertex, map);
                        let end_pos = Self::map_grid_to_local(screen_size, end_vertex, map);

                        // Compute the perpendicular distance from the point to the line
                        let line_vec = end_pos - start_pos;
                        let mouse_vec = screen_pos - start_pos;
                        let line_vec_length = line_vec.magnitude();
                        let projection =
                            mouse_vec.dot(line_vec) / (line_vec_length * line_vec_length);
                        let closest_point = start_pos + projection.clamp(0.0, 1.0) * line_vec;
                        let distance = (screen_pos - closest_point).magnitude();

                        if distance <= hover_threshold {
                            selection.1 = Some(linedef.id);
                            break;
                        }
                    }
                }
            }
        }

        // Check the sectors

        /// Point-in-polygon test using the ray-casting method
        fn point_in_polygon(point: Vec2<f32>, polygon: &[Vec2<f32>]) -> bool {
            let mut inside = false;
            let mut j = polygon.len() - 1;

            for i in 0..polygon.len() {
                if (polygon[i].y > point.y) != (polygon[j].y > point.y)
                    && point.x
                        < (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y)
                            / (polygon[j].y - polygon[i].y)
                            + polygon[i].x
                {
                    inside = !inside;
                }
                j = i;
            }

            inside
        }

        // Reverse on sorted sectors by area (to allow to pick small sectors first)
        let ordered = map.sorted_sectors_by_area();
        for sector in ordered.iter().rev() {
            if sector.intersects_vertical_slice(map, self.editing_slice, self.editing_slice_height)
            {
                if self.no_rect_geo_on_map
                    && sector.properties.contains("rect")
                    && sector.name.is_empty()
                {
                    continue;
                }
                let mut vertices = Vec::new();
                for &linedef_id in &sector.linedefs {
                    if let Some(linedef) = map.find_linedef(linedef_id) {
                        if let Some(start_vertex) = map.find_vertex(linedef.start_vertex) {
                            let vertex =
                                Self::map_grid_to_local(screen_size, start_vertex.as_vec2(), map);

                            // Add the vertex to the list if it isn't already there
                            if vertices.last() != Some(&vertex) {
                                vertices.push(vertex);
                            }
                        }
                    }
                }

                if point_in_polygon(screen_pos, &vertices) {
                    selection.2 = Some(sector.id);
                    return selection;
                }
            }
        }

        selection
    }

    /// Returns all geometry within the given rectangle.
    pub fn geometry_in_rectangle(
        &self,
        top_left: Vec2<f32>,
        bottom_right: Vec2<f32>,
        map: &Map,
    ) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
        let mut selection: (Vec<u32>, Vec<u32>, Vec<u32>) = (Vec::new(), Vec::new(), Vec::new());

        // Define helper to check if a point is within the rectangle
        fn point_in_rectangle(
            point: Vec2<f32>,
            top_left: Vec2<f32>,
            bottom_right: Vec2<f32>,
        ) -> bool {
            point.x >= top_left.x
                && point.x <= bottom_right.x
                && point.y >= top_left.y
                && point.y <= bottom_right.y
        }

        /// Check if a line segment intersects a rectangle
        fn line_intersects_rectangle(
            a: Vec2<f32>,
            b: Vec2<f32>,
            top_left: Vec2<f32>,
            bottom_right: Vec2<f32>,
        ) -> bool {
            // fn between(x: f32, min: f32, max: f32) -> bool {
            //     x >= min && x <= max
            // }

            // Axis-Aligned Bounding Box (AABB) test for the line segment
            let (min_x, max_x) = (a.x.min(b.x), a.x.max(b.x));
            let (min_y, max_y) = (a.y.min(b.y), a.y.max(b.y));

            if min_x > bottom_right.x
                || max_x < top_left.x
                || min_y > bottom_right.y
                || max_y < top_left.y
            {
                return false; // Line is outside the rectangle
            }

            // Check if either endpoint is inside the rectangle
            if point_in_rectangle(a, top_left, bottom_right)
                || point_in_rectangle(b, top_left, bottom_right)
            {
                return true;
            }

            // Check edge intersections
            let rect_edges = [
                (top_left, Vec2::new(bottom_right.x, top_left.y)), // Top
                (Vec2::new(bottom_right.x, top_left.y), bottom_right), // Right
                (bottom_right, Vec2::new(top_left.x, bottom_right.y)), // Bottom
                (Vec2::new(top_left.x, bottom_right.y), top_left), // Left
            ];

            rect_edges
                .iter()
                .any(|&(p1, p2)| line_segments_intersect(a, b, p1, p2))
        }

        /// Check if two line segments intersect
        fn line_segments_intersect(
            p1: Vec2<f32>,
            p2: Vec2<f32>,
            q1: Vec2<f32>,
            q2: Vec2<f32>,
        ) -> bool {
            fn ccw(a: Vec2<f32>, b: Vec2<f32>, c: Vec2<f32>) -> bool {
                (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x)
            }

            ccw(p1, q1, q2) != ccw(p2, q1, q2) && ccw(p1, p2, q1) != ccw(p1, p2, q2)
        }

        // Check vertices
        for vertex in &map.vertices {
            if vertex.intersects_vertical_slice(self.editing_slice, self.editing_slice_height) {
                if let Some(vertex_pos) = map.get_vertex(vertex.id) {
                    if point_in_rectangle(vertex_pos, top_left, bottom_right) {
                        selection.0.push(vertex.id);
                    }
                }
            }
        }

        // Check linedefs
        for linedef in &map.linedefs {
            if linedef.intersects_vertical_slice(map, self.editing_slice, self.editing_slice_height)
            {
                let start_vertex = map.get_vertex(linedef.start_vertex);
                let end_vertex = map.get_vertex(linedef.end_vertex);

                if let (Some(start_vertex), Some(end_vertex)) = (start_vertex, end_vertex) {
                    let start_pos = start_vertex;
                    let end_pos = end_vertex;

                    // Check if either endpoint is inside the rectangle
                    if point_in_rectangle(start_pos, top_left, bottom_right)
                        || point_in_rectangle(end_pos, top_left, bottom_right)
                    {
                        selection.1.push(linedef.id);
                    }
                }
            }
        }

        // Check sectors
        // fn point_in_polygon(point: Vec2f, polygon: &[Vec2f]) -> bool {
        //     let mut inside = false;
        //     let mut j = polygon.len() - 1;

        //     for i in 0..polygon.len() {
        //         if (polygon[i].y > point.y) != (polygon[j].y > point.y)
        //             && point.x
        //                 < (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y)
        //                     / (polygon[j].y - polygon[i].y)
        //                     + polygon[i].x
        //         {
        //             inside = !inside;
        //         }
        //         j = i;
        //     }

        //     inside
        // }

        for sector in &map.sectors {
            if sector.intersects_vertical_slice(map, self.editing_slice, self.editing_slice_height)
            {
                let mut vertices = Vec::new();
                for &linedef_id in &sector.linedefs {
                    if let Some(linedef) = map.find_linedef(linedef_id) {
                        if let Some(start_vertex) = map.find_vertex(linedef.start_vertex) {
                            let vertex = start_vertex.as_vec2();

                            // Add the vertex to the list if it isn't already there
                            if vertices.last() != Some(&vertex) {
                                vertices.push(vertex);
                            }
                        }
                    }
                }

                // Check if any part of the sector polygon is in the rectangle
                if vertices
                    .iter()
                    .any(|v| point_in_rectangle(*v, top_left, bottom_right))
                    || vertices.windows(2).any(|pair| {
                        // For edges, check if they intersect the rectangle
                        let (a, b) = (pair[0], pair[1]);
                        line_intersects_rectangle(a, b, top_left, bottom_right)
                    })
                {
                    selection.2.push(sector.id);
                }
            }
        }

        selection
    }

    /// Returns false if the hover is empty
    pub fn hover_is_empty(&self) -> bool {
        self.hover.0.is_none() && self.hover.1.is_none() && self.hover.2.is_none()
    }

    /// Converts the hover into arrays.
    pub fn hover_to_arrays(&self) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
        let mut arrays: (Vec<u32>, Vec<u32>, Vec<u32>) = (vec![], vec![], vec![]);
        if let Some(v) = self.hover.0 {
            arrays.0.push(v);
        }
        if let Some(l) = self.hover.1 {
            arrays.1.push(l);
        }
        if let Some(s) = self.hover.2 {
            arrays.2.push(s);
        }
        arrays
    }

    /// Adds the given interactions provided by a server tick to the context.
    pub fn add_interactions(&mut self, interactions: Vec<Interaction>) {
        for interaction in interactions {
            if let Some(interactions) = self.interactions.get_mut(&interaction.to) {
                interactions.push(interaction);
            } else {
                self.interactions.insert(interaction.to, vec![interaction]);
            }
        }
    }
}