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
//! This module implements the rendering algorithm of maplibre-rs. It manages the whole
//! communication with the GPU.
//!
//! The render in this module is largely based on the
//! [bevy_render](https://github.com/bevyengine/bevy/tree/aced6a/crates/bevy_render)
//! crate with commit `aced6a`.
//! It is dual-licensed under MIT and Apache:
//!
//! ```text
//! Bevy is dual-licensed under either
//!
//! * MIT License (docs/LICENSE-MIT or http://opensource.org/licenses/MIT)
//! * Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
//!
//! at your option.
//! ```
//!
//! We appreciate the design and implementation work which as gone into it.
//!

use std::{ops::Deref, rc::Rc, sync::Arc};

use crate::{
    environment::Environment,
    kernel::Kernel,
    plugin::Plugin,
    render::{
        error::RenderError,
        eventually::Eventually,
        graph::{EmptyNode, RenderGraph},
        main_pass::{MainPassDriverNode, MainPassNode},
        resource::{Head, Surface, Texture, TextureView},
        settings::{RendererSettings, WgpuSettings},
        systems::{
            cleanup_system::cleanup_system, resource_system::ResourceSystem,
            sort_phase_system::sort_phase_system,
            tile_view_pattern_system::tile_view_pattern_system,
        },
    },
    schedule::{Schedule, StageLabel},
    tcs::{
        system::{stage::SystemStage, SystemContainer},
        world::World,
    },
    window::{HeadedMapWindow, MapWindow},
};

pub mod graph;
pub mod resource;
mod systems;

// Rendering internals
mod graph_runner;
mod main_pass;
pub mod shaders; // TODO: Make private

// Public API
pub mod builder;
pub mod camera;
pub mod error;
pub mod eventually;
pub mod render_commands;
pub mod render_phase;
pub mod settings;
pub mod tile_view_pattern;
pub mod view_state;

pub use shaders::ShaderVertex;

use crate::{
    render::{
        render_phase::{LayerItem, RenderPhase, TileMaskItem},
        systems::{graph_runner_system::GraphRunnerSystem, upload_system::upload_system},
        tile_view_pattern::{ViewTileSources, WgpuTileViewPattern},
    },
    window::PhysicalSize,
};

pub(crate) const INDEX_FORMAT: wgpu::IndexFormat = wgpu::IndexFormat::Uint32; // Must match IndexDataType

/// The labels of the default App rendering stages.
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub enum RenderStageLabel {
    /// Extract data from the world.
    Extract,

    /// Prepare render resources from the extracted data for the GPU.
    /// For example during this phase textures are created, buffers are allocated and written.
    Prepare,

    /// Queues [PhaseItems](render_phase::PhaseItem) that depend on
    /// [`Prepare`](RenderStageLabel::Prepare) data and queue up draw calls to run during the
    /// [`Render`](RenderStageLabel::Render) stage.
    /// For example data is uploaded to the GPU in this stage.
    Queue,

    /// Sort the [`RenderPhases`](crate::render_phase::RenderPhase) here.
    PhaseSort,

    /// Actual rendering happens here.
    /// In most cases, only the render backend should insert resources here.
    Render,

    /// Cleanup render resources here.
    Cleanup,
}

impl StageLabel for RenderStageLabel {
    fn dyn_clone(&self) -> Box<dyn StageLabel> {
        Box::new(self.clone())
    }
}

pub struct RenderResources {
    pub surface: Surface,
    pub render_target: Eventually<TextureView>,
    pub depth_texture: Eventually<Texture>,
    pub multisampling_texture: Eventually<Option<Texture>>,
}

impl RenderResources {
    pub fn new(surface: Surface) -> Self {
        Self {
            render_target: Default::default(),
            depth_texture: Default::default(),
            multisampling_texture: Default::default(),
            surface,
        }
    }

    pub fn recreate_surface<MW>(
        &mut self,
        window: &MW,
        instance: &wgpu::Instance,
    ) -> Result<(), RenderError>
    where
        MW: MapWindow + HeadedMapWindow,
    {
        self.surface.recreate::<MW>(window, instance)
    }

