ascending_graphics 0.38.4

A graphical rendering library for 2D, using wgpu and winit.
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
use crate::{
    CameraView, DrawOrder, GpuRenderer, GraphicsError, Index, Mesh2DVertex,
    OtherError, Vec2, Vec3, Vec4, VertexBuilder, vbo::OrderedIndex,
};
use cosmic_text::Color;
use lyon::{
    lyon_tessellation::{FillOptions, StrokeOptions},
    math::Point as LPoint,
    path::Polygon,
    tessellation as tess,
};

/// Mode in how we will Create the Mesh's vertex layout.
#[derive(Debug, Copy, Clone)]
pub enum DrawMode {
    /// This will mostly only create lines without filling.
    Stroke(StrokeOptions),
    /// This will Create a filled area.
    Fill(FillOptions),
}

impl DrawMode {
    pub fn stroke(width: f32) -> DrawMode {
        DrawMode::Stroke(StrokeOptions::default().with_line_width(width))
    }

    pub fn fill() -> DrawMode {
        DrawMode::Fill(FillOptions::default())
    }
}

/// 2D Meshs to render to screen.
///
#[derive(Debug)]
pub struct Mesh2D {
    /// Position on the Screen.
    pub pos: Vec3,
    /// Width and Height of the mesh.
    pub size: Vec2,
    /// Saved Verticies of the Mesh.
    pub vertices: Vec<Mesh2DVertex>,
    /// Saved indices of the mesh.
    pub indices: Vec<u32>,
    /// Mesh's Vertex Buffer Store [`Index`].
    pub vbo_store_id: Index,
    /// the draw order of the rect. created/updated when update is called.
    pub order: DrawOrder,
    /// Index Max Generated by the Mesh Builder.
    pub high_index: u32,
    // if anything got updated we need to update the buffers too.
    pub changed: bool,
}

impl Mesh2D {
    /// Creates a new [`Mesh2D`] with rendering order layer.
    ///
    /// order_layer: Rendering Order Layer of the rect used in DrawOrder.
    pub fn new(
        renderer: &mut GpuRenderer,
        pos: Vec3,
        order_layer: u32,
    ) -> Self {
        Self {
            pos,
            size: Vec2::default(),
            vbo_store_id: renderer.default_vbo_store(),
            order: DrawOrder::new(false, Vec3::default(), order_layer),
            changed: true,
            vertices: Vec::new(),
            indices: Vec::new(),
            high_index: 0,
        }
    }

    /// Creates a new [`Mesh2D`] with rendering order layer and a indices and vbo se to capacity.
    ///
    /// order_layer: Rendering Order Layer of the rect used in DrawOrder.
    /// capacity: Size to Pre-Create the Vertices and indices at.
    pub fn with_capacity(
        renderer: &mut GpuRenderer,
        pos: Vec3,
        order_layer: u32,
        capacity: usize,
    ) -> Self {
        Self {
            pos,
            size: Vec2::default(),
            vbo_store_id: renderer.default_vbo_store(),
            order: DrawOrder::new(false, Vec3::default(), order_layer),
            changed: true,
            vertices: Vec::with_capacity(capacity),
            indices: Vec::with_capacity(capacity),
            high_index: 0,
        }
    }

    /// Unloads the [`Mesh2D`] from the Instance Buffers Store.
    ///
    pub fn unload(self, renderer: &mut GpuRenderer) {
        renderer.remove_vbo_store(self.vbo_store_id);
    }

    /// Updates the [`Mesh2D`]'s order to overide the last set position.
    /// Use this after calls to set_position to set it to a specific rendering order.
    ///
    pub fn set_order_pos(&mut self, order_override: Vec3) -> &mut Self {
        self.order.set_pos(order_override);
        self
    }

    /// Updates the [`Mesh2D`]'s orders Render Layer.
    ///
    pub fn set_order_layer(&mut self, order_layer: u32) -> &mut Self {
        self.order.order_layer = order_layer;
        self
    }

