fyrox-ui 0.36.2

Extendable UI library
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
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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use crate::font::FontHeight;
use crate::style::resource::StyleResource;
use crate::{
    brush::Brush,
    core::{
        algebra::{Matrix3, Point2, Vector2},
        color::Color,
        log::Log,
        math::{self, Rect, TriangleDefinition},
    },
    font::FontResource,
    formatted_text::FormattedText,
    Thickness,
};
use bytemuck::{Pod, Zeroable};
use fyrox_core::math::round_to_step;
use fyrox_texture::TextureResource;
use std::ops::Range;

#[derive(Clone, Copy, Debug, Pod, Zeroable)]
#[repr(C)]
pub struct Vertex {
    pub pos: Vector2<f32>,
    pub tex_coord: Vector2<f32>,
    pub color: Color,
}

impl Vertex {
    fn new(pos: Vector2<f32>, tex_coord: Vector2<f32>) -> Vertex {
        Vertex {
            pos,
            tex_coord,
            color: Color::WHITE,
        }
    }
}

#[derive(Clone, Debug)]
pub enum CommandTexture {
    None,
    Texture(TextureResource),
    Font {
        font: FontResource,
        height: FontHeight,
        page_index: usize,
    },
}

/// A set of triangles that will be used for clipping.
#[derive(Clone, Debug)]
pub struct ClippingGeometry {
    pub vertex_buffer: Vec<Vertex>,
    pub triangle_buffer: Vec<TriangleDefinition>,
    pub transform_stack: TransformStack,
}

impl Draw for ClippingGeometry {
    #[inline(always)]
    fn push_vertex_raw(&mut self, mut vertex: Vertex) {
        vertex.pos = self
            .transform_stack
            .transform
            .transform_point(&Point2::from(vertex.pos))
            .coords;

        self.vertex_buffer.push(vertex);
    }

    #[inline(always)]
    fn push_triangle(&mut self, a: u32, b: u32, c: u32) {
        self.triangle_buffer.push(TriangleDefinition([a, b, c]));
    }

    #[inline(always)]
    fn last_vertex_index(&self) -> u32 {
        self.vertex_buffer.len() as u32
    }
}

impl ClippingGeometry {
    pub fn is_contains_point(&self, pos: Vector2<f32>) -> bool {
        for triangle in self.triangle_buffer.iter() {
            if let Some((va, vb, vc)) = self.triangle_points(triangle) {
                if math::is_point_inside_2d_triangle(pos, va.pos, vb.pos, vc.pos) {
                    return true;
                }
            }
        }

        false
    }

    pub fn triangle_points(
        &self,
        triangle: &TriangleDefinition,
    ) -> Option<(&Vertex, &Vertex, &Vertex)> {
        let a = self.vertex_buffer.get(triangle[0] as usize)?;
        let b = self.vertex_buffer.get(triangle[1] as usize)?;
        let c = self.vertex_buffer.get(triangle[2] as usize)?;
        Some((a, b, c))
    }
}

#[derive(Clone, Debug)]
pub struct Command {
    /// Clipping bounds, should be used for scissor-test. Screen-space.
    pub clip_bounds: Rect<f32>,
    /// Total bounds of command's geometry. Screen-space.
    pub bounds: Rect<f32>,
    /// Brush defines visual appearance of rendered geometry.
    pub brush: Brush,
    pub texture: CommandTexture,
    pub triangles: Range<usize>,
    pub opacity: f32,
    /// A set of triangles that defines clipping region.
    pub clipping_geometry: Option<ClippingGeometry>,
}

pub trait Draw {
    fn push_vertex(&mut self, pos: Vector2<f32>, tex_coord: Vector2<f32>) {
        self.push_vertex_raw(Vertex::new(pos, tex_coord))
    }

    fn push_vertex_raw(&mut self, vertex: Vertex);

    fn push_triangle(&mut self, a: u32, b: u32, c: u32);

    fn last_vertex_index(&self) -> u32;