    pub fn surface(&self) -> &Surface {
        &self.surface
    }
}

pub struct Renderer {
    pub instance: wgpu::Instance,
    pub device: Arc<wgpu::Device>, // TODO: Arc is needed for headless rendering. Is there a simpler solution?
    pub queue: wgpu::Queue,
    pub adapter: wgpu::Adapter,

    pub wgpu_settings: WgpuSettings,
    pub settings: RendererSettings,

    pub resources: RenderResources,
    pub render_graph: RenderGraph,
}

impl Renderer {
    /// Initializes the renderer by retrieving and preparing the GPU instance, device and queue
    /// for the specified backend.
    pub async fn initialize<MW>(
        window: &MW,
        wgpu_settings: WgpuSettings,
        settings: RendererSettings,
    ) -> Result<Self, RenderError>
    where
        MW: MapWindow + HeadedMapWindow,
    {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu_settings.backends.unwrap_or(wgpu::Backends::all()),
            flags: Default::default(),
            dx12_shader_compiler: Default::default(),
            gles_minor_version: Default::default(),
        });

        let surface: wgpu::Surface = unsafe {
            instance
                .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::from_window(&window.handle())?)?
        };

        let (adapter, device, queue) = Self::request_device(
            &instance,
            &wgpu_settings,
            &wgpu::RequestAdapterOptions {
                power_preference: wgpu_settings.power_preference,
                force_fallback_adapter: false,
                compatible_surface: Some(&surface),
            },
        )
        .await?;

        let surface = Surface::from_surface(surface, &adapter, window, &settings);

        match surface.head() {
            Head::Headed(window) => window.configure(&device),
            Head::Headless(_) => {}
        }

        Ok(Self {
            instance,
            device: Arc::new(device),
            queue,
            adapter,
            wgpu_settings,
            settings,
            resources: RenderResources::new(surface),
            render_graph: Default::default(),
        })
    }

    pub async fn initialize_headless<MW>(
        window: &MW,
        wgpu_settings: WgpuSettings,
        settings: RendererSettings,
    ) -> Result<Self, RenderError>
    where
        MW: MapWindow,
    {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu_settings.backends.unwrap_or(wgpu::Backends::all()),
            flags: Default::default(),
            dx12_shader_compiler: Default::default(),
            gles_minor_version: Default::default(),
        });

        let (adapter, device, queue) = Self::request_device(
            &instance,
            &wgpu_settings,
            &wgpu::RequestAdapterOptions {
                power_preference: wgpu_settings.power_preference,
                force_fallback_adapter: false,
                compatible_surface: None,
            },
        )
        .await?;

        let surface = Surface::from_image(&device, window, &settings);

        Ok(Self {
            instance,
            device: Arc::new(device),
            queue,
            adapter,
            wgpu_settings,
            settings,
            resources: RenderResources::new(surface),
            render_graph: Default::default(),
        })
    }

    pub fn resize_surface(&mut self, size: PhysicalSize) {
        self.resources.surface.resize(size)
    }

    /// Requests a device
    async fn request_device(
        instance: &wgpu::Instance,
        settings: &WgpuSettings,
        request_adapter_options: &wgpu::RequestAdapterOptions<'_, '_>,
    ) -> Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue), RenderError> {
        let adapter = instance
            .request_adapter(request_adapter_options)
            .await
            .ok_or(RenderError::RequestAdaptor)?;

        let adapter_info = adapter.get_info();

        #[cfg(not(target_arch = "wasm32"))]
        let trace_path = if settings.record_trace {
            let path = std::path::Path::new("wgpu_trace");
            // ignore potential error, wgpu will log it
            let _ = std::fs::create_dir(path);
            Some(path)
        } else {
            None
        };

        #[cfg(target_arch = "wasm32")]
        let trace_path = None;

        let mut features =
            adapter.features() | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES;
        if adapter_info.device_type == wgpu::DeviceType::DiscreteGpu {
            // `MAPPABLE_PRIMARY_BUFFERS` can have a significant, negative performance impact for
            // discrete GPUs due to having to transfer data across the PCI-E bus and so it
            // should not be automatically enabled in this case. It is however beneficial for
            // integrated GPUs.
            features -= wgpu::Features::MAPPABLE_PRIMARY_BUFFERS;
        }
        let mut limits = adapter.limits();

        // Enforce the disabled features
        if let Some(disabled_features) = settings.disabled_features {
            features -= disabled_features;
        }
        // NOTE: |= is used here to ensure that any explicitly-enabled features are respected.
        features |= settings.features;

        // Enforce the limit constraints
        if let Some(constrained_limits) = settings.constrained_limits.as_ref() {
            // NOTE: Respect the configured limits as an 'upper bound'. This means for 'max' limits, we
            // take the minimum of the calculated limits according to the adapter/backend and the
            // specified max_limits. For 'min' limits, take the maximum instead. This is intended to
            // err on the side of being conservative. We can't claim 'higher' limits that are supported
            // but we can constrain to 'lower' limits.
            limits = wgpu::Limits {
                max_texture_dimension_1d: limits
                    .max_texture_dimension_1d
                    .min(constrained_limits.max_texture_dimension_1d),
                max_texture_dimension_2d: limits
                    .max_texture_dimension_2d
                    .min(constrained_limits.max_texture_dimension_2d),
                max_texture_dimension_3d: limits
                    .max_texture_dimension_3d
                    .min(constrained_limits.max_texture_dimension_3d),
                max_texture_array_layers: limits
                    .max_texture_array_layers
                    .min(constrained_limits.max_texture_array_layers),
                max_bind_groups: limits
                    .max_bind_groups
                    .min(constrained_limits.max_bind_groups),
                max_bindings_per_bind_group: limits
                    .max_bindings_per_bind_group
                    .min(constrained_limits.max_bindings_per_bind_group),
                max_dynamic_uniform_buffers_per_pipeline_layout: limits
                    .max_dynamic_uniform_buffers_per_pipeline_layout
                    .min(constrained_limits.max_dynamic_uniform_buffers_per_pipeline_layout),
                max_dynamic_storage_buffers_per_pipeline_layout: limits
                    .max_dynamic_storage_buffers_per_pipeline_layout
                    .min(constrained_limits.max_dynamic_storage_buffers_per_pipeline_layout),
                max_sampled_textures_per_shader_stage: limits
                    .max_sampled_textures_per_shader_stage
                    .min(constrained_limits.max_sampled_textures_per_shader_stage),
                max_samplers_per_shader_stage: limits
                    .max_samplers_per_shader_stage
                    .min(constrained_limits.max_samplers_per_shader_stage),
                max_storage_buffers_per_shader_stage: limits
                    .max_storage_buffers_per_shader_stage
                    .min(constrained_limits.max_storage_buffers_per_shader_stage),
                max_storage_textures_per_shader_stage: limits
                    .max_storage_textures_per_shader_stage
                    .min(constrained_limits.max_storage_textures_per_shader_stage),
                max_uniform_buffers_per_shader_stage: limits
                    .max_uniform_buffers_per_shader_stage
                    .min(constrained_limits.max_uniform_buffers_per_shader_stage),
                max_uniform_buffer_binding_size: limits
                    .max_uniform_buffer_binding_size
                    .min(constrained_limits.max_uniform_buffer_binding_size),
                max_storage_buffer_binding_size: limits
                    .max_storage_buffer_binding_size
                    .min(constrained_limits.max_storage_buffer_binding_size),
                max_vertex_buffers: limits
                    .max_vertex_buffers
                    .min(constrained_limits.max_vertex_buffers),
                max_vertex_attributes: limits
                    .max_vertex_attributes
                    .min(constrained_limits.max_vertex_attributes),
                max_vertex_buffer_array_stride: limits
                    .max_vertex_buffer_array_stride
                    .min(constrained_limits.max_vertex_buffer_array_stride),
                max_push_constant_size: limits
                    .max_push_constant_size
                    .min(constrained_limits.max_push_constant_size),
                min_uniform_buffer_offset_alignment: limits
                    .min_uniform_buffer_offset_alignment
                    .max(constrained_limits.min_uniform_buffer_offset_alignment),
                min_storage_buffer_offset_alignment: limits
                    .min_storage_buffer_offset_alignment
                    .max(constrained_limits.min_storage_buffer_offset_alignment),
                max_inter_stage_shader_components: limits
                    .max_inter_stage_shader_components
                    .min(constrained_limits.max_inter_stage_shader_components),
                max_color_attachments: limits
                    .max_color_attachments
                    .min(constrained_limits.max_color_attachments),
                max_color_attachment_bytes_per_sample: limits
                    .max_color_attachment_bytes_per_sample
                    .min(constrained_limits.max_color_attachment_bytes_per_sample),
                max_compute_workgroup_storage_size: limits
                    .max_compute_workgroup_storage_size
                    .min(constrained_limits.max_compute_workgroup_storage_size),
                max_compute_invocations_per_workgroup: limits
                    .max_compute_invocations_per_workgroup
                    .min(constrained_limits.max_compute_invocations_per_workgroup),
                max_compute_workgroup_size_x: limits
                    .max_compute_workgroup_size_x
                    .min(constrained_limits.max_compute_workgroup_size_x),
                max_compute_workgroup_size_y: limits
                    .max_compute_workgroup_size_y
                    .min(constrained_limits.max_compute_workgroup_size_y),
                max_compute_workgroup_size_z: limits
                    .max_compute_workgroup_size_z
                    .min(constrained_limits.max_compute_workgroup_size_z),
                max_compute_workgroups_per_dimension: limits
                    .max_compute_workgroups_per_dimension
                    .min(constrained_limits.max_compute_workgroups_per_dimension),
                min_subgroup_size: 0,
                max_buffer_size: limits
                    .max_buffer_size
                    .min(constrained_limits.max_buffer_size),
                max_non_sampler_bindings: limits
                    .max_non_sampler_bindings
                    .min(constrained_limits.max_non_sampler_bindings),
                max_subgroup_size: 0,
            };
        }

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: settings.device_label.as_ref().map(|a| a.as_ref()),
                    required_features: features,
                    required_limits: limits,
                    memory_hints: wgpu::MemoryHints::default(),
                },
                trace_path,
            )
            .await?;
        Ok((adapter, device, queue))
    }

    pub fn instance(&self) -> &wgpu::Instance {
        &self.instance
    }
    pub fn device(&self) -> &wgpu::Device {
        &self.device
    }
    pub fn queue(&self) -> &wgpu::Queue {
        &self.queue
    }
    pub fn state(&self) -> &RenderResources {
        &self.resources
    }
    pub fn surface(&self) -> &Surface {
        &self.resources.surface
    }
}

