]> pd.if.org Git - isea/blob - hfuncs.c
Initial checkin.
[isea] / hfuncs.c
1 #ifndef ISEA_STATIC
2 #define ISEA_STATIC
3 #endif
4
5 struct hex {
6         int iso;
7         int x, y, z;
8 };
9
10 /* y *must* be positive down as the xy /iso conversion assumes this */
11 ISEA_STATIC
12 int hex_xy(struct hex *h) {
13         if (!h->iso) return 1;
14         if (h->x >= 0) {
15                 h->y = -h->y - (h->x+1)/2;
16         } else {
17                 /* need to round toward -inf, not toward zero, so x-1 */
18                 h->y = -h->y - h->x/2;
19         }
20         h->iso = 0;
21
22         return 1;
23 }
24
25 ISEA_STATIC
26 int hex_iso(struct hex *h) {
27         if (h->iso) return 1;
28
29         if (h->x >= 0) {
30                 h->y = (-h->y - (h->x+1)/2);
31         } else {
32                 /* need to round toward -inf, not toward zero, so x-1 */
33                 h->y = (-h->y - (h->x)/2);
34         }
35
36         h->z = -h->x - h->y;
37         h->iso = 1;
38         return 1;
39 }
40
41 ISEA_STATIC
42 int hexbin2(int horizontal, double width, double x, double y,
43                 int *i, int *j) {
44         double z, rx, ry, rz;
45         double abs_dx, abs_dy, abs_dz;
46         int ix, iy, iz, s;
47         struct hex h;
48
49         x = x / cos(30 * M_PI / 180.0); /* rotated X coord */
50         y = y - x / 2.0; /* adjustment for rotated X */
51
52         /* adjust for actual hexwidth */
53         x /= width;
54         y /= width;
55
56         z = -x - y;
57
58         ix = rx = floor(x + 0.5);
59         iy = ry = floor(y + 0.5);
60         iz = rz = floor(z + 0.5);
61
62         s = ix + iy + iz;
63
64         if (s) {
65                 abs_dx = fabs(rx - x);
66                 abs_dy = fabs(ry - y);
67                 abs_dz = fabs(rz - z);
68
69                 if (abs_dx >= abs_dy && abs_dx >= abs_dz) {
70                         ix -= s;
71                 } else if (abs_dy >= abs_dx && abs_dy >= abs_dz) {
72                         iy -= s;
73                 } else {
74                         iz -= s;
75                 }
76         }
77         h.x = ix;
78         h.y = iy;
79         h.z = iz;
80         h.iso = 1;
81
82         hex_xy(&h);
83         *i = h.x;
84         *j = h.y;
85         return ix * 100 + iy;
86 }