    fn push_triangle_multicolor(&mut self, vertices: [(Vector2<f32>, Color); 3]) {
        let index = self.last_vertex_index();
        for &(pos, color) in &vertices {
            self.push_vertex_raw(Vertex {
                pos,
                tex_coord: Vector2::new(0.0, 0.0),
                color,
            });
        }

        self.push_triangle(index, index + 1, index + 2);
    }

    fn push_triangle_filled(&mut self, vertices: [Vector2<f32>; 3]) {
        let index = self.last_vertex_index();

        for &pos in &vertices {
            self.push_vertex(pos, Default::default());
        }

        self.push_triangle(index, index + 1, index + 2);
    }

    fn push_line(&mut self, a: Vector2<f32>, b: Vector2<f32>, thickness: f32) {
        let index = self.last_vertex_index();
        let perp = get_line_thickness_vector(a, b, thickness);
        self.push_vertex(a - perp, Vector2::new(0.0, 0.0));
        self.push_vertex(b - perp, Vector2::new(1.0, 0.0));
        self.push_vertex(a + perp, Vector2::new(1.0, 1.0));
        self.push_vertex(b + perp, Vector2::new(0.0, 1.0));

        self.push_triangle(index, index + 1, index + 2);
        self.push_triangle(index + 2, index + 1, index + 3);
    }

    fn push_rect(&mut self, rect: &Rect<f32>, thickness: f32) {
        let offset = thickness * 0.5;

        let left_top = Vector2::new(rect.x() + offset, rect.y() + thickness);
        let right_top = Vector2::new(rect.x() + rect.w() - offset, rect.y() + thickness);
        let right_bottom = Vector2::new(
            rect.x() + rect.w() - offset,
            rect.y() + rect.h() - thickness,
        );
        let left_bottom = Vector2::new(rect.x() + offset, rect.y() + rect.h() - thickness);
        let left_top_off = Vector2::new(rect.x(), rect.y() + offset);
        let right_top_off = Vector2::new(rect.x() + rect.w(), rect.y() + offset);
        let right_bottom_off = Vector2::new(rect.x() + rect.w(), rect.y() + rect.h() - offset);
        let left_bottom_off = Vector2::new(rect.x(), rect.y() + rect.h() - offset);

        // Horizontal lines
        self.push_line(left_top_off, right_top_off, thickness);
        self.push_line(right_bottom_off, left_bottom_off, thickness);

        // Vertical line
        self.push_line(right_top, right_bottom, thickness);
        self.push_line(left_bottom, left_top, thickness);
    }

    fn push_rect_vary(&mut self, rect: &Rect<f32>, thickness: Thickness) {
        let left_top = Vector2::new(rect.x() + thickness.left * 0.5, rect.y() + thickness.top);
        let right_top = Vector2::new(
            rect.x() + rect.w() - thickness.right * 0.5,
            rect.y() + thickness.top,
        );
        let right_bottom = Vector2::new(
            rect.x() + rect.w() - thickness.right * 0.5,
            rect.y() + rect.h() - thickness.bottom,
        );
        let left_bottom = Vector2::new(
            rect.x() + thickness.left * 0.5,
            rect.y() + rect.h() - thickness.bottom,
        );
        let left_top_off = Vector2::new(rect.x(), rect.y() + thickness.top * 0.5);
        let right_top_off = Vector2::new(rect.x() + rect.w(), rect.y() + thickness.top * 0.5);
        let right_bottom_off = Vector2::new(
            rect.x() + rect.w(),
            rect.y() + rect.h() - thickness.bottom * 0.5,
        );
        let left_bottom_off = Vector2::new(rect.x(), rect.y() + rect.h() - thickness.bottom * 0.5);

        // Horizontal lines
        self.push_line(left_top_off, right_top_off, thickness.top);
        self.push_line(right_bottom_off, left_bottom_off, thickness.bottom);

        // Vertical lines
        self.push_line(right_top, right_bottom, thickness.right);
        self.push_line(left_bottom, left_top, thickness.left);
    }

