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
//! Contains the Renderer struct which also contains all the
//! functions and logic to draw things to the screen

use crate::colour::Colour;
use crate::draw_queue::{BindGroups, DrawQueues};
use crate::engine_handle::WgpuClump;
use crate::matrix_math::*;
use crate::rect::Rectangle;
use crate::text::{Text, TransformedText};
use crate::texture::{Texture, TextureCache, TextureIndex};
use crate::vectors::Vec2;
use crate::vertex::{line_vert_pixels_to_screenspace, LineVertex, Vertex};
use crate::wgpu_glyph;
use crate::wgpu_glyph::{orthographic_projection, Layout};
use crate::WHITE_PIXEL;

use image::GenericImageView;
use winit::dpi::PhysicalSize;

/// The handle used for rendering all objects
pub struct Renderer {
    white_pixel: wgpu::BindGroup,
    draw_queues: DrawQueues,
    pipelines: RenderPipelines,
    clear_colour: Colour,
    pub(crate) glyph_brush: wgpu_glyph::GlyphBrush<(), wgpu_glyph::ab_glyph::FontArc>,
    pub(crate) wgpu_clump: WgpuClump, // its very cringe storing this here and not in engine however texture chace requires it
    pub(crate) size: Vec2<u32>,       // goes here bc normilzing stuff
    pub(crate) texture_cache: TextureCache,
}

impl Renderer {
    pub(crate) fn new(
        wgpu_clump: WgpuClump,
        size: PhysicalSize<u32>,
        camera_bind_group_layout: &wgpu::BindGroupLayout,
        clear_colour: Colour,
        texture_format: wgpu::TextureFormat,
    ) -> Self {
        let texture_cache = TextureCache::new();
        let draw_queues = DrawQueues::new();

        let minecraft_mono =
            wgpu_glyph::ab_glyph::FontArc::try_from_slice(include_bytes!("../Monocraft.ttf"))
                .unwrap();
        let glyph_brush = wgpu_glyph::GlyphBrushBuilder::using_font(minecraft_mono)
            .build(&wgpu_clump.device, wgpu::TextureFormat::Bgra8UnormSrgb);

        let white_pixel_image = image::load_from_memory(WHITE_PIXEL).unwrap();
        let white_pixel_rgba = white_pixel_image.to_rgba8();
        let (width, height) = white_pixel_image.dimensions();
        let white_pixel_size = wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        };

        let white_pixel_texture = wgpu_clump.device.create_texture(&wgpu::TextureDescriptor {
            size: white_pixel_size,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            view_formats: &[],
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            label: Some("White_Pixel"),
        });

        wgpu_clump.queue.write_texture(
            wgpu::ImageCopyTextureBase {
                texture: &white_pixel_texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &white_pixel_rgba,
            wgpu::ImageDataLayout {
                offset: 0,
                bytes_per_row: std::num::NonZeroU32::new(width * 4),
                rows_per_image: std::num::NonZeroU32::new(height),
            },
            white_pixel_size,
        );

        let white_pixel_view =
            white_pixel_texture.create_view(&wgpu::TextureViewDescriptor::default());
        let white_pixel_sampler = wgpu_clump.device.create_sampler(&wgpu::SamplerDescriptor {
            // what to do when given cordinates outside the textures height/width
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            // what do when give less or more than 1 pixel to sample
            // linear interprelates between all of them nearest gives the closet colour
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Nearest,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        let bind_group_layout =
            wgpu_clump
                .device
                .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                    entries: &[
                        wgpu::BindGroupLayoutEntry {
                            binding: 0,
                            visibility: wgpu::ShaderStages::FRAGMENT,
                            ty: wgpu::BindingType::Texture {
                                multisampled: false,
                                view_dimension: wgpu::TextureViewDimension::D2,
                                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                            },
                            count: None,
                        },
                        wgpu::BindGroupLayoutEntry {
                            binding: 1,
                            visibility: wgpu::ShaderStages::FRAGMENT,
                            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                            count: None,
                        },
                    ],
                    label: Some("white_pixel_bind_group_layout"),
                });

        let white_pixel = wgpu_clump
            .device
            .create_bind_group(&wgpu::BindGroupDescriptor {
                layout: &bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(&white_pixel_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Sampler(&white_pixel_sampler),
                    },
                ],
                label: Some("diffuse_bind_group"),
            });

        let pipelines = RenderPipelines::new(&wgpu_clump, camera_bind_group_layout, texture_format);

