deuxfleurs 0.1.0

Viewer for geometry processing data (surface meshes, point clouds, scalar field...)
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
use crate::camera::{Camera, CameraController, CameraUniform};
use crate::data::internal::{DataSettings, DataUniformBuilder};
use crate::deferred;
use crate::picker::{self, Picked};
use crate::point_cloud::{
    DisplayPointCloud, PointCloud, PointCloudDataBuffer, PointCloudFixedRenderer, PointCloudMut,
    PointCloudPipeline, UninitedPointCloud,
};
use crate::sbv::SBV;
use crate::screenshot;
use crate::segment::{
    DisplaySegment, Segment, SegmentDataBuffer, SegmentFixedRenderer, SegmentMut, SegmentPipeline,
    UninitedSegment,
};
use crate::surface::{
    DisplaySurface, NewSurfaceAttachment, Surface, SurfaceAttachment, SurfaceDataBuffer,
    SurfaceFixedRenderer, SurfaceMut, SurfacePipeline, UninitedSurface,
};
use crate::texture;
use crate::types::SurfaceIndices;
use crate::types::*;
use crate::ui::UiDataElement;
#[cfg(not(target_arch = "wasm32"))]
use egui_winit::clipboard::Clipboard;
use pollster::FutureExt;
#[cfg(feature = "saves")]
use serde::{Deserialize, Serialize};
#[cfg(target_arch = "wasm32")]
use web_sys::Clipboard;

use crate::Settings;
use crate::shape::{
    AttachedGeometry, DataBuffer, DisplayShape, EmptyAttached, FixedRenderer, GraphicalContext,
    NewAttachedGeometry, Render, RenderPipeline, Renderer, Shape, ShapeGeometry, ShapeMut,
    ShapeSettings, UninitedShape,
};
use egui;
use indexmap::IndexMap;
use rand::rngs::SmallRng;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use winit::event_loop::EventLoopProxy;
use winit::{event_loop::EventLoop, window::Window};
mod render_loop;

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(module = "/src/save.js")]
extern "C" {
    fn save_state(filename: &str, data: &[u8]);
}

#[repr(C)]
#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct LightUniform {
    position: [f32; 3],
    _padding: u32,
    color: [f32; 3],
    _padding2: u32,
}

#[repr(C)]
#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct JitterUniform {
    x: f32,
    y: f32,
    _padding: [u32; 2],
}

pub trait ContextHolder {
    type Context<'a>;
    type SurfaceRenderer;
    type SurfaceAttachedData;
    type PointCloudRenderer;
    type PointCloudAttachedData;
    type SegmentRenderer;
    type SegmentAttachedData;
}

pub trait ContainerContextGiver<Shape>: ContextHolder {
    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, Shape>,
        Self::Context<'_>,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    );

    fn get_container(&self) -> &IndexMap<String, Shape>;
}

pub trait GeometryHolder<Shape>: ContainerContextGiver<Shape> {
    type Args;

    fn register(
        &mut self,
        name: String,
        args: Self::Args,
    ) -> ShapeMut<'_, Shape, Self::Context<'_>>;

    fn get_shape_mut(&mut self, name: &str) -> Option<ShapeMut<'_, Shape, Self::Context<'_>>>;

    fn get_shape(&self, name: &str) -> Option<&'_ Shape>;

    fn remove_shape(&mut self, name: &str);
}

impl<Geometry, Settings, Data, Attached, T>
    GeometryHolder<UninitedShape<Geometry, Settings, Data, Attached>> for T