    fn push_rect_filled(&mut self, rect: &Rect<f32>, tex_coords: Option<&[Vector2<f32>; 4]>) {
        let index = self.last_vertex_index();
        self.push_vertex(
            Vector2::new(rect.x(), rect.y()),
            tex_coords.map_or(Vector2::new(0.0, 0.0), |t| t[0]),
        );
        self.push_vertex(
            Vector2::new(rect.x() + rect.w(), rect.y()),
            tex_coords.map_or(Vector2::new(1.0, 0.0), |t| t[1]),
        );
        self.push_vertex(
            Vector2::new(rect.x() + rect.w(), rect.y() + rect.h()),
            tex_coords.map_or(Vector2::new(1.0, 1.0), |t| t[2]),
        );
        self.push_vertex(
            Vector2::new(rect.x(), rect.y() + rect.h()),
            tex_coords.map_or(Vector2::new(0.0, 1.0), |t| t[3]),
        );

        self.push_triangle(index, index + 1, index + 2);
        self.push_triangle(index, index + 2, index + 3);
    }

    fn push_rect_multicolor(&mut self, rect: &Rect<f32>, colors: [Color; 4]) {
        let index = self.last_vertex_index();
        self.push_vertex_raw(Vertex {
            pos: rect.left_top_corner(),
            tex_coord: Vector2::new(0.0, 0.0),
            color: colors[0],
        });
        self.push_vertex_raw(Vertex {
            pos: rect.right_top_corner(),
            tex_coord: Vector2::new(1.0, 0.0),
            color: colors[1],
        });
        self.push_vertex_raw(Vertex {
            pos: rect.right_bottom_corner(),
            tex_coord: Vector2::new(1.0, 1.0),
            color: colors[2],
        });
        self.push_vertex_raw(Vertex {
            pos: rect.left_bottom_corner(),
            tex_coord: Vector2::new(0.0, 1.0),
            color: colors[3],
        });

        self.push_triangle(index, index + 1, index + 2);
        self.push_triangle(index, index + 2, index + 3);
    }

    fn push_circle_filled(
        &mut self,
        origin: Vector2<f32>,
        radius: f32,
        segments: usize,
        color: Color,
    ) {
        if segments >= 3 {
            let center_index = self.last_vertex_index();

            self.push_vertex_raw(Vertex {
                pos: origin,
                tex_coord: Vector2::default(),
                color,
            });

            let two_pi = 2.0 * std::f32::consts::PI;
            let delta_angle = two_pi / (segments as f32);
            let mut angle: f32 = 0.0;
            for _ in 0..segments {
                let x = origin.x + radius * angle.cos();
                let y = origin.y + radius * angle.sin();
                self.push_vertex_raw(Vertex {
                    pos: Vector2::new(x, y),
                    tex_coord: Vector2::default(),
                    color,
                });
                angle += delta_angle;
            }

            let first_vertex = center_index + 1;
            for segment in 0..segments {
                self.push_triangle(
                    center_index,
                    first_vertex + segment as u32,
                    first_vertex + (segment as u32 + 1) % segments as u32,
                );
            }
        }
    }

    fn push_circle(
        &mut self,
        center: Vector2<f32>,
        radius: f32,
        subdivisions: usize,
        thickness: f32,
    ) {
        let start_vertex = self.last_vertex_index();
        let d = std::f32::consts::TAU / subdivisions as f32;

        let half_thickness = thickness * 0.5;

        let mut angle = 0.0;
        while angle < std::f32::consts::TAU {
            let r = Vector2::new(angle.cos(), angle.sin());

            let p0 = center + r.scale(radius - half_thickness);
            self.push_vertex(p0, Default::default());

            let p1 = center + r.scale(radius + half_thickness);
            self.push_vertex(p1, Default::default());

            angle += d;
        }
        let last_vertex_index = self.last_vertex_index();

        self.connect_as_line(start_vertex, last_vertex_index, true)
    }

