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
//! Functions and types relating to meshes and shape drawing.

pub use lyon_tessellation::path::builder::BorderRadii;

use std::rc::Rc;

use bytemuck::{Pod, Zeroable};
use lyon_tessellation::geom::euclid::{Point2D, Size2D};
use lyon_tessellation::math::{Angle, Point, Rect, Vector};
use lyon_tessellation::path::builder::{Build, PathBuilder};
use lyon_tessellation::path::{Polygon, Winding};
use lyon_tessellation::{
    BuffersBuilder, FillOptions, FillTessellator, FillVertex, FillVertexConstructor, StrokeOptions,
    StrokeTessellator, StrokeVertex, StrokeVertexConstructor, VertexBuffers,
};

use crate::graphics::{self, ActiveCanvas, ActiveShader, Color, DrawParams, Rectangle, Texture};
use crate::math::Vec2;
use crate::platform::{RawIndexBuffer, RawVertexBuffer};
use crate::Context;
use crate::{Result, TetraError};

/// An individual piece of vertex data.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Vertex {
    /// The position of the vertex, in screen co-ordinates.
    ///
    /// The transform matrix will be applied to this value, followed by a projection
    /// from screen co-ordinates to device co-ordinates.
    pub position: Vec2<f32>,

    /// The texture co-ordinates that should be sampled for this vertex.
    ///
    /// Both the X and the Y should be between 0.0 and 1.0.
    pub uv: Vec2<f32>,

    /// The color of the vertex.
    ///
    /// This will be multiplied by the `color` of the `DrawParams` when drawing a
    /// mesh.
    pub color: Color,
}

impl Vertex {
    /// Creates a new vertex.
    pub fn new(position: Vec2<f32>, uv: Vec2<f32>, color: Color) -> Vertex {
        Vertex {
            position,
            uv,
            color,
        }
    }
}

// SAFETY: While the contract for `Pod` states that all fields should also be `Pod`,
// that isn't possible without upstream changes. All of the fields meet the
// *requirements* to be `Pod`, however, so this should not be unsound.
unsafe impl Pod for Vertex {}
unsafe impl Zeroable for Vertex {}

/// The expected usage of a GPU buffer.
///
/// The GPU may optionally use this to optimize data storage and access.
pub enum BufferUsage {
    /// The buffer's data is not expected to change after creation.
    Static,

    /// The buffer's data is expected to change occasionally after creation.
    Dynamic,

    /// The buffer's data is expected to change every frame.
    Stream,
}

/// The ordering of the vertices in a piece of geometry.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum VertexWinding {
    /// The vertices are in clockwise order.
    Clockwise,

    /// The vertices are in counter-clockwise order.
    CounterClockwise,
}

impl VertexWinding {
    /// Returns the opposite winding, compared to `self`.
    pub fn flipped(self) -> VertexWinding {
        match self {
            VertexWinding::Clockwise => VertexWinding::CounterClockwise,
            VertexWinding::CounterClockwise => VertexWinding::Clockwise,
        }
    }
}

/// Vertex data, stored in GPU memory.
///
/// This data can be drawn to the screen via a [`Mesh`].
///
/// # Performance
///
/// Creating a `VertexBuffer` is a relatively expensive operation. If you can, store them in your
/// [`State`](crate::State) struct rather than recreating them each frame.
///
/// Cloning a `VertexBuffer` is a very cheap operation, as the underlying data is shared between the
/// original instance and the clone via [reference-counting](https://doc.rust-lang.org/std/rc/struct.Rc.html).
/// This does mean, however, that updating a `VertexBuffer` will also update any other clones of
/// that `VertexBuffer`.
///
#[derive(Clone, Debug, PartialEq)]
pub struct VertexBuffer {
    handle: Rc<RawVertexBuffer>,
}