where
    for<'a> T: ContextHolder<Context<'a> = &'a mut crate::Settings>,
    T: ContainerContextGiver<UninitedShape<Geometry, Settings, Data, Attached>>,
    Geometry: ShapeGeometry,
    Settings: DataUniformBuilder + ShapeSettings,
    Data: DataSettings,
    for<'a> Attached: AttachedGeometry<&'a mut crate::Settings> + NewAttachedGeometry,
{
    type Args = Geometry::Args;

    fn register(
        &mut self,
        name: String,
        args: Self::Args,
    ) -> ShapeMut<UninitedShape<Geometry, Settings, Data, Attached>, Self::Context<'_>> {
        use crate::shape::ShapeTrait;
        let (container, mut context, _, _, _) = self.get_container_mut();
        if container.contains_key(&name) {
            let shape = container.get_mut(&name).unwrap();
            shape.replace(args, &mut context);
            ShapeMut {
                inner: shape,
                context,
            }
        } else {
            let shape = Shape::new_bare(name.clone(), args, None);
            container.insert(name.clone(), shape);
            ShapeMut {
                inner: container.get_mut(&name).unwrap(),
                context,
            }
        }
    }

    fn get_shape_mut(
        &mut self,
        name: &str,
    ) -> Option<ShapeMut<UninitedShape<Geometry, Settings, Data, Attached>, Self::Context<'_>>>
    {
        let (container, context, _, _, _) = self.get_container_mut();
        container.get_mut(name).map(|shape| ShapeMut {
            inner: shape,
            context,
        })
    }

    fn get_shape(
        &self,
        name: &str,
    ) -> Option<&'_ UninitedShape<Geometry, Settings, Data, Attached>> {
        self.get_container().get(name)
    }

    fn remove_shape(&mut self, name: &str) {
        let (container, _context, _should_resize, _counters_dirty, _picked) =
            self.get_container_mut();
        container.shift_remove(name);
    }
}

impl<Geometry, Fixed, DataB, Pipeline, Settings, Data, Attached, T>
    GeometryHolder<DisplayShape<Geometry, Fixed, DataB, Pipeline, Settings, Data, Attached>> for T
where
    for<'a> T: ContextHolder<Context<'a> = GraphicalContext<'a>>,
    T: ContainerContextGiver<
        DisplayShape<Geometry, Fixed, DataB, Pipeline, Settings, Data, Attached>,
    >,
    for<'a> Attached: AttachedGeometry<GraphicalContext<'a>>,
    Geometry: ShapeGeometry + Clone,
    Data: DataUniformBuilder + DataSettings + UiDataElement + Clone,
    Settings: ShapeSettings + Clone,
    Fixed: FixedRenderer<Geometry = Geometry>,
    DataB: DataBuffer<Data = Data, Geometry = Geometry>,
    Pipeline: RenderPipeline<Settings = Settings, Data = Data, Geometry = Geometry>,
    Renderer<Fixed, DataB, Pipeline>: Render,
{
    type Args = Geometry::Args;

    fn register(
        &mut self,
        name: String,
        args: Self::Args,
    ) -> ShapeMut<
        DisplayShape<Geometry, Fixed, DataB, Pipeline, Settings, Data, Attached>,
        Self::Context<'_>,
    > {
        use crate::shape::ShapeTrait;
        let (container, mut context, should_resize, counters_dirty, picked) =
            self.get_container_mut();
        *context.refresh_screen = true;
        // This could be better with Polonius
        if container.contains_key(&name) {
            let shape = container.get_mut(&name).unwrap();
            if !shape.replace(args, &mut context) {
                should_resize.map(|should_resize| *should_resize = true);
                counters_dirty.map(|counters_dirty| *counters_dirty = true);
                let picked = picked.unwrap();
                if let Some((picked_name, _picked)) = picked {
                    if *picked_name == name {
                        *picked = None;
                    }
                }
            }
            ShapeMut {
                inner: shape,
                context: context,
            }
        } else {
            let shape = Shape::new(
                name.clone(),
                args,
                None,
                context.device,
                context.camera_light_bind_group_layout,
                context.counter_bind_group_layout,
                context.color_format,
            );
            container.insert(name.clone(), shape);
            should_resize.map(|should_resize| *should_resize = true);
            counters_dirty.map(|counters_dirty| *counters_dirty = true);
            let picked = picked.unwrap();
            if let Some((picked_name, _picked)) = picked {
                if *picked_name == name {
                    *picked = None;
                }
            }
            ShapeMut {
                inner: container.get_mut(&name).unwrap(),
                context,
            }
        }
    }

    fn get_shape_mut(
        &mut self,
        name: &str,
    ) -> Option<
        ShapeMut<
            DisplayShape<Geometry, Fixed, DataB, Pipeline, Settings, Data, Attached>,
            Self::Context<'_>,
        >,
    > {
        let (container, context, _, _, _) = self.get_container_mut();
        container.get_mut(name).map(|shape| ShapeMut {
            inner: shape,
            context,
        })
    }

    fn get_shape(
        &self,
        name: &str,
    ) -> Option<&DisplayShape<Geometry, Fixed, DataB, Pipeline, Settings, Data, Attached>> {
        self.get_container().get(name)
    }

    fn remove_shape(&mut self, name: &str) {
        let (container, context, _should_resize, counters_dirty, picked) = self.get_container_mut();
        if let Some(shape) = container.shift_remove(name) {
            let picked = picked.unwrap();
            if let Some((picked_name, _picked)) = picked {
                if *picked_name == name {
                    *picked = None;
                }
            }
            *context.refresh_screen |= shape.show;
            *counters_dirty.unwrap() = true;
        }
    }
}