    fn connect_as_line(&mut self, from: u32, to: u32, closed: bool) {
        if closed {
            let count = to - from;
            for i in (0..count).step_by(2) {
                let i0 = from + i % count;
                let i1 = from + (i + 1) % count;
                let i2 = from + (i + 2) % count;
                let i3 = from + (i + 3) % count;
                self.push_triangle(i0, i1, i2);
                self.push_triangle(i1, i3, i2);
            }
        } else {
            for i in (from..to.saturating_sub(4)).step_by(2) {
                let i0 = i;
                let i1 = i + 1;
                let i2 = i + 2;
                let i3 = i + 3;
                self.push_triangle(i0, i1, i2);
                self.push_triangle(i1, i3, i2);
            }
        }
    }

    fn push_arc(
        &mut self,
        center: Vector2<f32>,
        radius: f32,
        angles: Range<f32>,
        subdivisions: usize,
        thickness: f32,
    ) {
        let start_vertex = self.last_vertex_index();
        self.push_arc_path_with_thickness(center, radius, angles, subdivisions, thickness);
        let last_vertex_index = self.last_vertex_index();

        self.connect_as_line(start_vertex, last_vertex_index, false)
    }

    fn push_arc_path_with_thickness(
        &mut self,
        center: Vector2<f32>,
        radius: f32,
        angles: Range<f32>,
        subdivisions: usize,
        thickness: f32,
    ) {
        let mut start_angle = math::wrap_angle(angles.start);
        let mut end_angle = math::wrap_angle(angles.end);

        if start_angle > end_angle {
            std::mem::swap(&mut start_angle, &mut end_angle);
        }

        let d = (end_angle - start_angle) / subdivisions as f32;

        let half_thickness = thickness * 0.5;

        let mut angle = start_angle;
        while angle <= end_angle {
            let r = Vector2::new(angle.cos(), angle.sin());

            let p0 = center + r.scale(radius - half_thickness);
            self.push_vertex(p0, Default::default());

            let p1 = center + r.scale(radius + half_thickness);
            self.push_vertex(p1, Default::default());

            angle += d;
        }
    }

    fn push_arc_path(
        &mut self,
        center: Vector2<f32>,
        radius: f32,
        angles: Range<f32>,
        subdivisions: usize,
    ) {
        let mut start_angle = math::wrap_angle(angles.start);
        let mut end_angle = math::wrap_angle(angles.end);

        if start_angle > end_angle {
            std::mem::swap(&mut start_angle, &mut end_angle);
        }

        let d = (end_angle - start_angle) / subdivisions as f32;

        let mut angle = start_angle;
        while angle <= end_angle {
            let p0 = center + Vector2::new(angle.cos() * radius, angle.sin() * radius);

            self.push_vertex(p0, Default::default());

            angle += d;
        }
    }

    fn push_line_path(&mut self, a: Vector2<f32>, b: Vector2<f32>) {
        self.push_vertex(a, Default::default());
        self.push_vertex(b, Default::default());
    }

    fn push_line_path_with_thickness(&mut self, a: Vector2<f32>, b: Vector2<f32>, thickness: f32) {
        let perp = get_line_thickness_vector(a, b, thickness);
        self.push_vertex(a - perp, Vector2::new(0.0, 0.0));
        self.push_vertex(a + perp, Vector2::new(1.0, 1.0));
        self.push_vertex(b - perp, Vector2::new(1.0, 0.0));
        self.push_vertex(b + perp, Vector2::new(0.0, 1.0));
    }