    /// Updates the [`Mesh2D`]'s [`DrawOrder`]'s is Alpha.
    /// Use this after from_builder, append_from_builder to overide the alpha sorting.
    ///
    pub fn set_order_alpha(&mut self, alpha: bool) -> &mut Self {
        self.order.alpha = alpha;
        self
    }

    /// Clears and Builds Mesh's from the [`Mesh2DBuilder`] into the [`Mesh2D`].
    ///
    pub fn from_builder(&mut self, builder: &Mesh2DBuilder) {
        let mut alpha = false;

        self.vertices.clear();
        self.indices.clear();

        self.size = Vec2::new(
            builder.bounds.z - builder.bounds.x,
            builder.bounds.w - builder.bounds.y,
        );

        self.vertices.reserve(builder.buffer.vertices.len());

        for vertex in &builder.buffer.vertices {
            let mut vertex = *vertex;

            vertex.pos[0] += builder.offset.x;
            vertex.pos[1] += builder.offset.y;

            if Color(vertex.color).a() < 255 {
                alpha = true
            }

            self.vertices.push(vertex);
        }

        self.indices.extend_from_slice(&builder.buffer.indices);

        self.order.alpha = alpha;
        self.high_index = builder.high_index;
        self.changed = true;
    }

    /// Appends Mesh's from the [`Mesh2DBuilder`] into the [`Mesh2D`].
    ///
    pub fn append_from_builder(&mut self, builder: &Mesh2DBuilder) {
        let mut alpha = self.order.alpha;
        let mut new_high_index = self.high_index;
        let size = Vec2::new(
            builder.bounds.z - builder.bounds.x,
            builder.bounds.w - builder.bounds.y,
        );
        self.size = self.size.max(size);

        self.vertices.reserve(builder.buffer.vertices.len());

        for vertex in &builder.buffer.vertices {
            let mut vertex = *vertex;

            vertex.pos[0] += builder.offset.x;
            vertex.pos[1] += builder.offset.y;

            if Color(vertex.color).a() < 255 {
                alpha = true
            }

            self.vertices.push(vertex);
        }

        for index in &builder.buffer.indices {
            let i = index
                + if self.high_index == 0 {
                    0
                } else {
                    self.high_index + 1
                };

            new_high_index = new_high_index.max(i);
            self.indices.push(i);
        }

        self.order.alpha = alpha;
        self.high_index = new_high_index;
        self.changed = true;
    }

    pub fn clear(&mut self) {
        self.vertices.clear();
        self.indices.clear();
        self.high_index = 0;
        self.order.alpha = false;
        self.changed = true;
    }

    /// Sets the [`Mesh2D`]'s Position.
    ///
    pub fn set_pos(&mut self, pos: Vec3) -> &mut Self {
        self.pos = pos;
        self.order.set_pos(pos);
        self.changed = true;
        self
    }

    /// Sets the [`Mesh2D`]'s width and height.
    ///
    pub fn set_size(&mut self, size: Vec2) -> &mut Self {
        self.size = size;
        self.changed = true;
        self
    }

    /// Updates the [`Mesh2D`]'s Buffers to prepare them for rendering.
    ///
    pub fn create_quad(&mut self, renderer: &mut GpuRenderer) {
        if let Some(store) = renderer.get_vbo_store_mut(self.vbo_store_id) {
            let mut verticies = Vec::with_capacity(self.vertices.len());

            for vertex in &self.vertices {
                let mut v = *vertex;

                v.pos[0] += self.pos.x;
                v.pos[1] += self.pos.y;
                verticies.push(v);
            }

            let vertex_bytes: &[u8] = bytemuck::cast_slice(&verticies);
            let index_bytes: &[u8] = bytemuck::cast_slice(&self.indices);

            if vertex_bytes.len() != store.store.len() {
                store.store.resize_with(vertex_bytes.len(), || 0);
            }

            if index_bytes.len() != store.indexs.len() {
                store.indexs.resize_with(index_bytes.len(), || 0);
            }

            store.store.copy_from_slice(vertex_bytes);
            store.indexs.copy_from_slice(index_bytes);
            store.changed = true;
        }
    }