impl VertexBuffer {
    /// Creates a new vertex buffer.
    ///
    /// The buffer will be created with the [`BufferUsage::Dynamic`] usage hint - this can
    /// be overridden via the [`with_usage`](Self::with_usage) constructor.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn new(ctx: &mut Context, vertices: &[Vertex]) -> Result<VertexBuffer> {
        VertexBuffer::with_usage(ctx, vertices, BufferUsage::Dynamic)
    }

    /// Creates a new vertex buffer, with the specified usage hint.
    ///
    /// The GPU may optionally use the usage hint to optimize data storage and access.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn with_usage(
        ctx: &mut Context,
        vertices: &[Vertex],
        usage: BufferUsage,
    ) -> Result<VertexBuffer> {
        let buffer = ctx.device.new_vertex_buffer(vertices.len(), 8, usage)?;

        ctx.device
            .set_vertex_buffer_data(&buffer, bytemuck::cast_slice(vertices), 0);

        Ok(VertexBuffer {
            handle: Rc::new(buffer),
        })
    }

    /// Uploads new vertex data to the GPU.
    ///
    /// # Panics
    ///
    /// Panics if the offset is out of bounds.
    pub fn set_data(&self, ctx: &mut Context, vertices: &[Vertex], offset: usize) {
        ctx.device
            .set_vertex_buffer_data(&self.handle, bytemuck::cast_slice(vertices), offset);
    }

    /// Creates a mesh using this buffer.
    ///
    /// This is a shortcut for calling [`Mesh::new`].
    pub fn into_mesh(self) -> Mesh {
        Mesh::new(self)
    }
}

/// Index data, stored in GPU memory.
///
/// An index buffer can be used as part of a [`Mesh`], in order to describe which vertex data should be drawn,
/// and what order it should be drawn in.
///
/// For example, to draw a square with raw vertex data, you need to use six vertices (two triangles,
/// with three vertices each). This is inefficient, as two of those vertices are shared by the two
/// triangles! Using an index buffer, you can instruct the graphics card to use vertices
/// multiple times while constructing your square.
///
/// Index data is made up of [`u32`] values, each of which correspond to the zero-based index of a vertex.
/// For example, to get the mesh to draw the third vertex, then the first, then the second, you would
/// create an index buffer containing `[2, 0, 1]`.
///
/// # Performance
///
/// Creating an `IndexBuffer` is a relatively expensive operation. If you can, store them in your
/// [`State`](crate::State) struct rather than recreating them each frame.
///
/// Cloning an `IndexBuffer` is a very cheap operation, as the underlying data is shared between the
/// original instance and the clone via [reference-counting](https://doc.rust-lang.org/std/rc/struct.Rc.html).
/// This does mean, however, that updating an `IndexBuffer` will also update any other clones of
/// that `IndexBuffer`.
#[derive(Clone, Debug, PartialEq)]
pub struct IndexBuffer {
    handle: Rc<RawIndexBuffer>,
}

impl IndexBuffer {
    /// Creates a new index buffer.
    ///
    /// The buffer will be created with the [`BufferUsage::Dynamic`] usage hint - this can
    /// be overridden via the [`with_usage`](Self::with_usage) constructor.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn new(ctx: &mut Context, indices: &[u32]) -> Result<IndexBuffer> {
        IndexBuffer::with_usage(ctx, indices, BufferUsage::Dynamic)
    }

    /// Creates a new index buffer, with the specified usage hint.
    ///
    /// The GPU may optionally use the usage hint to optimize data storage and access.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn with_usage(
        ctx: &mut Context,
        indices: &[u32],
        usage: BufferUsage,
    ) -> Result<IndexBuffer> {
        let buffer = ctx.device.new_index_buffer(indices.len(), usage)?;

        ctx.device.set_index_buffer_data(&buffer, indices, 0);

        Ok(IndexBuffer {
            handle: Rc::new(buffer),
        })
    }

    /// Sends new index data to the GPU.
    ///
    /// # Panics
    ///
    /// Panics if the offset is out of bounds.
    pub fn set_data(&self, ctx: &mut Context, indices: &[u32], offset: usize) {
        ctx.device
            .set_index_buffer_data(&self.handle, indices, offset);
    }
}

#[derive(Copy, Clone, Debug)]
struct DrawRange {
    start: usize,
    count: usize,
}

/// Ways of drawing a shape.
#[derive(Copy, Clone, Debug)]
pub enum ShapeStyle {
    /// A filled shape.
    Fill,
    /// An outlined shape with the specified stroke width.
    Stroke(f32),
}