#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
    use crate::{
        tcs::world::World,
        window::{MapWindow, MapWindowConfig, PhysicalSize, WindowCreateError},
    };

    #[derive(Clone)]
    pub struct HeadlessMapWindowConfig {
        size: PhysicalSize,
    }

    impl MapWindowConfig for HeadlessMapWindowConfig {
        type MapWindow = HeadlessMapWindow;

        fn create(&self) -> Result<Self::MapWindow, WindowCreateError> {
            Ok(Self::MapWindow { size: self.size })
        }
    }

    pub struct HeadlessMapWindow {
        size: PhysicalSize,
    }

    impl MapWindow for HeadlessMapWindow {
        fn size(&self) -> PhysicalSize {
            self.size
        }
    }

    #[tokio::test]
    async fn test_render() {
        use log::LevelFilter;

        use crate::render::{
            graph::RenderGraph, graph_runner::RenderGraphRunner, resource::Surface,
            RenderResources, RendererSettings,
        };

        let _ = env_logger::builder()
            .filter_level(LevelFilter::Trace)
            .is_test(true)
            .try_init();
        let graph = RenderGraph::default();

        let backends = wgpu::util::backend_bits_from_env().unwrap_or(wgpu::Backends::all());
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends,
            flags: Default::default(),
            dx12_shader_compiler: Default::default(),
            gles_minor_version: Default::default(),
        });
        let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, None)
            .await
            .expect("Unable to initialize adapter");

        let (device, queue) = adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    label: None,
                    required_features: wgpu::Features::default(),
                    required_limits: wgpu::Limits::default(),
                    memory_hints: wgpu::MemoryHints::default(),
                },
                None,
            )
            .await
            .expect("Unable to request device");

        let render_state = RenderResources::new(Surface::from_image(
            &device,
            &HeadlessMapWindow {
                size: PhysicalSize::new(100, 100).expect("invalid headless map size"),
            },
            &RendererSettings::default(),
        ));

        let world = World::default();
        RenderGraphRunner::run(&graph, &device, &queue, &render_state, &world)
            .expect("failed to run graph runner");
    }
}