        Self {
            white_pixel,
            draw_queues,
            glyph_brush,
            pipelines,
            clear_colour,
            wgpu_clump,
            size: size.into(),
            texture_cache,
        }
    }

    /// draws a textureless rectangle with a specificed colour
    pub fn draw_rectangle(&mut self, position: Vec2<f32>, width: f32, hieght: f32, colour: Colour) {
        let rectangle =
            Rectangle::from_pixels(position, [width, hieght], colour.to_raw(), self.size);
        self.draw_queues.add_rectangle(&rectangle);
    }

    /// Draws a rectangle in WGSL screenspace. point(-1.0, -1.0) is the bottom left corner and (0.0,0.0) is the center
    /// of the screen.
    pub fn draw_screenspace_rectangle(
        &mut self,
        position: Vec2<f32>,
        width: f32,
        hieght: f32,
        colour: Colour,
    ) {
        let rectangle = Rectangle::new(position, [width, hieght], colour.to_raw());
        self.draw_queues.add_rectangle(&rectangle);
    }

    /// draws a textured rectangle, however it will draw the entire texture
    pub fn draw_textured_rectangle(
        &mut self,
        position: Vec2<f32>,
        width: f32,
        hieght: f32,
        texture: &TextureIndex,
    ) {
        let rectangle =
            Rectangle::from_pixels(position, [width, hieght], Colour::White.to_raw(), self.size);
        self.draw_queues.add_textured_rectange(
            &mut self.texture_cache,
            &rectangle,
            texture,
            &self.wgpu_clump.device,
        );
    }

    /// Draws a textured rectangle in WGSL screenspace. point(-1.0, -1.0) is the bottom left corner and (0.0,0.0) is the
    /// center of the screen.
    pub fn draw_textured_screenspace_rectangle(
        &mut self,
        position: Vec2<f32>,
        width: f32,
        hieght: f32,
        texture: &TextureIndex,
    ) {
        let rectangle = Rectangle::new(position, [width, hieght], Colour::White.to_raw());
        self.draw_queues.add_textured_rectange(
            &mut self.texture_cache,
            &rectangle,
            texture,
            &self.wgpu_clump.device,
        );
    }

    /// draws a textured rectangle with the specifed UV coords.
    /// The image coords are not relative terms but the pixels of the image.
    /// uv_position is the top left corner for the uv rectangle to start, then the width and the height
    /// are just the width and the height of the uv rectangle.
    /// ```rust
    /// renderer.draw_textured_rectangle_with_uv(position, 100.0, 100.0, texture, Vec2{x: 0.0, y: 0.0}, Vec2{x: 100.0, y: 100.0})
    /// ```
    pub fn draw_textured_rectangle_with_uv(
        &mut self,
        position: Vec2<f32>,
        width: f32,
        hieght: f32,
        texture: &TextureIndex,
        uv_position: Vec2<f32>,
        uv_size: Vec2<f32>,
    ) {
        let uv_position = normalize_points(uv_position, texture.size.x, texture.size.y);
        let uv_width = uv_size.x / texture.size.x;
        let uv_height = uv_size.y / texture.size.y;
        let rectangle = Rectangle::from_pixels_with_uv(
            position,
            [width, hieght],
            Colour::White.to_raw(),
            self.size,
            uv_position,
            Vec2 {
                x: uv_width,
                y: uv_height,
            },
        );
        self.draw_queues.add_textured_rectange(
            &mut self.texture_cache,
            &rectangle,
            texture,
            &self.wgpu_clump.device,
        );
    }

    /// draws a regular polygon of any number of sides
    pub fn draw_regular_n_gon(
        &mut self,
        number_of_sides: u16,
        radius: f32,
        center: Vec2<f32>,
        colour: Colour,
    ) {
        self.draw_queues
            .add_regular_n_gon(number_of_sides, radius, center.to_raw(), colour);
    }

    /// draws a line, WILL DRAW ONTOP OF EVERTHING ELSE DUE TO BEING ITS OWN PIPELINE
    pub fn draw_line(&mut self, start_point: Vec2<f32>, end_point: Vec2<f32>, colour: Colour) {
        let start = line_vert_pixels_to_screenspace(
            LineVertex::new(start_point.to_raw(), colour.to_raw()),
            self.size,
        );
        let end = line_vert_pixels_to_screenspace(
            LineVertex::new(end_point.to_raw(), colour.to_raw()),
            self.size,
        );

        self.draw_queues.add_line(start, end)
    }

    /// Draws some text that will appear on top of all other elements due to seperate pipelines
    pub fn draw_text(&mut self, text: &str, position: Vec2<f32>, scale: f32, colour: Colour) {
        let text = Text {
            text: text.into(),
            position,
            scale,
            colour,
        };
        self.draw_queues.add_text(text)
    }

    /// Draws text with custom transform matrix
    pub fn draw_text_with_transform(
        &mut self,
        text: &str,
        position: Vec2<f32>,
        scale: f32,
        colour: Colour,
        transform: [f32; 16],
    ) {
        let text = TransformedText {
            text: text.into(),
            position,
            scale,
            colour,
            transformation: transform,
            bounds: (self.size.x as f32, self.size.y as f32),
        };
        self.draw_queues.add_transfromed_text(text)
    }

    pub(crate) fn render(
        &mut self,
        size: Vec2<u32>,
        camera: &wgpu::BindGroup,
        surface: &wgpu::Surface,
    ) -> Result<(), wgpu::SurfaceError> {
        let output = surface.get_current_texture()?;
        let view = output
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        let mut encoder =
            self.wgpu_clump
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Render Encoder"),
                });

        let render_items = self.draw_queues.process_queued(&self.wgpu_clump.device);

        let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: &view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(self.clear_colour.into()),
                    store: true,
                },
            })],
            depth_stencil_attachment: None,
        });

        render_pass.set_pipeline(&self.pipelines.polygon_pipeline);
        render_pass.set_bind_group(1, camera, &[]);
        if render_items.number_of_rectangle_indicies != 0 {
            render_pass.set_vertex_buffer(0, render_items.rectangle_buffer.slice(..));
            render_pass.set_index_buffer(
                render_items.rectangle_index_buffer.slice(..),
                wgpu::IndexFormat::Uint16,
            );
            let mut current_bind_group = &render_items.rectangle_bind_group_switches[0];
            for (idx, bind_group_switch_point) in render_items
                .rectangle_bind_group_switches
                .iter()
                .enumerate()
            {
                if bind_group_switch_point.bind_group != current_bind_group.bind_group {
                    current_bind_group = bind_group_switch_point;
                }
                let bind_group = match current_bind_group.bind_group {
                    BindGroups::WhitePixel => &self.white_pixel,
                    BindGroups::Custom { bind_group } => &self.texture_cache[bind_group].bind_group,
                };
                render_pass.set_bind_group(0, bind_group, &[]);
                let draw_range = match render_items.rectangle_bind_group_switches.get(idx + 1) {
                    Some(switch_point) => {
                        current_bind_group.point as u32..switch_point.point as u32
                    }
                    None => {
                        current_bind_group.point as u32..render_items.number_of_rectangle_indicies
                    }
                };
                render_pass.draw_indexed(draw_range, 0, 0..1);
            }
        }
        render_pass.set_pipeline(&self.pipelines.line_pipeline);
        render_pass.set_bind_group(0, camera, &[]);
        render_pass.set_vertex_buffer(0, render_items.line_buffer.slice(..));
        render_pass.draw(0..render_items.number_of_line_verticies, 0..1);
        drop(render_pass);

        let mut staging_belt = wgpu::util::StagingBelt::new(1024);

        render_items
            .transformed_text
            .iter()
            .map(|text| {
                (
                    wgpu_glyph::Section {
                        screen_position: (text.position.x, text.position.y),
                        bounds: text.bounds,
                        text: vec![wgpu_glyph::Text::new(&text.text)
                            .with_scale(text.scale)
                            .with_color(text.colour.to_raw())],
                        layout: Layout::default_single_line()
                            .line_breaker(wgpu_glyph::BuiltInLineBreaker::AnyCharLineBreaker),
                    },
                    text.transformation,
                )
            })
            .for_each(|(section, transform)| {
                let text_transform = unflatten_matrix(transform);
                let ortho = unflatten_matrix(orthographic_projection(size.x, size.y));
                let transform = flatten_matrix(ortho * text_transform);
                self.glyph_brush.queue(section);
                self.glyph_brush
                    .draw_queued_with_transform(
                        &self.wgpu_clump.device,
                        &mut staging_belt,
                        &mut encoder,
                        &view,
                        camera,
                        transform,
                    )
                    .unwrap();
            });

        render_items
            .text
            .iter()
            .map(|text| wgpu_glyph::Section {
                screen_position: (text.position.x, text.position.y),
                bounds: (size.x as f32, size.y as f32),
                text: vec![wgpu_glyph::Text::new(&text.text)
                    .with_scale(text.scale)
                    .with_color(text.colour.to_raw())],
                layout: Layout::default_single_line()
                    .line_breaker(wgpu_glyph::BuiltInLineBreaker::AnyCharLineBreaker),
            })
            .for_each(|s| self.glyph_brush.queue(s));

        self.glyph_brush
            .draw_queued(
                &self.wgpu_clump.device,
                &mut staging_belt,
                &mut encoder,
                &view,
                camera,
                size.x,
                size.y,
            )
            .unwrap();

        staging_belt.finish();
        self.wgpu_clump
            .queue
            .submit(std::iter::once(encoder.finish()));
        output.present();

        Ok(())
    }
}