/// Holds the application state. Starting point to add visualization datas.
pub struct InnerGraphicalState {
    surfaces: IndexMap<String, DisplaySurface>,
    clouds: IndexMap<String, DisplayPointCloud>,
    segments: IndexMap<String, DisplaySegment>,
    pub(crate) settings: Settings,

    window: Option<Arc<Window>>,
    proxy: Option<EventLoopProxy<UserEvent>>,
    // Graphic context
    surface: Option<wgpu::Surface<'static>>,
    device: wgpu::Device,
    queue: wgpu::Queue,
    config: wgpu::SurfaceConfiguration,
    // Window size
    size: winit::dpi::PhysicalSize<u32>,
    // Textures
    depth_texture: texture::Texture,
    // Screenshots
    screenshoter: screenshot::Screenshoter,

    // Keyboard
    ctrl_pressed: bool,
    // Camera
    camera: Camera,
    camera_controller: CameraController,
    camera_uniform: CameraUniform,
    camera_buffer: wgpu::Buffer,
    // Lighting
    light_uniform: LightUniform,
    light_buffer: wgpu::Buffer,
    jitter_buffer: wgpu::Buffer,
    camera_light_bind_group_layout: wgpu::BindGroupLayout,
    camera_light_bind_group: wgpu::BindGroup,
    // egui
    //ui: ui::UI,
    //time: std::time::Instant,
    pub(crate) dirty: bool,
    egui_dirty: bool,
    should_resize: bool,

    // Item picker
    pub(crate) picker: picker::Picker,

    copy: deferred::TextureCopy,
    pbr_renderer: deferred::PBR,
    ground: deferred::Ground,
    taa_counter: u8,
    sbv: SBV,
    rng: SmallRng,
}

impl ContextHolder for InnerGraphicalState {
    type Context<'a> = GraphicalContext<'a>;
    type SurfaceRenderer = Renderer<SurfaceFixedRenderer, SurfaceDataBuffer, SurfacePipeline>;
    type SurfaceAttachedData = SurfaceAttachment;
    type PointCloudRenderer =
        Renderer<PointCloudFixedRenderer, PointCloudDataBuffer, PointCloudPipeline>;
    type PointCloudAttachedData = EmptyAttached;
    type SegmentRenderer = Renderer<SegmentFixedRenderer, SegmentDataBuffer, SegmentPipeline>;
    type SegmentAttachedData = EmptyAttached;
}

impl ContainerContextGiver<DisplaySurface> for InnerGraphicalState {
    fn get_container(&self) -> &IndexMap<String, DisplaySurface> {
        &self.surfaces
    }

    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, DisplaySurface>,
        Self::Context<'_>,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    ) {
        (
            &mut self.surfaces,
            Self::Context {
                settings: &self.settings,
                device: &self.device,
                queue: &self.queue,
                camera_light_bind_group_layout: &self.camera_light_bind_group_layout,
                counter_bind_group_layout: &self.picker.bind_group_layout,
                color_format: self.config.format,
                refresh_screen: &mut self.dirty,
            },
            Some(&mut self.should_resize),
            Some(&mut self.picker.counters_dirty),
            Some(&mut self.picker.picked_item),
        )
    }
}