/// A 2D mesh that can be drawn to the screen.
///
/// A `Mesh` is a wrapper for a [`VertexBuffer`], which allows it to be drawn in combination with several
/// optional modifiers:
///
/// * A [`Texture`] that individual vertices can sample from.
/// * An [`IndexBuffer`] that can be used to modify the order/subset of vertices that are drawn.
/// * A winding order, which determines which side of the geometry is front-facing.
/// * A backface culling flag, which determines whether back-facing geometry should be drawn.
/// * A draw range, which can be used to draw subsections of the mesh.
///
/// Without a texture set, the mesh will be drawn in white - the `color` attribute on the [vertex data](Vertex) or
/// [`DrawParams`] can be used to change this.
///
/// Note that, unlike quad rendering via [`Texture`], mesh rendering is not batched by default - each time you
/// draw the mesh will result in a seperate draw call.
///
/// # Performance
///
/// Creating or cloning a `Mesh` is a very cheap operation, as meshes are effectively just collections
/// of resources that live on the GPU. The only expensive part is the creation of the buffers/textures,
/// which can be done ahead of time.
///
/// Note that cloned meshes do not share data, so updating one instance of a mesh will not affect
/// other instances.
///
/// # Examples
///
/// The [`mesh`](https://github.com/17cupsofcoffee/tetra/blob/main/examples/mesh.rs) example demonstrates
/// how to build and draw a simple mesh.
///
/// The [`shapes`](https://github.com/17cupsofcoffee/tetra/blob/main/examples/shapes.rs) example demonstrates
/// how to draw primitive shapes, both through the simplified API on `Mesh`, and the more powerful
/// [`GeometryBuilder`] API.  
#[derive(Clone, Debug)]
pub struct Mesh {
    vertex_buffer: VertexBuffer,
    index_buffer: Option<IndexBuffer>,
    texture: Option<Texture>,
    draw_range: Option<DrawRange>,
    winding: VertexWinding,
    backface_culling: bool,
}

impl Mesh {
    /// Creates a new mesh, using the provided vertex buffer.
    pub fn new(vertex_buffer: VertexBuffer) -> Mesh {
        Mesh {
            vertex_buffer,
            index_buffer: None,
            texture: None,
            draw_range: None,
            winding: VertexWinding::CounterClockwise,
            backface_culling: true,
        }
    }

    /// Creates a new mesh, using the provided vertex and index buffers.
    pub fn indexed(vertex_buffer: VertexBuffer, index_buffer: IndexBuffer) -> Mesh {
        Mesh {
            vertex_buffer,
            index_buffer: Some(index_buffer),
            texture: None,
            winding: VertexWinding::CounterClockwise,
            draw_range: None,
            backface_culling: true,
        }
    }