    fn push_rounded_rect_filled(
        &mut self,
        rect: &Rect<f32>,
        mut corner_radius: f32,
        corner_subdivisions: usize,
    ) {
        // Restrict corner radius in available rectangle.
        let min_axis = rect.w().min(rect.h());
        corner_radius = corner_radius.min(min_axis * 0.5);

        let center_index = self.last_vertex_index();
        self.push_vertex(rect.center(), Default::default());

        self.push_line_path(
            Vector2::new(rect.x(), rect.y() + rect.h() - corner_radius),
            Vector2::new(rect.x(), rect.y() + corner_radius),
        );

        self.push_arc_path(
            rect.position + Vector2::repeat(corner_radius),
            corner_radius,
            180.0f32.to_radians()..270.0f32.to_radians(),
            corner_subdivisions,
        );

        self.push_line_path(
            Vector2::new(rect.x() + corner_radius, rect.y()),
            Vector2::new(rect.x() + rect.w() - corner_radius, rect.y()),
        );

        self.push_arc_path(
            Vector2::new(
                rect.position.x + rect.w() - corner_radius,
                rect.position.y + corner_radius,
            ),
            corner_radius,
            270.0f32.to_radians()..359.9999f32.to_radians(),
            corner_subdivisions,
        );

        self.push_line_path(
            Vector2::new(rect.x() + rect.w(), rect.y() + corner_radius),
            Vector2::new(rect.x() + rect.w(), rect.y() + rect.h() - corner_radius),
        );

        self.push_arc_path(
            Vector2::new(
                rect.position.x + rect.w() - corner_radius,
                rect.position.y + rect.h() - corner_radius,
            ),
            corner_radius,
            0.0f32.to_radians()..90.0f32.to_radians(),
            corner_subdivisions,
        );

        self.push_line_path(
            Vector2::new(rect.x() + rect.w() - corner_radius, rect.y() + rect.h()),
            Vector2::new(rect.x() + corner_radius, rect.y() + rect.h()),
        );

        self.push_arc_path(
            Vector2::new(
                rect.position.x + corner_radius,
                rect.position.y + rect.h() - corner_radius,
            ),
            corner_radius,
            90.0f32.to_radians()..180.0f32.to_radians(),
            corner_subdivisions,
        );

        // Connect all vertices.
        let first_index = center_index + 1;
        let last_vertex_index = self.last_vertex_index().saturating_sub(1);
        for i in first_index..last_vertex_index {
            let next = i + 1;
            self.push_triangle(i, next, center_index)
        }

        self.push_triangle(last_vertex_index, first_index, center_index);
    }

    fn push_rounded_rect(
        &mut self,
        rect: &Rect<f32>,
        thickness: f32,
        mut corner_radius: f32,
        corner_subdivisions: usize,
    ) {
        // Restrict corner radius in available rectangle.
        let min_axis = rect.w().min(rect.h());
        corner_radius = corner_radius.min(min_axis * 0.5);

        let half_thickness = thickness * 0.5;

        let start_index = self.last_vertex_index();

        self.push_line_path_with_thickness(
            Vector2::new(
                rect.x() + half_thickness,
                rect.y() + rect.h() - thickness - corner_radius,
            ),
            Vector2::new(
                rect.x() + half_thickness,
                rect.y() + thickness + corner_radius,
            ),
            thickness,
        );

        self.push_arc_path_with_thickness(
            rect.position + Vector2::repeat(corner_radius + half_thickness),
            corner_radius,
            180.0f32.to_radians()..270.0f32.to_radians(),
            corner_subdivisions,
            thickness,
        );

        self.push_line_path_with_thickness(
            Vector2::new(
                rect.x() + corner_radius + half_thickness,
                rect.y() + half_thickness,
            ),
            Vector2::new(
                rect.x() + rect.w() - corner_radius - half_thickness,
                rect.y() + half_thickness,
            ),
            thickness,
        );

        self.push_arc_path_with_thickness(
            Vector2::new(
                rect.position.x + rect.w() - corner_radius - half_thickness,
                rect.position.y + corner_radius + half_thickness,
            ),
            corner_radius,
            270.0f32.to_radians()..359.9999f32.to_radians(),
            corner_subdivisions,
            thickness,
        );

        self.push_line_path_with_thickness(
            Vector2::new(
                rect.x() + rect.w() - half_thickness,
                rect.y() + thickness + corner_radius,
            ),
            Vector2::new(
                rect.x() + rect.w() - half_thickness,
                rect.y() + rect.h() - thickness - corner_radius,
            ),
            thickness,
        );

        self.push_arc_path_with_thickness(
            Vector2::new(
                rect.position.x + rect.w() - corner_radius - half_thickness,
                rect.position.y + rect.h() - corner_radius - half_thickness,
            ),
            corner_radius,
            0.0f32.to_radians()..90.0f32.to_radians(),
            corner_subdivisions,
            thickness,
        );

        self.push_line_path_with_thickness(
            Vector2::new(
                rect.x() + rect.w() - corner_radius - half_thickness,
                rect.y() + rect.h() - half_thickness,
            ),
            Vector2::new(
                rect.x() + corner_radius + half_thickness,
                rect.y() + rect.h() - half_thickness,
            ),
            thickness,
        );

        self.push_arc_path_with_thickness(
            Vector2::new(
                rect.position.x + corner_radius + half_thickness,
                rect.position.y + rect.h() - corner_radius - half_thickness,
            ),
            corner_radius,
            90.0f32.to_radians()..180.0f32.to_radians(),
            corner_subdivisions,
            thickness,
        );

        let last_vertex_index = self.last_vertex_index();
        self.connect_as_line(start_index, last_vertex_index, true);
    }