impl ContainerContextGiver<DisplayPointCloud> for InnerGraphicalState {
    fn get_container(&self) -> &IndexMap<String, DisplayPointCloud> {
        &self.clouds
    }

    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, DisplayPointCloud>,
        Self::Context<'_>,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    ) {
        (
            &mut self.clouds,
            Self::Context {
                settings: &self.settings,
                device: &self.device,
                queue: &self.queue,
                camera_light_bind_group_layout: &self.camera_light_bind_group_layout,
                counter_bind_group_layout: &self.picker.bind_group_layout,
                color_format: self.config.format,
                refresh_screen: &mut self.dirty,
            },
            Some(&mut self.should_resize),
            Some(&mut self.picker.counters_dirty),
            Some(&mut self.picker.picked_item),
        )
    }
}

impl ContainerContextGiver<DisplaySegment> for InnerGraphicalState {
    fn get_container(&self) -> &IndexMap<String, DisplaySegment> {
        &self.segments
    }

    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, DisplaySegment>,
        Self::Context<'_>,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    ) {
        (
            &mut self.segments,
            Self::Context {
                settings: &self.settings,
                device: &self.device,
                queue: &self.queue,
                camera_light_bind_group_layout: &self.camera_light_bind_group_layout,
                counter_bind_group_layout: &self.picker.bind_group_layout,
                color_format: self.config.format,
                refresh_screen: &mut self.dirty,
            },
            Some(&mut self.should_resize),
            Some(&mut self.picker.counters_dirty),
            Some(&mut self.picker.picked_item),
        )
    }
}

impl StateTrait for InnerGraphicalState {
    #[cfg(feature = "saves")]
    fn load_from_state_slice(&mut self, data: &[u8]) -> Result<(), ()> {
        let bared = serde_cbor::from_slice(data).map_err(|_| ())?;
        self.receive_save(bared);
        Ok(())
    }

    #[cfg(feature = "saves")]
    fn save_state_vec(&self) -> Result<Vec<u8>, ()> {
        let surfaces = self
            .surfaces
            .iter()
            .map(|(name, field)| (name.clone(), field.downgrade()))
            .collect();
        let clouds = self
            .clouds
            .iter()
            .map(|(name, field)| (name.clone(), field.downgrade()))
            .collect();
        let segments = self
            .segments
            .iter()
            .map(|(name, field)| (name.clone(), field.downgrade()))
            .collect();
        let bared = InnerBareStateSerde {
            settings: self.settings.clone(),
            camera: self.camera.clone(),
            surfaces,
            clouds,
            segments,
            ground_level: self.ground.level,
        };
        serde_cbor::to_vec(&bared).map_err(|_| ())
    }

    fn get_camera(&self) -> &Camera {
        &self.camera
    }

    fn get_camera_mut(&mut self) -> &mut Camera {
        // Conservative
        self.dirty = true;
        &mut self.camera
    }

    fn get_settings(&self) -> &Settings {
        &self.settings
    }

    fn get_settings_mut(&mut self) -> &mut Settings {
        // Conservative
        self.dirty = true;
        &mut self.settings
    }
}

pub struct InnerBareState<T: FnMut(&mut egui::Ui, &mut RunningState)> {
    pub(crate) surfaces: IndexMap<String, UninitedSurface>,
    pub(crate) clouds: IndexMap<String, UninitedPointCloud>,
    pub(crate) segments: IndexMap<String, UninitedSegment>,
    pub settings: Settings,
    pub camera: Camera,
    pub(crate) callback: T,
}