    /// Creates a new rectangle mesh.
    ///
    /// If you need to draw multiple shapes, consider using [`GeometryBuilder`] to generate a combined mesh
    /// instead.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn rectangle(ctx: &mut Context, style: ShapeStyle, rectangle: Rectangle) -> Result<Mesh> {
        GeometryBuilder::new()
            .rectangle(style, rectangle)?
            .build_mesh(ctx)
    }

    /// Creates a new rounded rectangle mesh.
    ///
    /// If you need to draw multiple shapes, consider using [`GeometryBuilder`] to generate a combined mesh
    /// instead.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn rounded_rectangle(
        ctx: &mut Context,
        style: ShapeStyle,
        rectangle: Rectangle,
        radii: BorderRadii,
    ) -> Result<Mesh> {
        GeometryBuilder::new()
            .rounded_rectangle(style, rectangle, radii)?
            .build_mesh(ctx)
    }

    /// Creates a new circle mesh.
    ///
    /// If you need to draw multiple shapes, consider using [`GeometryBuilder`] to generate a combined mesh
    /// instead.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn circle(
        ctx: &mut Context,
        style: ShapeStyle,
        center: Vec2<f32>,
        radius: f32,
    ) -> Result<Mesh> {
        GeometryBuilder::new()
            .circle(style, center, radius)?
            .build_mesh(ctx)
    }

    /// Creates a new ellipse mesh.
    ///
    /// If you need to draw multiple shapes, consider using [`GeometryBuilder`] to generate a combined mesh
    /// instead.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn ellipse(
        ctx: &mut Context,
        style: ShapeStyle,
        center: Vec2<f32>,
        radii: Vec2<f32>,
    ) -> Result<Mesh> {
        GeometryBuilder::new()
            .ellipse(style, center, radii)?
            .build_mesh(ctx)
    }

    /// Creates a new polygon mesh.
    ///
    /// If you need to draw multiple shapes, consider using [`GeometryBuilder`] to generate a combined mesh
    /// instead.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn polygon(ctx: &mut Context, style: ShapeStyle, points: &[Vec2<f32>]) -> Result<Mesh> {
        GeometryBuilder::new()
            .polygon(style, points)?
            .build_mesh(ctx)
    }

    /// Creates a new polyline mesh.
    ///
    /// If you need to draw multiple shapes, consider using [`GeometryBuilder`] to generate a combined mesh
    /// instead.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn polyline(ctx: &mut Context, stroke_width: f32, points: &[Vec2<f32>]) -> Result<Mesh> {
        GeometryBuilder::new()
            .polyline(stroke_width, points)?
            .build_mesh(ctx)
    }

    /// Draws the mesh to the screen (or to a canvas, if one is enabled).
    pub fn draw<P>(&self, ctx: &mut Context, params: P)
    where
        P: Into<DrawParams>,
    {
        graphics::flush(ctx);

        let texture = match &self.texture {
            Some(t) => t,
            None => &ctx.graphics.default_texture,
        };

        let shader = match &ctx.graphics.shader {
            ActiveShader::Default => &ctx.graphics.default_shader,
            ActiveShader::User(s) => s,
        };

        let params = params.into();
        let model_matrix = params.to_matrix();

        // TODO: Failing to apply the defaults should be handled more gracefully than this,
        // but we can't do that without breaking changes.
        let _ = shader.set_default_uniforms(
            &mut ctx.device,
            ctx.graphics.projection_matrix * ctx.graphics.transform_matrix * model_matrix,
            params.color,
        );

        ctx.device.cull_face(self.backface_culling);

        // Because canvas rendering is effectively done upside-down, the winding order is the opposite
        // of what you'd expect in that case.
        ctx.device.front_face(match &ctx.graphics.canvas {
            ActiveCanvas::Window => self.winding,
            ActiveCanvas::User(_) => self.winding.flipped(),
        });

        let draw_range = self.draw_range.map(|r| (r.start, r.count));

        match &self.index_buffer {
            Some(index_buffer) => {
                let (start, count) = draw_range.unwrap_or_else(|| (0, index_buffer.handle.count()));

                ctx.device.draw_elements(
                    &self.vertex_buffer.handle,
                    &index_buffer.handle,
                    &texture.data.handle,
                    &shader.data.handle,
                    start,
                    count,
                );
            }
            None => {
                let (start, count) =
                    draw_range.unwrap_or_else(|| (0, self.vertex_buffer.handle.count()));

                ctx.device.draw_arrays(
                    &self.vertex_buffer.handle,
                    &texture.data.handle,
                    &shader.data.handle,
                    start,
                    count,
                );
            }
        }
    }

    /// Gets a reference to the vertex buffer contained within this mesh.
    pub fn vertex_buffer(&self) -> &VertexBuffer {
        &self.vertex_buffer
    }

    /// Sets the vertex buffer that will be used when drawing the mesh.
    pub fn set_vertex_buffer(&mut self, vertex_buffer: VertexBuffer) {
        self.vertex_buffer = vertex_buffer;
    }

    /// Gets a reference to the index buffer contained within this mesh.
    ///
    /// Returns [`None`] if this mesh does not currently have an index buffer attatched.
    pub fn index_buffer(&self) -> Option<&IndexBuffer> {
        self.index_buffer.as_ref()
    }

    /// Sets the index buffer that will be used when drawing the mesh.
    pub fn set_index_buffer(&mut self, index_buffer: IndexBuffer) {
        self.index_buffer = Some(index_buffer);
    }

    /// Resets the mesh to no longer use indexed drawing.
    pub fn reset_index_buffer(&mut self) {
        self.index_buffer = None;
    }

    /// Gets a reference to the texture contained within this mesh.
    ///
    /// Returns [`None`] if this mesh does not currently have an texture attatched.
    pub fn texture(&self) -> Option<&Texture> {
        self.texture.as_ref()
    }

    /// Sets the texture that will be used when drawing the mesh.
    pub fn set_texture(&mut self, texture: Texture) {
        self.texture = Some(texture);
    }

    /// Resets the mesh to be untextured.
    pub fn reset_texture(&mut self) {
        self.texture = None;
    }

    /// Returns which winding order represents front-facing geometry in this mesh.
    ///
    /// Back-facing geometry will be culled (not rendered) by default, but
    /// this can be changed via [`set_backface_culling`](Self::set_backface_culling).
    ///
    /// The default winding order is counter-clockwise.
    pub fn front_face_winding(&self) -> VertexWinding {
        self.winding
    }

    /// Sets which winding order represents front-facing geometry in this mesh.
    ///
    /// Back-facing geometry will be culled (not rendered) by default, but
    /// this can be changed via [`set_backface_culling`](Self::set_backface_culling).
    ///
    /// The default winding order is counter-clockwise.
    pub fn set_front_face_winding(&mut self, winding: VertexWinding) {
        self.winding = winding;
    }

    /// Returns whether or not this mesh will cull (not render) back-facing geometry.
    ///
    /// By default, backface culling is enabled, counter-clockwise vertices are
    /// considered front-facing, and clockwise vertices are considered back-facing.
    /// This can be modified via [`set_backface_culling`](Self::set_backface_culling) and
    /// [`set_front_face_winding`](Self::set_front_face_winding).
    pub fn backface_culling(&self) -> bool {
        self.backface_culling
    }

    /// Sets whether or not this mesh will cull (not render) back-facing geometry.
    ///
    /// By default, backface culling is enabled, counter-clockwise vertices are
    /// considered front-facing, and clockwise vertices are considered back-facing.
    /// This can be modified via this function and [`set_front_face_winding`](Self::set_front_face_winding).
    pub fn set_backface_culling(&mut self, enabled: bool) {
        self.backface_culling = enabled;
    }

    /// Sets the range of vertices (or indices, if the mesh is indexed) that should be included
    /// when drawing this mesh.
    ///
    /// This can be useful if you have a large mesh but you only want to want to draw a
    /// subsection of it, or if you want to draw a mesh in multiple stages.
    pub fn set_draw_range(&mut self, start: usize, count: usize) {
        self.draw_range = Some(DrawRange { start, count });
    }

    /// Sets the mesh to include all of its data when drawing.
    pub fn reset_draw_range(&mut self) {
        self.draw_range = None;
    }
}