    /// Used to check and update the vertex array.
    /// Returns a [`OrderedIndex`] used in Rendering.
    ///
    pub fn update(&mut self, renderer: &mut GpuRenderer) -> OrderedIndex {
        if self.changed {
            self.create_quad(renderer);
            self.changed = false;
        }

        OrderedIndex::new(self.order, self.vbo_store_id, self.high_index)
    }

    /// Checks if Mouse position is within the [`Mesh2D`]'s Bounds.
    pub fn check_mouse_bounds(&self, mouse_pos: Vec2) -> bool {
        mouse_pos[0] > self.pos.x
            && mouse_pos[0] < self.pos.x + self.size.x
            && mouse_pos[1] > self.pos.y
            && mouse_pos[1] < self.pos.y + self.size.y
    }
}

/// [`Mesh2D`] based on ggez Meshbuilder.
///
#[derive(Debug, Clone)]
pub struct Mesh2DBuilder {
    pub buffer: tess::geometry_builder::VertexBuffers<Mesh2DVertex, u32>,
    pub offset: Vec2,
    pub bounds: Vec4,
    pub size: Vec2,
    pub z: f32,
    pub high_index: u32,
    pub camera_view: CameraView,
}

impl Default for Mesh2DBuilder {
    fn default() -> Self {
        Self {
            buffer: tess::VertexBuffers::new(),
            offset: Vec2::default(),
            bounds: Vec4::new(0.0, 0.0, 0.0, 0.0),
            size: Vec2::new(0.0, 0.0),
            z: 1.0,
            high_index: 0,
            camera_view: CameraView::default(),
        }
    }
}

impl Mesh2DBuilder {
    /// Resets [`Mesh2DBuilder`] back to Defaults so the Builder can be reused.
    ///
    pub fn clear(&mut self) {
        self.buffer.clear();
        self.bounds = Vec4::new(0.0, 0.0, 0.0, 0.0);
        self.size = Vec2::new(0.0, 0.0);
        self.z = 1.0;
        self.high_index = 0;
        self.camera_view = CameraView::default();
    }

    /// Creates a new [`Mesh2DBuilder`] with [`CameraView`].
    ///
    pub fn with_camera_view(camera_view: CameraView) -> Self {
        Self {
            camera_view,
            ..Self::default()
        }
    }

    /// Sets the [`Mesh2DBuilder`]'s offset positions which is used during appending or building to Mesh2D.
    /// This does not affect the finalization Phase.
    ///
    pub fn set_offset(&mut self, offset: Vec2) -> &mut Self {
        self.offset = offset;
        self
    }

    /// Finalizes the [`Mesh2DBuilder`] so it can be appended to a [`Mesh2D`].
    ///
    pub fn finalize(&mut self) -> &mut Self {
        let [minx, miny, maxx, maxy, minz] = self.buffer.vertices.iter().fold(
            [f32::MAX, f32::MAX, f32::MIN, f32::MIN, 1.0],
            |[minx, miny, maxx, maxy, minz], vert| {
                let [x, y, z] = vert.pos;
                [
                    minx.min(x),
                    miny.min(y),
                    maxx.max(x),
                    maxy.max(y),
                    minz.min(z),
                ]
            },
        );

        let high_index = self
            .buffer
            .indices
            .iter()
            .fold(0, |max, index| max.max(*index));
        self.bounds = Vec4::new(minx, miny, maxx, maxy);
        self.size = Vec2::new(maxx - minx, maxy - miny);
        self.z = minz;
        self.high_index = high_index;
        self
    }