#[cfg(feature = "saves")]
#[derive(Serialize, Deserialize)]
pub(crate) struct InnerBareStateSerde {
    pub(crate) surfaces: IndexMap<String, UninitedSurface>,
    pub(crate) clouds: IndexMap<String, UninitedPointCloud>,
    pub(crate) segments: IndexMap<String, UninitedSegment>,
    pub(crate) settings: Settings,
    pub(crate) camera: Camera,
    pub(crate) ground_level: f32,
}

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> ContextHolder for InnerBareState<T> {
    type Context<'a> = &'a mut Settings;
    type SurfaceRenderer = ();
    type SurfaceAttachedData = NewSurfaceAttachment;
    type PointCloudRenderer = ();
    type PointCloudAttachedData = ();
    type SegmentRenderer = ();
    type SegmentAttachedData = ();
}

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> ContainerContextGiver<UninitedSurface>
    for InnerBareState<T>
{
    fn get_container(&self) -> &IndexMap<String, UninitedSurface> {
        &self.surfaces
    }

    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, UninitedSurface>,
        &mut Settings,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    ) {
        (&mut self.surfaces, &mut self.settings, None, None, None)
    }
}

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> ContainerContextGiver<UninitedPointCloud>
    for InnerBareState<T>
{
    fn get_container(&self) -> &IndexMap<String, UninitedPointCloud> {
        &self.clouds
    }

    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, UninitedPointCloud>,
        &mut Settings,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    ) {
        (&mut self.clouds, &mut self.settings, None, None, None)
    }
}

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> ContainerContextGiver<UninitedSegment>
    for InnerBareState<T>
{
    fn get_container(&self) -> &IndexMap<String, UninitedSegment> {
        &self.segments
    }

    fn get_container_mut(
        &mut self,
    ) -> (
        &mut IndexMap<String, UninitedSegment>,
        &mut Settings,
        Option<&mut bool>,
        Option<&mut bool>,
        Option<&mut Option<(String, Picked)>>,
    ) {
        (&mut self.segments, &mut self.settings, None, None, None)
    }
}

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> StateTrait for InnerBareState<T> {
    #[cfg(feature = "saves")]
    fn load_from_state_slice(&mut self, data: &[u8]) -> Result<(), ()> {
        let bared: InnerBareStateSerde = serde_cbor::from_slice(data).map_err(|_| ())?;
        self.surfaces = bared.surfaces;
        self.clouds = bared.clouds;
        self.segments = bared.segments;
        self.settings = bared.settings;
        self.camera = bared.camera;
        Ok(())
    }

    #[cfg(feature = "saves")]
    fn save_state_vec(&self) -> Result<Vec<u8>, ()> {
        let surfaces = self.surfaces.clone();
        let clouds = self.clouds.clone();
        let segments = self.segments.clone();
        let bared = InnerBareStateSerde {
            settings: self.settings.clone(),
            camera: self.camera.clone(),
            surfaces,
            clouds,
            segments,
            //ground_level: self.ground.level,
            ground_level: 0.,
        };
        serde_cbor::to_vec(&bared).map_err(|_| ())
    }

    fn get_camera(&self) -> &Camera {
        &self.camera
    }

    fn get_camera_mut(&mut self) -> &mut Camera {
        &mut self.camera
    }

    fn get_settings(&self) -> &Settings {
        &self.settings
    }

    fn get_settings_mut(&mut self) -> &mut Settings {
        &mut self.settings
    }
}

pub trait StateTrait:
    GeometryHolder<
        Surface<
            <Self as ContextHolder>::SurfaceRenderer,
            <Self as ContextHolder>::SurfaceAttachedData,
        >,
        Args = (SurfaceIndices, Vec<[f32; 3]>),
    > + GeometryHolder<
        PointCloud<
            <Self as ContextHolder>::PointCloudRenderer,
            <Self as ContextHolder>::PointCloudAttachedData,
        >,
        Args = Vec<[f32; 3]>,
    > + GeometryHolder<
        Segment<
            <Self as ContextHolder>::SegmentRenderer,
            <Self as ContextHolder>::SegmentAttachedData,
        >,
        Args = (Vec<[f32; 3]>, Vec<[u32; 2]>),
    >
{
    #[cfg(feature = "saves")]
    fn load_from_state_slice(&mut self, data: &[u8]) -> Result<(), ()>;

    #[cfg(feature = "saves")]
    fn save_state_vec(&self) -> Result<Vec<u8>, ()>;

    fn get_camera(&self) -> &Camera;

    fn get_camera_mut(&mut self) -> &mut Camera;

    fn get_settings(&self) -> &Settings;

    fn get_settings_mut(&mut self) -> &mut Settings;
}

pub struct State<T>(pub(crate) T);

impl<T: StateTrait> State<T> {
    pub(crate) fn new_inner(inner: T) -> Self {
        Self(inner)
    }