    fn push_bezier(
        &mut self,
        p0: Vector2<f32>,
        p1: Vector2<f32>,
        p2: Vector2<f32>,
        p3: Vector2<f32>,
        subdivisions: usize,
        thickness: f32,
    ) {
        fn cubic_bezier(
            p0: Vector2<f32>,
            p1: Vector2<f32>,
            p2: Vector2<f32>,
            p3: Vector2<f32>,
            t: f32,
        ) -> Vector2<f32> {
            p0.scale((1.0 - t).powi(3))
                + p1.scale(3.0 * t * (1.0 - t).powi(2))
                + p2.scale(3.0 * t.powi(2) * (1.0 - t))
                + p3.scale(t.powi(3))
        }

        let mut prev = cubic_bezier(p0, p1, p2, p3, 0.0);
        for i in 0..subdivisions {
            let t = (i + 1) as f32 / subdivisions as f32;
            let next = cubic_bezier(p0, p1, p2, p3, t);
            // TODO: This could give gaps between segments on sharp turns, it should be either patched
            // or be continuous line instead of separate segments.
            self.push_line(prev, next, thickness);
            prev = next;
        }
    }

    fn push_grid(&mut self, zoom: f32, cell_size: Vector2<f32>, grid_bounds: Rect<f32>) {
        let mut local_left_bottom = grid_bounds.left_top_corner();
        local_left_bottom.x = round_to_step(local_left_bottom.x, cell_size.x);
        local_left_bottom.y = round_to_step(local_left_bottom.y, cell_size.y);

        let mut local_right_top = grid_bounds.right_bottom_corner();
        local_right_top.x = round_to_step(local_right_top.x, cell_size.x);
        local_right_top.y = round_to_step(local_right_top.y, cell_size.y);

        let w = (local_right_top.x - local_left_bottom.x).abs();
        let h = (local_right_top.y - local_left_bottom.y).abs();

        let nw = ((w / cell_size.x).ceil()) as usize;
        let nh = ((h / cell_size.y).ceil()) as usize;

        for ny in 0..=nh {
            let k = ny as f32 / (nh) as f32;
            let y = local_left_bottom.y + k * h;
            self.push_line(
                Vector2::new(local_left_bottom.x - cell_size.x, y),
                Vector2::new(local_right_top.x + cell_size.x, y),
                1.0 / zoom,
            );
        }

        for nx in 0..=nw {
            let k = nx as f32 / (nw) as f32;
            let x = local_left_bottom.x + k * w;
            self.push_line(
                Vector2::new(x, local_left_bottom.y - cell_size.y),
                Vector2::new(x, local_right_top.y + cell_size.y),
                1.0 / zoom,
            );
        }
    }
}

#[derive(Clone, Debug)]
pub struct TransformStack {
    transform: Matrix3<f32>,
    stack: Vec<Matrix3<f32>>,
}

impl Default for TransformStack {
    fn default() -> Self {
        Self {
            transform: Matrix3::identity(),
            stack: vec![],
        }
    }
}

impl TransformStack {
    #[inline]
    pub fn push(&mut self, matrix: Matrix3<f32>) {
        self.stack
            .push(std::mem::replace(&mut self.transform, matrix));
    }