pub(crate) struct RenderPipelines {
    pub(crate) line_pipeline: wgpu::RenderPipeline,
    pub(crate) polygon_pipeline: wgpu::RenderPipeline,
}

impl RenderPipelines {
    pub fn new(
        wgpu_clump: &WgpuClump,
        camera_bind_group_layout: &wgpu::BindGroupLayout,
        texture_format: wgpu::TextureFormat,
    ) -> Self {
        let generic_shader = wgpu_clump
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Shader"),
                source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
            });

        let line_shader = wgpu_clump
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Line_Shader"),
                source: wgpu::ShaderSource::Wgsl(include_str!("shaders/line_shader.wgsl").into()),
            });

        let polygon_pipeline = make_pipeline(
            &wgpu_clump.device,
            wgpu::PrimitiveTopology::TriangleList,
            &[
                &Texture::make_bind_group_layout(&wgpu_clump.device),
                camera_bind_group_layout,
            ],
            &[Vertex::desc()],
            &generic_shader,
            texture_format,
            Some("Generic_pipeline"),
        );

        let line_pipeline = make_pipeline(
            &wgpu_clump.device,
            wgpu::PrimitiveTopology::LineList,
            &[camera_bind_group_layout],
            &[LineVertex::desc()],
            &line_shader,
            texture_format,
            Some("line_renderer"),
        );

        Self {
            polygon_pipeline,
            line_pipeline,
        }
    }
}