    /// Register a new surface. If an existing one with same number of vertices
    /// and same faces exists, previous settings and data are recovered.
    ///
    /// See [`Surface`] and [`SurfaceMut`] for how to add data to the created
    /// shape.
    pub fn register_surface<V: Vertices, I: Into<SurfaceIndices>>(
        &mut self,
        name: impl Into<String>,
        vertices: V,
        indices: I,
    ) -> SurfaceMut<T::SurfaceRenderer, T::SurfaceAttachedData, T::Context<'_>> {
        self.0
            .register(name.into(), (indices.into(), vertices.into()))
    }

    pub fn get_surface_mut(
        &mut self,
        name: &str,
    ) -> Option<SurfaceMut<T::SurfaceRenderer, T::SurfaceAttachedData, T::Context<'_>>> {
        self.0.get_shape_mut(name)
    }

    pub fn get_surface(
        &self,
        name: &str,
    ) -> Option<&Surface<T::SurfaceRenderer, T::SurfaceAttachedData>> {
        self.0.get_shape(name)
    }

    pub fn remove_surface(&mut self, name: &str) {
        <T as GeometryHolder<Surface<T::SurfaceRenderer, T::SurfaceAttachedData>>>::remove_shape(
            &mut self.0,
            name,
        );
    }

    /// Register a new point cloud. If an existing one with same number of points
    /// exists, previous settings and data are recovered.
    ///
    /// See [`PointCloud`] and [`PointCloudMut`] for how to add data to the created
    /// shape.
    pub fn register_point_cloud<V: Vertices>(
        &mut self,
        name: impl Into<String>,
        positions: V,
    ) -> PointCloudMut<T::PointCloudRenderer, T::PointCloudAttachedData, T::Context<'_>> {
        self.0.register(name.into(), positions.into())
    }

    pub fn get_point_cloud_mut(
        &mut self,
        name: &str,
    ) -> Option<PointCloudMut<T::PointCloudRenderer, T::PointCloudAttachedData, T::Context<'_>>>
    {
        self.0.get_shape_mut(name)
    }

    pub fn get_point_cloud(
        &self,
        name: &str,
    ) -> Option<&PointCloud<T::PointCloudRenderer, T::PointCloudAttachedData>> {
        self.0.get_shape(name)
    }

    pub fn remove_point_cloud(&mut self, name: &str) {
        <T as GeometryHolder<PointCloud<T::PointCloudRenderer, T::PointCloudAttachedData>>>::remove_shape(
                &mut self.0,
                name,
            );
    }

    /// Register a list of segments. If an existing one with same number of points
    /// and same connextions exists, previous settings and data are recovered.
    ///
    /// See [`Segment`] and [`SegmentMut`] for how to add data to the created
    /// shape.
    ///
    /// Arguments :
    /// * `positions`: segments extremities
    /// * `connections`: segments denoted by extremities indices
    pub fn register_segment<V: Vertices>(
        &mut self,
        name: impl Into<String>,
        positions: V,
        connections: Vec<[u32; 2]>,
    ) -> SegmentMut<T::SegmentRenderer, T::SegmentAttachedData, T::Context<'_>> {
        self.0
            .register(name.into(), (positions.into(), connections))
    }

    pub fn get_segment_mut(
        &mut self,
        name: &str,
    ) -> Option<SegmentMut<T::SegmentRenderer, T::SegmentAttachedData, T::Context<'_>>> {
        self.0.get_shape_mut(name)
    }

    pub fn get_segment(
        &self,
        name: &str,
    ) -> Option<&Segment<T::SegmentRenderer, T::SegmentAttachedData>> {
        self.0.get_shape(name)
    }

    pub fn remove_segment(&mut self, name: &str) {
        <T as GeometryHolder<Segment<T::SegmentRenderer, T::SegmentAttachedData>>>::remove_shape(
            &mut self.0,
            name,
        );
    }

    /// Load app state from given file content.
    #[cfg_attr(docsrs, doc(cfg(all(feature = "saves", not(target_arch = "wasm32")))))]
    #[cfg(all(feature = "saves", not(target_arch = "wasm32")))]
    pub fn load_from_state_file(&mut self, path: impl AsRef<std::path::Path>) -> Result<(), ()> {
        let data = std::fs::read(path.as_ref()).map_err(|_| ())?;
        self.0.load_from_state_slice(&data)
    }

    /// Load app state from given buffer.
    #[cfg_attr(docsrs, doc(cfg(feature = "saves")))]
    #[cfg(feature = "saves")]
    pub fn load_from_state_slice(&mut self, data: &[u8]) -> Result<(), ()> {
        self.0.load_from_state_slice(data)
    }

    /// Save current state in cbor into chosen file.
    #[cfg_attr(docsrs, doc(cfg(all(feature = "saves", not(target_arch = "wasm32")))))]
    #[cfg(all(feature = "saves", not(target_arch = "wasm32")))]
    pub fn save_state_file(&self, path: impl AsRef<std::path::Path>) -> Result<(), ()> {
        let data = self.0.save_state_vec()?;
        std::fs::write(path.as_ref(), &data).map_err(|_| ())
    }

    /// Save current state in cbor, downloaded in browser.
    #[cfg_attr(docsrs, doc(cfg(all(feature = "saves", target_arch = "wasm32"))))]
    #[cfg(all(feature = "saves", target_arch = "wasm32"))]
    pub fn save_state(&self) -> Result<(), ()> {
        let data = self.0.save_state_vec()?;
        save_state("deuxfleurs.cbor", &data);
        Ok(())
    }

    /// Save current state in cbor into buffer.
    #[cfg_attr(docsrs, doc(cfg(feature = "saves")))]
    #[cfg(feature = "saves")]
    pub fn save_state_vec(&self) -> Result<Vec<u8>, ()> {
        self.0.save_state_vec()
    }

    pub fn get_settings_mut(&mut self) -> &mut Settings {
        self.0.get_settings_mut()
    }

    pub fn get_settings(&self) -> &Settings {
        self.0.get_settings()
    }

    pub fn set_camera(&mut self, eye: [f32; 3], target: [f32; 3], up: [f32; 3]) {
        self.0
            .get_camera_mut()
            .set_from_eye_target_up(eye, target, up);
    }

    /// Result is `(eye, target, up)`.
    pub fn get_camera(&self) -> ([f32; 3], [f32; 3], [f32; 3]) {
        self.0.get_camera().as_eye_target_up()
    }
}