// Contributors to the RenderGraph should use the following label conventions:
// 1. Graph modules should have a NAME, input module, and node module (where relevant)
// 2. The "main_graph" graph is the root.
// 3. "sub graph" modules should be nested beneath their parent graph module
pub mod main_graph {
    // Labels for input nodes
    pub mod input {}
    // Labels for non-input nodes
    pub mod node {
        pub const MAIN_PASS_DEPENDENCIES: &str = "main_pass_dependencies";
        pub const MAIN_PASS_DRIVER: &str = "main_pass_driver";
    }
}

/// Labels for the "draw" graph
mod draw_graph {
    pub const NAME: &str = "draw";
    // Labels for input nodes
    pub mod input {}
    // Labels for non-input nodes
    pub mod node {
        pub const MAIN_PASS: &str = "main_pass";
    }
}

pub struct MaskPipeline(pub wgpu::RenderPipeline);
impl Deref for MaskPipeline {
    type Target = wgpu::RenderPipeline;

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

// TODO: Do we really want a render plugin or do we want to statically do this setup?
#[derive(Default)]
pub struct RenderPlugin;

impl<E: Environment> Plugin<E> for RenderPlugin {
    fn build(
        &self,
        schedule: &mut Schedule,
        _kernel: Rc<Kernel<E>>,
        world: &mut World,
        graph: &mut RenderGraph,
    ) {
        let resources = &mut world.resources;

        let mut draw_graph = RenderGraph::default();
        // Draw nodes
        draw_graph.add_node(draw_graph::node::MAIN_PASS, MainPassNode::new());
        // Input node
        let input_node_id = draw_graph.set_input(vec![]);
        // Edges
        draw_graph
            .add_node_edge(input_node_id, draw_graph::node::MAIN_PASS)
            .expect("main pass or draw node does not exist");

        graph.add_sub_graph(draw_graph::NAME, draw_graph);
        graph.add_node(main_graph::node::MAIN_PASS_DEPENDENCIES, EmptyNode);
        graph.add_node(main_graph::node::MAIN_PASS_DRIVER, MainPassDriverNode);
        graph
            .add_node_edge(
                main_graph::node::MAIN_PASS_DEPENDENCIES,
                main_graph::node::MAIN_PASS_DRIVER,
            )
            .expect("main pass driver or dependencies do not exist");

        // render graph dependency
        resources.init::<RenderPhase<LayerItem>>();
        resources.init::<RenderPhase<TileMaskItem>>();
        // tile_view_pattern:
        resources.insert(Eventually::<WgpuTileViewPattern>::Uninitialized);
        resources.init::<ViewTileSources>();
        // masks
        resources.insert(Eventually::<MaskPipeline>::Uninitialized);

        schedule.add_stage(RenderStageLabel::Extract, SystemStage::default());
        schedule.add_stage(
            RenderStageLabel::Prepare,
            SystemStage::default().with_system(SystemContainer::new(ResourceSystem)),
        );
        schedule.add_stage(
            RenderStageLabel::Queue,
            SystemStage::default()
                .with_system(tile_view_pattern_system)
                .with_system(upload_system),
        );
        schedule.add_stage(
            RenderStageLabel::PhaseSort,
            SystemStage::default().with_system(sort_phase_system),
        );
        schedule.add_stage(
            RenderStageLabel::Render,
            SystemStage::default().with_system(SystemContainer::new(GraphRunnerSystem)),
        );
        schedule.add_stage(
            RenderStageLabel::Cleanup,
            SystemStage::default().with_system(cleanup_system),
        );
    }
}