fn make_pipeline(
    device: &wgpu::Device,
    topology: wgpu::PrimitiveTopology,
    bind_group_layouts: &[&wgpu::BindGroupLayout],
    vertex_buffers: &[wgpu::VertexBufferLayout],
    shader: &wgpu::ShaderModule,
    texture_format: wgpu::TextureFormat,
    label: Option<&str>,
) -> wgpu::RenderPipeline {
    let layout_label = label.map(|label| format!("{}_layout", label));

    let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: layout_label.as_deref(), // somehow converss Option<String> to Option<&str>
        bind_group_layouts,
        push_constant_ranges: &[],
    });

    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label,
        layout: Some(&layout),
        vertex: wgpu::VertexState {
            module: shader,
            entry_point: "vs_main", //specify the entry point (can be whatever as long as it exists)
            buffers: vertex_buffers, // specfies what type of vertices we want to pass to the shader,
        },
        fragment: Some(wgpu::FragmentState {
            // techically optional. Used to store colour data to the surface
            module: shader,
            entry_point: "fs_main",
            targets: &[Some(wgpu::ColorTargetState {
                // tells wgpu what colour outputs it should set up.
                format: texture_format,
                blend: Some(wgpu::BlendState::ALPHA_BLENDING), // specifies that the blending should just replace old pixel data wiht new data,
                write_mask: wgpu::ColorWrites::ALL,            // writes all colours
            })],
        }),
        primitive: wgpu::PrimitiveState {
            topology,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Cw, // triagnle must be counter-clock wise to be considered facing forawrd
            cull_mode: Some(wgpu::Face::Back), // all triagnles not front facing are culled
            // setting this to anything other than fill requires Features::NON_FILL_POLYGON_MODE
            polygon_mode: wgpu::PolygonMode::Fill,
            // requires Features::DEPTH_CLIP_CONTROLL,
            unclipped_depth: false,
            // requires Features::CONSERVATIVE_RASTERIZATION,
            conservative: false,
        },
        depth_stencil: None,
        multisample: wgpu::MultisampleState {
            count: 1,                         // determines how many samples the pipeline will use
            mask: !0, // how many samples the pipeline will use (in this case all of them)
            alpha_to_coverage_enabled: false, // something to do with AA
        },
        multiview: None,
    })
}