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
use std::rc::Rc;

use thiserror::Error;

use crate::{
    context::MapContext,
    coords::{LatLon, Zoom},
    environment::Environment,
    kernel::Kernel,
    render::{
        builder::{
            InitializationResult, InitializedRenderer, RendererBuilder, UninitializedRenderer,
        },
        create_default_render_graph,
        error::RenderError,
        graph::RenderGraphError,
        register_default_render_stages,
    },
    schedule::{Schedule, Stage},
    stages::register_stages,
    style::Style,
    window::{HeadedMapWindow, MapWindow, MapWindowConfig},
    world::World,
};

#[derive(Error, Debug)]
pub enum MapError {
    /// No need to set renderer again
    #[error("renderer was already set for this map")]
    RendererAlreadySet,
    #[error("initializing render graph failed")]
    RenderGraphInit(RenderGraphError),
    #[error("initializing device failed")]
    DeviceInit(RenderError),
}

pub enum MapContextState {
    Ready(MapContext),
    Pending {
        style: Style,
        renderer_builder: RendererBuilder,
    },
}

pub struct Map<E: Environment> {
    kernel: Rc<Kernel<E>>,
    schedule: Schedule,
    map_context: MapContextState,
    window: <E::MapWindowConfig as MapWindowConfig>::MapWindow,
}

impl<E: Environment> Map<E>
where
    <<E as Environment>::MapWindowConfig as MapWindowConfig>::MapWindow: HeadedMapWindow,
{
    pub fn new(
        style: Style,
        kernel: Kernel<E>,
        renderer_builder: RendererBuilder,
    ) -> Result<Self, MapError> {
        let mut schedule = Schedule::default();

        let graph = create_default_render_graph().unwrap(); // TODO: Remove unwrap
        register_default_render_stages(graph, &mut schedule);

        let kernel = Rc::new(kernel);

        register_stages::<E>(&mut schedule, kernel.clone());

        let window = kernel.map_window_config().create();

        let map = Self {
            kernel,
            map_context: MapContextState::Pending {
                style,
                renderer_builder,
            },
            schedule,
            window,
        };
        Ok(map)
    }

    pub async fn initialize_renderer(&mut self) -> Result<(), MapError> {
        match &mut self.map_context {
            MapContextState::Ready(_) => Err(MapError::RendererAlreadySet),
            MapContextState::Pending {
                style,
                renderer_builder,
            } => {
                let init_result = renderer_builder
                    .clone() // Cloning because we want to be able to build multiple times maybe
                    .build()
                    .initialize_renderer::<E::MapWindowConfig>(&self.window)
                    .await
                    .map_err(MapError::DeviceInit)?;

                let window_size = self.window.size();

                let center = style.center.unwrap_or_default();

                let world = World::new_at(
                    window_size,
                    LatLon::new(center[0], center[1]),
                    style.zoom.map(Zoom::new).unwrap_or_default(),
                    cgmath::Deg::<f64>(style.pitch.unwrap_or_default()),
                );

                match init_result {
                    InitializationResult::Initialized(InitializedRenderer { renderer, .. }) => {
                        self.map_context = MapContextState::Ready(MapContext {
                            world,
                            style: std::mem::take(style),
                            renderer,
                        });
                    }
                    InitializationResult::Uninizalized(UninitializedRenderer { .. }) => {}
                    _ => panic!("Rendering context gone"),
                };
                Ok(())
            }
        }
    }

    pub fn window_mut(&mut self) -> &mut <E::MapWindowConfig as MapWindowConfig>::MapWindow {
        &mut self.window
    }
    pub fn window(&self) -> &<E::MapWindowConfig as MapWindowConfig>::MapWindow {
        &self.window
    }

    pub fn has_renderer(&self) -> bool {
        match &self.map_context {
            MapContextState::Ready(_) => true,
            MapContextState::Pending { .. } => false,
        }
    }

    #[tracing::instrument(name = "update_and_redraw", skip_all)]
    pub fn run_schedule(&mut self) -> Result<(), MapError> {
        match &mut self.map_context {
            MapContextState::Ready(map_context) => {
                self.schedule.run(map_context);
                Ok(())
            }
            MapContextState::Pending { .. } => Err(MapError::RendererAlreadySet),
        }
    }

    pub fn context(&self) -> Result<&MapContext, MapError> {
        match &self.map_context {
            MapContextState::Ready(map_context) => Ok(map_context),
            MapContextState::Pending { .. } => Err(MapError::RendererAlreadySet),
        }
    }

    pub fn context_mut(&mut self) -> Result<&mut MapContext, MapError> {
        match &mut self.map_context {
            MapContextState::Ready(map_context) => Ok(map_context),
            MapContextState::Pending { .. } => Err(MapError::RendererAlreadySet),
        }
    }

    pub fn kernel(&self) -> &Rc<Kernel<E>> {
        &self.kernel
    }
}