    /// Returns the transformation matrix that will be used to transform vertices of drawing context.
    #[inline]
    pub fn transform(&self) -> &Matrix3<f32> {
        &self.transform
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.stack.len()
    }

    pub fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }

    pub fn content(&self) -> Vec<Matrix3<f32>> {
        self.stack.clone()
    }

    #[inline]
    pub fn pop(&mut self) {
        if let Some(top) = self.stack.pop() {
            self.transform = top;
        } else {
            Log::err("TransformStack pop failure.")
        }
    }
}

#[derive(Debug, Clone)]
pub struct DrawingContext {
    vertex_buffer: Vec<Vertex>,
    triangle_buffer: Vec<TriangleDefinition>,
    command_buffer: Vec<Command>,
    pub transform_stack: TransformStack,
    opacity_stack: Vec<f32>,
    triangles_to_commit: usize,
    pub style: StyleResource,
    /// Amount of time (in seconds) that passed from creation of the engine. Keep in mind, that
    /// this value is **not** guaranteed to match real time. A user can change delta time with
    /// which the engine "ticks" and this delta time affects elapsed time.
    pub elapsed_time: f32,
}

fn get_line_thickness_vector(a: Vector2<f32>, b: Vector2<f32>, thickness: f32) -> Vector2<f32> {
    if let Some(dir) = (b - a).try_normalize(f32::EPSILON) {
        Vector2::new(dir.y, -dir.x).scale(thickness * 0.5)
    } else {
        Vector2::default()
    }
}

impl Draw for DrawingContext {
    #[inline(always)]
    fn push_vertex_raw(&mut self, mut vertex: Vertex) {
        vertex.pos = self
            .transform_stack
            .transform
            .transform_point(&Point2::from(vertex.pos))
            .coords;

        self.vertex_buffer.push(vertex);
    }

    #[inline(always)]
    fn push_triangle(&mut self, a: u32, b: u32, c: u32) {
        self.triangle_buffer.push(TriangleDefinition([a, b, c]));
        self.triangles_to_commit += 1;
    }

    #[inline(always)]
    fn last_vertex_index(&self) -> u32 {
        self.vertex_buffer.len() as u32
    }
}

impl DrawingContext {
    pub fn new(style: StyleResource) -> DrawingContext {
        DrawingContext {
            vertex_buffer: Vec::new(),
            triangle_buffer: Vec::new(),
            command_buffer: Vec::new(),
            triangles_to_commit: 0,
            opacity_stack: vec![1.0],
            transform_stack: Default::default(),
            style,
            elapsed_time: 0.0,
        }
    }

    #[inline]
    pub fn clear(&mut self) {
        self.vertex_buffer.clear();
        self.triangle_buffer.clear();
        self.command_buffer.clear();
        self.opacity_stack.clear();
        self.opacity_stack.push(1.0);
        self.triangles_to_commit = 0;
    }

    #[inline]
    pub fn get_vertices(&self) -> &[Vertex] {
        self.vertex_buffer.as_slice()
    }

    #[inline]
    pub fn get_triangles(&self) -> &[TriangleDefinition] {
        self.triangle_buffer.as_slice()
    }

    #[inline]
    pub fn get_commands(&self) -> &Vec<Command> {
        &self.command_buffer
    }

    pub fn push_opacity(&mut self, opacity: f32) {
        self.opacity_stack.push(opacity);
    }

    pub fn pop_opacity(&mut self) {
        self.opacity_stack.pop().unwrap();
    }

    pub fn triangle_points(
        &self,
        triangle: &TriangleDefinition,
    ) -> Option<(&Vertex, &Vertex, &Vertex)> {
        let a = self.vertex_buffer.get(triangle[0] as usize)?;
        let b = self.vertex_buffer.get(triangle[1] as usize)?;
        let c = self.vertex_buffer.get(triangle[2] as usize)?;
        Some((a, b, c))
    }

