]> git.lizzy.rs Git - nothing.git/blob - src/math/triangle.c
(#647) fix max_int64
[nothing.git] / src / math / triangle.c
1 #include <math.h>
2 #include <stdio.h>
3
4 #include "math/pi.h"
5 #include "math/rand.h"
6 #include "triangle.h"
7
8 Triangle triangle(Point p1, Point p2, Point p3)
9 {
10     const Triangle result = {
11         .p1 = p1,
12         .p2 = p2,
13         .p3 = p3
14     };
15
16     return result;
17 }
18
19 Triangle equilateral_triangle(void)
20 {
21     const float d = PI_2 / 3.0f;
22
23     const Triangle result = {
24         .p1 = vec(cosf(0.0f), sinf(0.0f)),
25         .p2 = vec(cosf(d), sinf(d)),
26         .p3 = vec(cosf(2.0f * d), sinf(2.0f * d))
27     };
28
29     return result;
30 }
31
32 Triangle random_triangle(float radius)
33 {
34     return triangle(
35         vec_from_polar(rand_float(2 * PI), rand_float(radius)),
36         vec_from_polar(rand_float(2 * PI), rand_float(radius)),
37         vec_from_polar(rand_float(2 * PI), rand_float(radius)));
38 }
39
40 static void swap_points(Point *p1, Point *p2)
41 {
42     Point t = *p1;
43     *p1 = *p2;
44     *p2 = t;
45 }
46
47 Triangle triangle_sorted_by_y(Triangle t)
48 {
49     if (t.p1.y > t.p2.y) { swap_points(&t.p1, &t.p2); }
50     if (t.p2.y > t.p3.y) { swap_points(&t.p2, &t.p3); }
51     if (t.p1.y > t.p2.y) { swap_points(&t.p1, &t.p2); }
52
53     return t;
54 }
55
56 void rect_as_triangles(Rect rect, Triangle triangles[2])
57 {
58     Triangle t1 = {
59         .p1 = { .x = rect.x, .y = rect.y },
60         .p2 = { .x = rect.x + rect.w, .y = rect.y },
61         .p3 = { .x = rect.x, .y = rect.y + rect.h }
62     };
63
64     Triangle t2 = {
65         .p1 = { .x = rect.x + rect.w, .y = rect.y },
66         .p2 = { .x = rect.x, .y = rect.y + rect.h },
67         .p3 = { .x = rect.x + rect.w, .y = rect.y + rect.h }
68     };
69
70     triangles[0] = t1;
71     triangles[1] = t2;
72 }
73
74 Triangle triangle_mat3x3_product(Triangle t, mat3x3 m)
75 {
76     Triangle t1 = {
77         .p1 = point_mat3x3_product(t.p1, m),
78         .p2 = point_mat3x3_product(t.p2, m),
79         .p3 = point_mat3x3_product(t.p3, m)
80     };
81
82     return t1;
83 }