impl From<VertexBuffer> for Mesh {
    fn from(buffer: VertexBuffer) -> Self {
        Mesh::new(buffer)
    }
}

fn to_lyon_rect(rectangle: Rectangle) -> Rect {
    Rect::new(
        Point2D::new(rectangle.x, rectangle.y),
        Size2D::new(rectangle.width, rectangle.height),
    )
}

struct TetraVertexConstructor(Color);

impl FillVertexConstructor<Vertex> for TetraVertexConstructor {
    fn new_vertex(&mut self, vertex: FillVertex) -> Vertex {
        let position = vertex.position();

        Vertex::new(Vec2::new(position.x, position.y), Vec2::zero(), self.0)
    }
}

impl StrokeVertexConstructor<Vertex> for TetraVertexConstructor {
    fn new_vertex(&mut self, vertex: StrokeVertex) -> Vertex {
        let position = vertex.position();

        Vertex::new(Vec2::new(position.x, position.y), Vec2::zero(), self.0)
    }
}

/// A builder for creating primitive shape geometry, and associated buffers/meshes.
///
/// # Performance
///
/// `GeometryBuilder` stores the generated vertex and index data in a pair of `Vec`s. This means that creating
/// a new builder (as well as cloning an existing one) will allocate memory. Consider reusing a `GeometryBuilder`
/// if you need to reuse the generated data, or if you need to create new data every frame.
///
/// # Examples
///
/// The [`shapes`](https://github.com/17cupsofcoffee/tetra/blob/main/examples/shapes.rs) example demonstrates
/// how to draw primitive shapes, both through the simplified API on [`Mesh`], and the more powerful
/// `GeometryBuilder` API.  
#[derive(Debug, Clone)]
pub struct GeometryBuilder {
    data: VertexBuffers<Vertex, u32>,
    color: Color,
}

impl GeometryBuilder {
    /// Creates a new empty geometry builder.
    pub fn new() -> GeometryBuilder {
        GeometryBuilder {
            data: VertexBuffers::new(),
            color: Color::WHITE,
        }
    }