    pub fn is_command_contains_point(&self, command: &Command, pos: Vector2<f32>) -> bool {
        for i in command.triangles.clone() {
            if let Some(triangle) = self.triangle_buffer.get(i) {
                if let Some((va, vb, vc)) = self.triangle_points(triangle) {
                    if math::is_point_inside_2d_triangle(pos, va.pos, vb.pos, vc.pos) {
                        return true;
                    }
                }
            }
        }

        false
    }

    fn pending_range(&self) -> Range<usize> {
        if self.triangle_buffer.is_empty() {
            0..self.triangles_to_commit
        } else {
            (self.triangle_buffer.len() - self.triangles_to_commit)..self.triangle_buffer.len()
        }
    }

    fn bounds_of(&self, range: Range<usize>) -> Rect<f32> {
        let mut bounds = Rect::new(f32::MAX, f32::MAX, 0.0, 0.0);
        for i in range {
            for &k in self.triangle_buffer[i].as_ref() {
                bounds.push(self.vertex_buffer[k as usize].pos);
            }
        }
        bounds
    }

    pub fn commit(
        &mut self,
        clip_bounds: Rect<f32>,
        brush: Brush,
        texture: CommandTexture,
        clipping_geometry: Option<ClippingGeometry>,
    ) {
        if self.triangles_to_commit > 0 {
            let triangles = self.pending_range();
            let bounds = self.bounds_of(triangles.clone());

            let opacity = *self.opacity_stack.last().unwrap();
            self.command_buffer.push(Command {
                clip_bounds,
                bounds,
                brush,
                texture,
                triangles,
                opacity,
                clipping_geometry,
            });
            self.triangles_to_commit = 0;
        }
    }

    pub fn draw_text(
        &mut self,
        clip_bounds: Rect<f32>,
        position: Vector2<f32>,
        formatted_text: &FormattedText,
    ) {
        let font = formatted_text.get_font();

        #[inline(always)]
        fn draw(
            formatted_text: &FormattedText,
            ctx: &mut DrawingContext,
            clip_bounds: Rect<f32>,
            position: Vector2<f32>,
            dilation: f32,
            offset: Vector2<f32>,
            brush: Brush,
            font: &FontResource,
        ) {
            let Some(mut current_page_index) = formatted_text
                .get_glyphs()
                .first()
                .map(|g| g.atlas_page_index)
            else {
                return;
            };

            for element in formatted_text.get_glyphs() {
                // If we've switched to another atlas page, commit the text and start a new batch.
                if current_page_index != element.atlas_page_index {
                    ctx.commit(
                        clip_bounds,
                        brush.clone(),
                        CommandTexture::Font {
                            font: font.clone(),
                            page_index: current_page_index,
                            // Use font size scaled by super sampling scaling to pick correct atlas
                            // page.
                            height: FontHeight::from(formatted_text.super_sampled_font_size()),
                        },
                        None,
                    );
                    current_page_index = element.atlas_page_index;
                }

                let bounds = element.bounds;

                let final_bounds = Rect::new(
                    position.x + bounds.x() + offset.x,
                    position.y + bounds.y() + offset.y,
                    bounds.w(),
                    bounds.h(),
                )
                .inflate(dilation, dilation);

                ctx.push_rect_filled(&final_bounds, Some(&element.tex_coords));
            }

            // Commit the rest.
            ctx.commit(
                clip_bounds,
                brush,
                CommandTexture::Font {
                    font: font.clone(),
                    page_index: current_page_index,
                    // Use font size scaled by super sampling scaling to pick correct atlas
                    // page.
                    height: FontHeight::from(formatted_text.super_sampled_font_size()),
                },
                None,
            );
        }

        // Draw shadow, if any.
        if *formatted_text.shadow {
            draw(
                formatted_text,
                self,
                clip_bounds,
                position,
                *formatted_text.shadow_dilation,
                *formatted_text.shadow_offset,
                (*formatted_text.shadow_brush).clone(),
                &font,
            );
        }

        draw(
            formatted_text,
            self,
            clip_bounds,
            position,
            0.0,
            Default::default(),
            formatted_text.brush(),
            &font,
        );
    }
}