    /// Draws a Line within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn line(
        &mut self,
        points: &[Vec2],
        z: f32,
        width: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        self.polyline(DrawMode::stroke(width), points, z, color)
    }

    /// Draws a Circle within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn circle(
        &mut self,
        mode: DrawMode,
        point: Vec2,
        radius: f32,
        tolerance: f32,
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        assert!(tolerance > 0.0, "Tolerances <= 0 are invalid");
        {
            let buffers = &mut self.buffer;
            let vb = VertexBuilder {
                z,
                color,
                camera: self.camera_view as u32,
            };
            match mode {
                DrawMode::Fill(fill_options) => {
                    let mut tessellator = tess::FillTessellator::new();
                    tessellator.tessellate_circle(
                        tess::math::point(point.x, point.y),
                        radius,
                        &fill_options.with_tolerance(tolerance),
                        &mut tess::BuffersBuilder::new(buffers, vb),
                    )?;
                }
                DrawMode::Stroke(options) => {
                    let mut tessellator = tess::StrokeTessellator::new();
                    tessellator.tessellate_circle(
                        tess::math::point(point.x, point.y),
                        radius,
                        &options.with_tolerance(tolerance),
                        &mut tess::BuffersBuilder::new(buffers, vb),
                    )?;
                }
            };
        }
        Ok(self)
    }

    /// Draws an Ellipse within the [`Mesh2DBuilder`] vertex buffer.
    ///
    #[allow(clippy::too_many_arguments)]
    pub fn ellipse(
        &mut self,
        mode: DrawMode,
        point: Vec2,
        radius1: f32,
        radius2: f32,
        tolerance: f32,
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        assert!(tolerance > 0.0, "Tolerances <= 0 are invalid");
        {
            let buffers = &mut self.buffer;
            let vb = VertexBuilder {
                z,
                color,
                camera: self.camera_view as u32,
            };
            match mode {
                DrawMode::Fill(fill_options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let mut tessellator = tess::FillTessellator::new();
                    tessellator.tessellate_ellipse(
                        tess::math::point(point.x, point.y),
                        tess::math::vector(radius1, radius2),
                        tess::math::Angle { radians: 0.0 },
                        tess::path::Winding::Positive,
                        &fill_options.with_tolerance(tolerance),
                        builder,
                    )?;
                }
                DrawMode::Stroke(options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let mut tessellator = tess::StrokeTessellator::new();
                    tessellator.tessellate_ellipse(
                        tess::math::point(point.x, point.y),
                        tess::math::vector(radius1, radius2),
                        tess::math::Angle { radians: 0.0 },
                        tess::path::Winding::Positive,
                        &options.with_tolerance(tolerance),
                        builder,
                    )?;
                }
            };
        }
        Ok(self)
    }

    /// Draws an Polyline within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn polyline(
        &mut self,
        mode: DrawMode,
        points: &[Vec2],
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        if points.len() < 2 {
            return Err(GraphicsError::Other(OtherError::new(
                "MeshBuilder::polyline() got a list of < 2 points",
            )));
        }

        self.polyline_inner(mode, points, false, z, color)
    }

    /// Draws an Polygon within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn polygon(
        &mut self,
        mode: DrawMode,
        points: &[Vec2],
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        if points.len() < 3 {
            return Err(GraphicsError::Other(OtherError::new(
                "MeshBuilder::polygon() got a list of < 3 points",
            )));
        }

        self.polyline_inner(mode, points, true, z, color)
    }

    fn polyline_inner(
        &mut self,
        mode: DrawMode,
        points: &[Vec2],
        is_closed: bool,
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        let vb = VertexBuilder {
            z,
            color,
            camera: self.camera_view as u32,
        };
        self.polyline_with_vertex_builder(mode, points, is_closed, vb)
    }

    /// Draws an Polyline within the [`Mesh2DBuilder`] vertex buffer using a custom vertex builder.
    ///
    pub fn polyline_with_vertex_builder<V>(
        &mut self,
        mode: DrawMode,
        points: &[Vec2],
        is_closed: bool,
        vb: V,
    ) -> Result<&mut Self, GraphicsError>
    where
        V: tess::StrokeVertexConstructor<Mesh2DVertex>
            + tess::FillVertexConstructor<Mesh2DVertex>,
    {
        {
            assert!(points.len() > 1);
            let buffers = &mut self.buffer;
            let points: Vec<LPoint> = points
                .iter()
                .cloned()
                .map(|p| tess::math::point(p.x, p.y))
                .collect();
            let polygon = Polygon {
                points: &points,
                closed: is_closed,
            };
            match mode {
                DrawMode::Fill(options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let tessellator = &mut tess::FillTessellator::new();
                    tessellator
                        .tessellate_polygon(polygon, &options, builder)?;
                }
                DrawMode::Stroke(options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let tessellator = &mut tess::StrokeTessellator::new();
                    tessellator
                        .tessellate_polygon(polygon, &options, builder)?;
                }
            };
        }
        Ok(self)
    }

    /// Draws an Rectangle within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn rectangle(
        &mut self,
        mode: DrawMode,
        bounds: Vec4,
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        {
            let buffers = &mut self.buffer;
            let rect = tess::math::Box2D::from_origin_and_size(
                tess::math::point(bounds.x, bounds.y),
                tess::math::size(bounds.z, bounds.w),
            );
            let vb = VertexBuilder {
                z,
                color,
                camera: self.camera_view as u32,
            };
            match mode {
                DrawMode::Fill(fill_options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let mut tessellator = tess::FillTessellator::new();
                    tessellator.tessellate_rectangle(
                        &rect,
                        &fill_options,
                        builder,
                    )?;
                }
                DrawMode::Stroke(options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let mut tessellator = tess::StrokeTessellator::new();
                    tessellator
                        .tessellate_rectangle(&rect, &options, builder)?;
                }
            };
        }
        Ok(self)
    }

    /// Draws an Rounded Rectangle within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn rounded_rectangle(
        &mut self,
        mode: DrawMode,
        bounds: Vec4,
        z: f32,
        radius: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        {
            let buffers = &mut self.buffer;
            let rect = tess::math::Box2D::from_origin_and_size(
                tess::math::point(bounds.x, bounds.y),
                tess::math::size(bounds.z, bounds.w),
            );
            let radii = tess::path::builder::BorderRadii::new(radius);
            let vb = VertexBuilder {
                z,
                color,
                camera: self.camera_view as u32,
            };
            let mut path_builder = tess::path::Path::builder();
            path_builder.add_rounded_rectangle(
                &rect,
                &radii,
                tess::path::Winding::Positive,
            );
            let path = path_builder.build();

            match mode {
                DrawMode::Fill(fill_options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let mut tessellator = tess::FillTessellator::new();
                    tessellator.tessellate_path(
                        &path,
                        &fill_options,
                        builder,
                    )?;
                }
                DrawMode::Stroke(options) => {
                    let builder = &mut tess::BuffersBuilder::new(buffers, vb);
                    let mut tessellator = tess::StrokeTessellator::new();
                    tessellator.tessellate_path(&path, &options, builder)?;
                }
            };
        }
        Ok(self)
    }

    /// Draws an Triangle within the [`Mesh2DBuilder`] vertex buffer.
    ///
    pub fn triangles(
        &mut self,
        triangles: &[Vec2],
        z: f32,
        color: Color,
    ) -> Result<&mut Self, GraphicsError> {
        {
            if !triangles.len().is_multiple_of(3) {
                return Err(GraphicsError::Other(OtherError::new(
                    "Called MeshBuilder::triangles() with points that have a length not a multiple of 3.",
                )));
            }
            let tris = triangles
                .iter()
                .cloned()
                .map(|p| lyon::math::point(p.x, p.y))
                .collect::<Vec<_>>();
            let tris = tris.chunks(3);
            let vb = VertexBuilder {
                z,
                color,
                camera: self.camera_view as u32,
            };
            for tri in tris {
                assert!(tri.len() == 3);
                let first_index: u32 =
                    self.buffer.vertices.len().try_into().unwrap();
                self.buffer.vertices.push(vb.new_vertex(tri[0]));
                self.buffer.vertices.push(vb.new_vertex(tri[1]));
                self.buffer.vertices.push(vb.new_vertex(tri[2]));
                self.buffer.indices.push(first_index);
                self.buffer.indices.push(first_index + 1);
                self.buffer.indices.push(first_index + 2);
            }
        }
        Ok(self)
    }
}