    /// Adds a rectangle.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    pub fn rectangle(
        &mut self,
        style: ShapeStyle,
        rectangle: Rectangle,
    ) -> Result<&mut GeometryBuilder> {
        let mut builder = BuffersBuilder::new(&mut self.data, TetraVertexConstructor(self.color));

        match style {
            ShapeStyle::Fill => {
                let options = FillOptions::default();
                let mut tessellator = FillTessellator::new();
                tessellator
                    .tessellate_rectangle(&to_lyon_rect(rectangle), &options, &mut builder)
                    .map_err(TetraError::TessellationError)?;
            }

            ShapeStyle::Stroke(width) => {
                let options = StrokeOptions::default().with_line_width(width);
                let mut tessellator = StrokeTessellator::new();
                tessellator
                    .tessellate_rectangle(&to_lyon_rect(rectangle), &options, &mut builder)
                    .map_err(TetraError::TessellationError)?;
            }
        }

        Ok(self)
    }

    /// Adds a rounded rectangle.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    pub fn rounded_rectangle(
        &mut self,
        style: ShapeStyle,
        rectangle: Rectangle,
        radii: BorderRadii,
    ) -> Result<&mut GeometryBuilder> {
        let mut builder = BuffersBuilder::new(&mut self.data, TetraVertexConstructor(self.color));

        match style {
            ShapeStyle::Fill => {
                let options = FillOptions::default();
                let mut tessellator = FillTessellator::new();
                let mut builder = tessellator.builder(&options, &mut builder);
                builder.add_rounded_rectangle(&to_lyon_rect(rectangle), &radii, Winding::Positive);
                builder.build().map_err(TetraError::TessellationError)?;
            }

            ShapeStyle::Stroke(width) => {
                let options = StrokeOptions::default().with_line_width(width);
                let mut tessellator = StrokeTessellator::new();
                let mut builder = tessellator.builder(&options, &mut builder);
                builder.add_rounded_rectangle(&to_lyon_rect(rectangle), &radii, Winding::Positive);
                builder.build().map_err(TetraError::TessellationError)?;
            }
        }

        Ok(self)
    }

    /// Adds a circle.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    pub fn circle(
        &mut self,
        style: ShapeStyle,
        center: Vec2<f32>,
        radius: f32,
    ) -> Result<&mut GeometryBuilder> {
        let mut builder = BuffersBuilder::new(&mut self.data, TetraVertexConstructor(self.color));

        match style {
            ShapeStyle::Fill => {
                let options = FillOptions::default();
                let mut tessellator = FillTessellator::new();

                tessellator
                    .tessellate_circle(
                        Point::new(center.x, center.y),
                        radius,
                        &options,
                        &mut builder,
                    )
                    .map_err(TetraError::TessellationError)?;
            }

            ShapeStyle::Stroke(width) => {
                let options = StrokeOptions::default().with_line_width(width);
                let mut tessellator = StrokeTessellator::new();

                tessellator
                    .tessellate_circle(
                        Point::new(center.x, center.y),
                        radius,
                        &options,
                        &mut builder,
                    )
                    .map_err(TetraError::TessellationError)?;
            }
        }

        Ok(self)
    }

    /// Adds an ellipse.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    pub fn ellipse(
        &mut self,
        style: ShapeStyle,
        center: Vec2<f32>,
        radii: Vec2<f32>,
    ) -> Result<&mut GeometryBuilder> {
        let mut builder = BuffersBuilder::new(&mut self.data, TetraVertexConstructor(self.color));

        match style {
            ShapeStyle::Fill => {
                let options = FillOptions::default();
                let mut tessellator = FillTessellator::new();

                tessellator
                    .tessellate_ellipse(
                        Point::new(center.x, center.y),
                        Vector::new(radii.x, radii.y),
                        Angle::radians(0.0),
                        Winding::Positive,
                        &options,
                        &mut builder,
                    )
                    .map_err(TetraError::TessellationError)?;
            }

            ShapeStyle::Stroke(width) => {
                let options = StrokeOptions::default().with_line_width(width);
                let mut tessellator = StrokeTessellator::new();

                tessellator
                    .tessellate_ellipse(
                        Point::new(center.x, center.y),
                        Vector::new(radii.x, radii.y),
                        Angle::radians(0.0),
                        Winding::Positive,
                        &options,
                        &mut builder,
                    )
                    .map_err(TetraError::TessellationError)?;
            }
        }

        Ok(self)
    }

    /// Adds a polygon.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    pub fn polygon(
        &mut self,
        style: ShapeStyle,
        points: &[Vec2<f32>],
    ) -> Result<&mut GeometryBuilder> {
        let mut builder = BuffersBuilder::new(&mut self.data, TetraVertexConstructor(self.color));

        let points: Vec<Point> = points
            .iter()
            .map(|point| Point::new(point.x, point.y))
            .collect();

        let polygon = Polygon {
            points: &points,
            closed: true,
        };

        match style {
            ShapeStyle::Fill => {
                let options = FillOptions::default();
                let mut tessellator = FillTessellator::new();

                tessellator
                    .tessellate_polygon(polygon, &options, &mut builder)
                    .map_err(TetraError::TessellationError)?;
            }

            ShapeStyle::Stroke(width) => {
                let options = StrokeOptions::default().with_line_width(width);
                let mut tessellator = StrokeTessellator::new();

                tessellator
                    .tessellate_polygon(polygon, &options, &mut builder)
                    .map_err(TetraError::TessellationError)?;
            }
        }

        Ok(self)
    }

    /// Adds a polyline.
    ///
    /// # Errors
    ///
    /// * [`TetraError::TessellationError`](crate::TetraError::TessellationError) will be returned if the shape
    /// could not be turned into vertex data.
    pub fn polyline(
        &mut self,
        stroke_width: f32,
        points: &[Vec2<f32>],
    ) -> Result<&mut GeometryBuilder> {
        let mut builder = BuffersBuilder::new(&mut self.data, TetraVertexConstructor(self.color));

        let points: Vec<Point> = points
            .iter()
            .map(|point| Point::new(point.x, point.y))
            .collect();

        let polygon = Polygon {
            points: &points,
            closed: false,
        };

        let options = StrokeOptions::default().with_line_width(stroke_width);
        let mut tessellator = StrokeTessellator::new();

        tessellator
            .tessellate_polygon(polygon, &options, &mut builder)
            .map_err(TetraError::TessellationError)?;

        Ok(self)
    }

    /// Sets the color that will be used for subsequent shapes.
    ///
    /// You can also use [`DrawParams::color`](super::DrawParams) to tint an entire mesh -
    /// this method only needs to be used if you want to display multiple colors in a
    /// single piece of geometry.
    pub fn set_color(&mut self, color: Color) -> &mut GeometryBuilder {
        self.color = color;
        self
    }

    /// Clears the geometry builder's data.
    pub fn clear(&mut self) -> &mut GeometryBuilder {
        self.data.vertices.clear();
        self.data.indices.clear();

        self
    }

    /// Returns a view of the generated vertex data.
    pub fn vertices(&self) -> &[Vertex] {
        &self.data.vertices
    }

    /// Returns a view of the generated index data.
    pub fn indices(&self) -> &[u32] {
        &self.data.indices
    }

    /// Consumes the builder, returning the generated geometry.
    pub fn into_data(self) -> (Vec<Vertex>, Vec<u32>) {
        (self.data.vertices, self.data.indices)
    }

    /// Builds a vertex and index buffer from the generated geometry.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn build_buffers(&self, ctx: &mut Context) -> Result<(VertexBuffer, IndexBuffer)> {
        Ok((
            VertexBuffer::new(ctx, &self.data.vertices)?,
            IndexBuffer::new(ctx, &self.data.indices)?,
        ))
    }

    /// Builds a mesh from the generated geometry.
    ///
    /// # Errors
    ///
    /// * [`TetraError::PlatformError`](crate::TetraError::PlatformError) will be returned if the underlying
    /// graphics API encounters an error.
    pub fn build_mesh(&self, ctx: &mut Context) -> Result<Mesh> {
        let (vertex_buffer, index_buffer) = self.build_buffers(ctx)?;

        Ok(Mesh::indexed(vertex_buffer, index_buffer))
    }
}

impl Default for GeometryBuilder {
    fn default() -> Self {
        GeometryBuilder::new()
    }
}