/// Starting point to build the app.
pub type InitialState<T: FnMut(&mut egui::Ui, &mut RunningState)> = State<InnerBareState<T>>;

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> InitialState<T> {
    /// Show the window and start the app.
    ///
    /// In wasm, `width` and `height` are ignored and css is used to define the dimensions
    /// (allowing for dimensions in `%` and `vh`/`vw`).
    ///
    /// Arguments:
    /// * `width`: requested width of the app (no effect in wasm)
    /// * `height`: requested height of the app (no effect in wasm)
    /// * `id`: serves as window title, or id shape to attach to. If `None` uses `"State"`.
    ///
    /// ```
    /// use deuxfleurs::load_mesh;
    ///
    /// # fn main() {
    /// #     pollster::block_on(run());
    /// # }
    /// # pub async fn run() {
    /// let (spot_v, spot_f) = load_mesh("examples/assets/spot.obj").await.unwrap();
    /// let mut handle = deuxfleurs::init();
    /// handle.register_surface("Spot", spot_v, spot_f);
    /// let mut handle = handle.run(1920, 1080, Some("deuxfleurs"));
    /// # }
    /// ```
    pub fn run<S: Into<String>>(self, width: u32, height: u32, id: Option<S>) {
        StateWrapper::run(self, width, height, id.map(Into::into));
    }

    /// Run the app without a window. Allows running the app in environment where no
    /// display is available and taking screenshots automatically.
    ///
    /// Currently only available on non wasm targets, as webGL requires a context.
    ///
    /// ```
    /// use deuxfleurs::load_mesh;
    ///
    /// # fn main() {
    /// #     pollster::block_on(run());
    /// # }
    /// # pub async fn run() {
    /// let (spot_v, spot_f) = load_mesh("examples/assets/spot.obj").await.unwrap();
    /// let mut handle = deuxfleurs::init();
    /// handle.register_surface("Spot", spot_v, spot_f);
    /// let mut handle = handle.run_headless();
    /// handle.screenshot();
    /// # }
    /// ```
    #[cfg(not(target_arch = "wasm32"))]
    #[cfg_attr(docsrs, doc(cfg(not(target_arch = "wasm32"))))]
    pub fn run_headless(self) -> RunningState {
        let inner = InnerGraphicalState::new(
            self.0.surfaces,
            self.0.clouds,
            self.0.segments,
            self.0.settings,
            self.0.camera,
            None,
            None,
        )
        .block_on();
        RunningState::new_inner(inner)
    }

    /// Specify a callback that will be called once every frame.
    ///
    /// Passes an [`egui::Ui`] and a [`RunningState`] arguments which can be
    /// used to add UI elements and modify state accordingly.
    pub fn with_callback<U: FnMut(&mut egui::Ui, &mut RunningState)>(
        self,
        callback: U,
    ) -> InitialState<U> {
        let InnerBareState {
            surfaces,
            clouds,
            segments,
            settings,
            camera,
            ..
        } = self.0;
        let inner = InnerBareState {
            surfaces,
            clouds,
            segments,
            settings,
            callback,
            camera,
        };
        InitialState::new_inner(inner)
    }
}

/// Holds the application state. Starting point to add visualization datas.
pub type RunningState = State<InnerGraphicalState>;

struct StateWrapper<T: FnMut(&mut egui::Ui, &mut RunningState)> {
    init_state: Option<InitialState<T>>,
    state: Option<RunningState>,
    ui: Option<crate::ui::UI>,
    clipboard: Option<Clipboard>,
    callback: Option<T>,
    id: String,
    width: u32,
    height: u32,
    proxy: EventLoopProxy<UserEvent>,
}

pub(crate) enum UserEvent {
    #[cfg(feature = "obj_button")]
    LoadMesh(Vec<[f32; 3]>, crate::types::SurfaceIndices, String),
    #[cfg(feature = "saves")]
    LoadState(InnerBareStateSerde),
    Paste(String),
    Pick,
}

impl Deref for RunningState {
    type Target = InnerGraphicalState;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for RunningState {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl RunningState {
    async fn new(
        surfaces: IndexMap<String, UninitedSurface>,
        clouds: IndexMap<String, UninitedPointCloud>,
        segments: IndexMap<String, UninitedSegment>,
        camera: Camera,
        settings: Settings,
        window: Window,
        proxy: EventLoopProxy<UserEvent>,
    ) -> Self {
        let inner = InnerGraphicalState::new(
            surfaces,
            clouds,
            segments,
            settings,
            camera,
            Some(window),
            Some(proxy),
        )
        .await;
        Self::new_inner(inner)
    }

    /// Fit camera and ground to match the visible shapes
    pub fn resize_scene(&mut self) {
        self.0.resize_scene();
    }

    /// Take a screenshot of the scene. The screenshot is then
    /// saved on disk under the name `screenshot_[nnn].png`, with
    /// `nnn` incrementing each time.
    pub fn screenshot(&mut self) {
        self.0.screenshot();
    }

    /// Take a screenshot of the scene. The screenshot is then
    /// returned as a vector oy bytes, each storing `r` `g` `b`
    /// `a` (in order) values of each pixel.
    ///
    /// Should not fail, unless internal buffer storage is
    /// messed up.
    pub fn screenshot_to_buffer(&mut self) -> Result<Vec<u8>, ()> {
        self.0.screenshot_to_buffer()
    }

    /// Get current selected object: first the name, then index `i` and type of the selected element
    pub fn get_picked(&self) -> &Option<(String, Picked)> {
        self.0.get_picked()
    }

    /// Politely ask to render the next frame, even if no change is detected
    pub fn refresh(&mut self) {
        self.0.refresh();
    }
}

impl<T: FnMut(&mut egui::Ui, &mut RunningState)> StateWrapper<T> {
    fn run(init_state: InitialState<T>, width: u32, height: u32, id: Option<String>) {
        let id = id.unwrap_or("deuxfleurs".into());
        #[cfg(target_arch = "wasm32")]
        {
            std::panic::set_hook(Box::new(console_error_panic_hook::hook));
        }
        #[cfg(feature = "logger")]
        cfg_if::cfg_if! {
            if #[cfg(target_arch = "wasm32")] {
                console_log::init_with_level(log::Level::Warn).expect("Couldn't initialize logger");
            } else {
                env_logger::init();
            }
        }

        let event_loop = EventLoop::<UserEvent>::with_user_event().build().unwrap();
        let proxy = event_loop.create_proxy();
        let mut app = Self {
            init_state: Some(init_state),
            state: None,
            clipboard: None,
            callback: None,
            ui: None,
            id,
            width,
            height,
            proxy,
        };
        event_loop.run_app(&mut app).unwrap();
    }
}