-
Notifications
You must be signed in to change notification settings - Fork 0
/
tg.c
14281 lines (13353 loc) · 463 KB
/
tg.c
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
// https://github.com/tidwall/tg
//
// Copyright 2023 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
#include <math.h>
#include <float.h>
#include <stdarg.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "tg.h"
/******************************************************************************
Implementation Notes:
- Right-hand-rule is not required for polygons.
- The "properties" GeoJSON field is not required for Features.
- All polygons with at least 32 points are indexed automatically (TG_NATURAL).
Developer notes:
- This tg.c source file includes the entire tg library. (amalgamation)
- All dependencies are embedded between the BEGIN/END tags.
- Do not edit a dependency directly in this file. Instead edit the file in
the deps directory and then run deps/embed.sh to replace out its code in
this file.
*******************************************************************************/
enum base {
BASE_POINT = 1, // tg_point
BASE_LINE = 2, // tg_line
BASE_RING = 3, // tg_ring
BASE_POLY = 4, // tg_poly
BASE_GEOM = 5, // tg_geom
};
enum flags {
HAS_Z = 1<<0, // Geometry has additional Z coordinates
HAS_M = 1<<1, // Geometry has additional M coordinates
IS_ERROR = 1<<2, // Geometry is a parse error. Falls back to POINT
IS_EMPTY = 1<<3, // Same as a GeoJSON null object (empty coords)
IS_FEATURE = 1<<4, // GeoJSON. Geometry is Feature
IS_FEATURE_COL = 1<<5, // GeoJSON. GeometryGollection is FeatureCollection
HAS_NULL_PROPS = 1<<6, // GeoJSON. 'Feature' with 'properties'=null
IS_UNLOCATED = 1<<7, // GeoJSON. 'Feature' with 'geometry'=null
};
// Optionally use non-atomic reference counting when TG_NOATOMICS is defined.
#ifdef TG_NOATOMICS
typedef int rc_t;
static int rc_sub(rc_t *rc) {
int fetch = *rc;
(*rc)--;
return fetch;
}
static int rc_add(rc_t *rc) {
int fetch = *rc;
(*rc)++;
return fetch;
}
#else
#include <stdatomic.h>
typedef atomic_int rc_t;
static int rc_sub(rc_t *rc) {
return atomic_fetch_sub(rc, 1);
}
static int rc_add(rc_t *rc) {
return atomic_fetch_add(rc, 1);
}
#endif
struct head {
rc_t rc;
enum base base:8;
enum tg_geom_type type:8;
enum flags flags:8;
};
/// A ring is series of tg_segment which creates a shape that does not
/// self-intersect and is fully closed, where the start and end points are the
/// exact same value.
///
/// **Creating**
///
/// To create a new ring use the tg_ring_new() function.
///
/// ```
/// struct tg_ring *ring = tg_ring_new(points, npoints);
/// ```
///
/// **Upcasting**
///
/// A tg_ring can always be safely upcasted to a tg_poly or tg_geom; allowing
/// it to use any tg_poly_*() or tg_geom_*() function.
///
/// ```
/// struct tg_poly *poly = (struct tg_poly*)ring; // Cast to a tg_poly
/// struct tg_geom *geom = (struct tg_geom*)ring; // Cast to a tg_geom
/// ```
/// @see RingFuncs
/// @see PolyFuncs
struct tg_ring {
struct head head;
bool closed;
bool clockwise;
bool convex;
double area;
int npoints;
int nsegs;
struct tg_rect rect;
struct index *index;
struct ystripes *ystripes;
struct tg_point points[];
};
/// A line is a series of tg_segment that make up a linestring.
///
/// **Creating**
///
/// To create a new line use the tg_line_new() function.
///
/// ```
/// struct tg_line *line = tg_line_new(points, npoints);
/// ```
///
/// **Upcasting**
///
/// A tg_line can always be safely upcasted to a tg_geom; allowing
/// it to use any tg_geom_*() function.
///
/// ```
/// struct tg_geom *geom = (struct tg_geom*)line; // Cast to a tg_geom
/// ```
///
/// @see LineFuncs
struct tg_line { int _; };
/// A polygon consists of one exterior ring and zero or more holes.
///
/// **Creating**
///
/// To create a new polygon use the tg_poly_new() function.
///
/// ```
/// struct tg_poly *poly = tg_poly_new(exterior, holes, nholes);
/// ```
///
/// **Upcasting**
///
/// A tg_poly can always be safely upcasted to a tg_geom; allowing
/// it to use any tg_geom_*() function.
///
/// ```
/// struct tg_geom *geom = (struct tg_geom*)poly; // Cast to a tg_geom
/// ```
///
/// @see PolyFuncs
struct tg_poly {
struct head head;
struct tg_ring *exterior;
int nholes;
struct tg_ring **holes;
};
struct multi {
struct tg_geom **geoms;
int ngeoms;
struct tg_rect rect; // unioned rect child geometries
struct index *index; // geometry index, or NULL if not indexed
int *ixgeoms; // indexed geometries, or NULL if not indexed
};
/// A geometry is the common generic type that can represent a Point,
/// LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, or
/// GeometryCollection.
///
/// For geometries that are derived from GeoJSON, they may have addtional
/// attributes such as being a Feature or a FeatureCollection; or include
/// extra json fields.
///
/// **Creating**
///
/// To create a new geometry use one of the @ref GeometryConstructors or
/// @ref GeometryParsing functions.
///
/// ```
/// struct tg_geom *geom = tg_geom_new_point(point);
/// struct tg_geom *geom = tg_geom_new_polygon(poly);
/// struct tg_geom *geom = tg_parse_geojson(geojson);
/// ```
///
/// **Upcasting**
///
/// Other types, specifically tg_line, tg_ring, and tg_poly, can be safely
/// upcasted to a tg_geom; allowing them to use any tg_geom_*()
/// function.
///
/// ```
/// struct tg_geom *geom1 = (struct tg_geom*)line; // Cast to a LineString
/// struct tg_geom *geom2 = (struct tg_geom*)ring; // Cast to a Polygon
/// struct tg_geom *geom3 = (struct tg_geom*)poly; // Cast to a Polygon
/// ```
///
/// @see GeometryConstructors
/// @see GeometryAccessors
/// @see GeometryPredicates
/// @see GeometryParsing
/// @see GeometryWriting
struct tg_geom {
struct head head;
union {
struct tg_point point;
struct tg_line *line;
struct tg_poly *poly;
struct multi *multi;
};
union {
struct { // TG_POINT
double z;
double m;
};
struct { // !TG_POINT
double *coords; // extra dimensinal coordinates
int ncoords;
};
};
union {
char *xjson; // extra json fields, such as "id", "properties", etc.
char *error; // an error message, when flag IS_ERROR
};
};
struct boxed_point {
struct head head;
struct tg_point point;
};
#define todo(msg) { \
fprintf(stderr, "todo: %s, line: %d\n", (msg), __LINE__); \
exit(1); \
}
// private methods
bool tg_ring_empty(const struct tg_ring *ring);
bool tg_line_empty(const struct tg_line *line);
bool tg_poly_empty(const struct tg_poly *poly);
void tg_rect_search(struct tg_rect rect, struct tg_rect target,
bool(*iter)(struct tg_segment seg, int index, void *udata),
void *udata);
void tg_ring_search(const struct tg_ring *ring, struct tg_rect rect,
bool(*iter)(struct tg_segment seg, int index, void *udata),
void *udata);
void tg_line_search(const struct tg_line *ring, struct tg_rect rect,
bool(*iter)(struct tg_segment seg, int index, void *udata),
void *udata);
void tg_geom_foreach(const struct tg_geom *geom,
bool(*iter)(const struct tg_geom *geom, void *udata), void *udata);
double tg_ring_polsby_popper_score(const struct tg_ring *ring);
double tg_line_polsby_popper_score(const struct tg_line *line);
int tg_rect_num_points(struct tg_rect rect);
struct tg_point tg_rect_point_at(struct tg_rect rect, int index);
int tg_rect_num_segments(struct tg_rect rect);
struct tg_segment tg_rect_segment_at(struct tg_rect rect, int index);
int tg_geom_de9im_dims(const struct tg_geom *geom);
bool tg_point_covers_point(struct tg_point a, struct tg_point b);
bool tg_point_covers_rect(struct tg_point a, struct tg_rect b);
bool tg_point_covers_line(struct tg_point a, const struct tg_line *b);
bool tg_point_covers_poly(struct tg_point a, const struct tg_poly *b);
bool tg_geom_covers_point(const struct tg_geom *a, struct tg_point b);
bool tg_geom_covers_xy(const struct tg_geom *a, double x, double y);
bool tg_segment_covers_segment(struct tg_segment a, struct tg_segment b);
bool tg_segment_covers_point(struct tg_segment a, struct tg_point b);
bool tg_segment_covers_rect(struct tg_segment a, struct tg_rect b);
bool tg_rect_covers_point(struct tg_rect a, struct tg_point b);
bool tg_rect_covers_xy(struct tg_rect a, double x, double y);
bool tg_rect_covers_rect(struct tg_rect a, struct tg_rect b);
bool tg_rect_covers_line(struct tg_rect a, const struct tg_line *b);
bool tg_rect_covers_poly(struct tg_rect a, const struct tg_poly *b);
bool tg_line_covers_point(const struct tg_line *a, struct tg_point b);
bool tg_line_covers_rect(const struct tg_line *a, struct tg_rect b);
bool tg_line_covers_line(const struct tg_line *a, const struct tg_line *b);
bool tg_line_covers_poly(const struct tg_line *a, const struct tg_poly *b);
bool tg_line_intersects_point(const struct tg_line *a, struct tg_point b);
bool tg_line_intersects_rect(const struct tg_line *a, struct tg_rect b);
bool tg_line_intersects_line(const struct tg_line *a, const struct tg_line *b);
bool tg_line_intersects_poly(const struct tg_line *a, const struct tg_poly *b);
bool tg_point_intersects_point(struct tg_point a, struct tg_point b);
bool tg_point_intersects_rect(struct tg_point a, struct tg_rect b);
bool tg_point_intersects_line(struct tg_point a, const struct tg_line *b);
bool tg_point_intersects_poly(struct tg_point a, const struct tg_poly *b);
bool tg_rect_intersects_rect(struct tg_rect a, struct tg_rect b);
bool tg_rect_intersects_line(struct tg_rect a, const struct tg_line *b);
bool tg_rect_intersects_poly(struct tg_rect a, const struct tg_poly *b);
bool tg_segment_intersects_segment(struct tg_segment a, struct tg_segment b);
bool tg_poly_covers_xy(const struct tg_poly *a, double x, double y);
bool tg_poly_touches_line(const struct tg_poly *a, const struct tg_line *b);
bool tg_poly_coveredby_poly(const struct tg_poly *a, const struct tg_poly *b);
bool tg_poly_covers_point(const struct tg_poly *a, struct tg_point b);
bool tg_poly_covers_rect(const struct tg_poly *a, struct tg_rect b);
bool tg_poly_covers_line(const struct tg_poly *a, const struct tg_line *b);
bool tg_poly_covers_poly(const struct tg_poly *a, const struct tg_poly *b);
bool tg_poly_intersects_point(const struct tg_poly *a, struct tg_point b);
bool tg_poly_intersects_rect(const struct tg_poly *a, struct tg_rect b);
bool tg_poly_intersects_line(const struct tg_poly *a, const struct tg_line *b);
bool tg_poly_intersects_poly(const struct tg_poly *a, const struct tg_poly *b);
bool tg_geom_intersects_point(const struct tg_geom *a, struct tg_point b);
static_assert(sizeof(int) == 4 || sizeof(int) == 8, "invalid int size");
// Function attribute for noinline.
#if defined(__GNUC__)
#define __attr_noinline __attribute__((noinline))
#elif defined(_MSC_VER)
#define __attr_noinline __declspec(noinline)
#else
#define __attr_noinline
#endif
// Fast floating-point min and max for gcc and clang on arm64 and x64.
#if defined(__GNUC__) && defined(__aarch64__)
// arm64 already uses branchless operations for fmin and fmax
static inline double fmin0(double x, double y) {
return fmin(x, y);
}
static inline double fmax0(double x, double y) {
return fmax(x, y);
}
static inline float fminf0(float x, float y) {
return fminf(x, y);
}
static inline float fmaxf0(float x, float y) {
return fmaxf(x, y);
}
#elif defined(__GNUC__) && defined(__x86_64__)
// gcc/amd64 sometimes uses branching with fmin/fmax.
// This code use single a asm op instead.
// https://gcc.gnu.org/bugzilla//show_bug.cgi?id=94497
#pragma GCC diagnostic push
#ifdef __clang__
#pragma clang diagnostic ignored "-Wlanguage-extension-token"
#endif
static inline double fmin0(double x, double y) {
asm("minsd %1, %0" : "+x" (x) : "x" (y));
return x;
}
static inline double fmax0(double x, double y) {
asm("maxsd %1, %0" : "+x" (x) : "x" (y));
return x;
}
static inline float fminf0(float x, float y) {
asm("minss %1, %0" : "+x" (x) : "x" (y));
return x;
}
static inline float fmaxf0(float x, float y) {
asm("maxss %1, %0" : "+x" (x) : "x" (y));
return x;
}
#pragma GCC diagnostic pop
#else
// for everything else, let the compiler figure it out.
static inline double fmin0(double x, double y) {
return x < y ? x : y;
}
static inline double fmax0(double x, double y) {
return x > y ? x : y;
}
static inline float fminf0(double x, float y) {
return x < y ? x : y;
}
static inline float fmaxf0(float x, float y) {
return x > y ? x : y;
}
#endif
static inline double fclamp0(double f, double min, double max) {
return fmin0(fmax0(f, min), max);
}
static bool feq(double x, double y) {
return !((x < y) | (x > y));
}
static bool eq_zero(double x) {
return feq(x, 0);
}
static bool collinear(
double x1, double y1, // point 1
double x2, double y2, // point 2
double x3, double y3 // point 3
) {
bool x1x2 = feq(x1, x2);
bool x1x3 = feq(x1, x3);
bool x2x3 = feq(x2, x3);
bool y1y2 = feq(y1, y2);
bool y1y3 = feq(y1, y3);
bool y2y3 = feq(y2, y3);
if (x1x2) {
return x1x3;
}
if (y1y2) {
return y1y3;
}
if ((x1x2 & y1y2) | (x1x3 & y1y3) | (x2x3 & y2y3)) {
return true;
}
double cx1 = x3 - x1;
double cy1 = y3 - y1;
double cx2 = x2 - x1;
double cy2 = y2 - y1;
double s1 = cx1 * cy2;
double s2 = cy1 * cx2;
// Check if precision was lost.
double s3 = (s1 / cy2) - cx1;
double s4 = (s2 / cx2) - cy1;
if (s3 < 0) {
s1 = nexttoward(s1, -INFINITY);
} else if (s3 > 0) {
s1 = nexttoward(s1, +INFINITY);
}
if (s4 < 0) {
s2 = nexttoward(s2, -INFINITY);
} else if (s4 > 0) {
s2 = nexttoward(s2, +INFINITY);
}
return eq_zero(s1 - s2);
}
static double length(double x1, double y1, double x2, double y2) {
return sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2));
}
#ifndef ludo
#define ludo
#define ludo1(i,f) f; i++;
#define ludo2(i,f) ludo1(i,f); ludo1(i,f);
#define ludo4(i,f) ludo2(i,f); ludo2(i,f);
#define ludo8(i,f) ludo4(i,f); ludo4(i,f);
#define ludo16(i,f) ludo8(i,f); ludo8(i,f);
#define ludo32(i,f) ludo16(i,f); ludo16(i,f);
#define ludo64(i,f) ludo32(i,f); ludo32(i,f);
#define for1(i,n,f) while(i+1<=(n)) { ludo1(i,f); }
#define for2(i,n,f) while(i+2<=(n)) { ludo2(i,f); } for1(i,n,f);
#define for4(i,n,f) while(i+4<=(n)) { ludo4(i,f); } for1(i,n,f);
#define for8(i,n,f) while(i+8<=(n)) { ludo8(i,f); } for1(i,n,f);
#define for16(i,n,f) while(i+16<=(n)) { ludo16(i,f); } for1(i,n,f);
#define for32(i,n,f) while(i+32<=(n)) { ludo32(i,f); } for1(i,n,f);
#define for64(i,n,f) while(i+64<=(n)) { ludo64(i,f); } for1(i,n,f);
#endif
static size_t grow_cap(size_t cap, size_t init_cap) {
return cap == 0 ? init_cap : cap < 1000 ? cap * 2 : cap * 1.25;
}
#define print_segment(s) { \
printf("(%f %f,%f %f)", (s).a.x, (s).a.y, (s).b.x, (s).b.y); \
}
#define print_geom(g) { \
size_t sz = tg_geom_wkt(g, 0, 0); \
char *wkt = tg_malloc(sz+1); \
assert(wkt); \
tg_geom_wkt(g, wkt, sz+1); \
printf("%s\n", wkt); \
free(wkt); \
}
/////////////////////
// global behaviors
/////////////////////
// Global variables shared by all TG functions.
static void *(*_malloc)(size_t) = NULL;
static void *(*_realloc)(void*, size_t) = NULL;
static void (*_free)(void*) = NULL;
static enum tg_index default_index = TG_NATURAL;
static int default_index_spread = 16;
/// Allow for configuring a custom allocator.
///
/// This overrides the built-in malloc, realloc, and free functions for all
/// TG operations.
/// @warning This function, if needed, should be called **only once** at
/// program start up and prior to calling any other tg_*() function.
/// @see GlobalFuncs
void tg_env_set_allocator(
void *(*malloc)(size_t),
void *(*realloc)(void*, size_t),
void (*free)(void*))
{
_malloc = malloc;
_realloc = realloc;
_free = free;
}
void *tg_malloc(size_t nbytes) {
return (_malloc?_malloc:malloc)(nbytes);
}
void *tg_realloc(void *ptr, size_t nbytes) {
return (_realloc?_realloc:realloc)(ptr, nbytes);
}
void tg_free(void *ptr) {
(_free?_free:free)(ptr);
}
/// Set the geometry indexing default.
///
/// This is a global override to the indexing for all yet-to-be created
/// geometries.
/// @warning This function, if needed, should be called **only once** at
/// program start up and prior to calling any other tg_*() function.
/// @see [tg_index](.#tg_index)
/// @see tg_env_set_index()
/// @see GlobalFuncs
void tg_env_set_index(enum tg_index ix) {
switch (ix) {
case TG_NONE:
case TG_NATURAL:
case TG_YSTRIPES:
// only change for none, natural, and ystripes
default_index = ix;
break;
default:
// no change
break;
}
}
/// Get the current geometry indexing default.
/// @see [tg_index](.#tg_index)
/// @see tg_env_set_index()
/// @see GlobalFuncs
enum tg_index tg_env_get_default_index(void) {
return default_index;
}
/// Set the default index spread.
///
/// The "spread" is how many rectangles are grouped together on an indexed
/// level before propagating up to a higher level.
///
/// Default is 16.
///
/// This is a global override to the indexing spread for all yet-to-be created
/// geometries.
/// @warning This function, if needed, should be called **only once** at
/// program start up and prior to calling any other tg_*() function.
/// @see [tg_index](.#tg_index)
/// @see tg_env_set_index()
/// @see <a href="POLYGON_INDEXING.md">About TG indexing</a>
/// @see GlobalFuncs
void tg_env_set_index_spread(int spread) {
// only allow spreads between 2 and 1024
if (spread >= 2 && spread <= 4096) {
default_index_spread = spread;
}
}
int tg_env_get_index_spread(void) {
return default_index_spread;
}
enum tg_index tg_index_with_spread(enum tg_index ix, int spread) {
// Only 16 bits of the tg_index is used.
// first 4 bits is the index. The next 12 is the spread.
if (spread != 0) {
spread = spread < 2 ? 2 : spread > 4096 ? 4096 : spread;
spread--; // ensure range 1-4095 (but will actually be 2-4096)
}
return (ix & 0xF) | (spread << 4);
}
enum tg_index tg_index_extract_spread(enum tg_index ix, int *spread) {
int ixspread = ((unsigned int)(ix >> 4)) & 4095;
if (ixspread > 0) {
ixspread++;
}
if (ixspread == 0) {
ixspread = tg_env_get_index_spread();
}
if (spread) {
*spread = ixspread;
}
return ix & 0xF;
}
////////////////////
// point
////////////////////
static bool pteq(struct tg_point a, struct tg_point b) {
return feq(a.x, b.x) && feq(a.y, b.y);
}
/// Returns the minimum bounding rectangle of a point.
/// @see PointFuncs
struct tg_rect tg_point_rect(struct tg_point point) {
return (struct tg_rect){ .min = point, .max = point };
}
/// Tests whether a point fully contains another point.
/// @see PointFuncs
bool tg_point_covers_point(struct tg_point point, struct tg_point other) {
return pteq(point, other);
}
bool tg_point_contains_point(struct tg_point point, struct tg_point other) {
return pteq(point, other);
}
/// Tests whether a point intersects another point.
/// @see PointFuncs
bool tg_point_intersects_point(struct tg_point a, struct tg_point b) {
return pteq(a, b);
}
bool tg_point_touches_point(struct tg_point a, struct tg_point b) {
// Points do not have boundaries
(void)a; (void)b;
return false;
}
/// Tests whether a point fully contains a rectangle.
/// @see PointFuncs
bool tg_point_covers_rect(struct tg_point point, struct tg_rect rect) {
return pteq(rect.min, point) && pteq(rect.max, point);
}
/// Tests whether a point fully intersects a rectangle.
/// @see PointFuncs
bool tg_point_intersects_rect(struct tg_point point, struct tg_rect rect) {
return tg_rect_covers_point(rect, point);
}
/// Tests whether a point fully contains a line.
/// @see PointFuncs
bool tg_point_covers_line(struct tg_point point, const struct tg_line *line) {
return !tg_line_empty(line) &&
tg_point_covers_rect(point, tg_line_rect(line));
}
bool tg_point_contains_line(struct tg_point point, const struct tg_line *line) {
return !tg_line_empty(line) &&
tg_point_covers_rect(point, tg_line_rect(line));
}
/// Tests whether a point intersects a line.
/// @see PointFuncs
bool tg_point_intersects_line(struct tg_point point,
const struct tg_line *line)
{
return tg_line_intersects_point(line, point);
}
bool tg_point_touches_line(struct tg_point point, const struct tg_line *line) {
int nsegs = tg_line_num_segments(line);
if (nsegs == 0) {
return false;
}
struct tg_segment s0 = tg_line_segment_at(line, 0);
struct tg_segment sN = tg_line_segment_at(line, nsegs-1);
return pteq(point, s0.a) || pteq(point, sN.b);
}
/// Tests whether a point fully contains a polygon.
/// @see PointFuncs
bool tg_point_covers_poly(struct tg_point point, const struct tg_poly *poly) {
return !tg_poly_empty(poly) &&
tg_point_covers_rect(point, tg_poly_rect(poly));
}
bool tg_point_contains_poly(struct tg_point point, const struct tg_poly *poly) {
// not possible
(void)point; (void)poly;
return false;
}
/// Tests whether a point intersects a polygon.
/// @see PointFuncs
bool tg_point_intersects_poly(struct tg_point point,
const struct tg_poly *poly)
{
return tg_poly_intersects_point(poly, point);
}
bool tg_point_touches_poly(struct tg_point point, const struct tg_poly *poly) {
// Return true if the point touches the boundary of the exterior ring or
// the boundary of the interior holes.
const struct tg_ring *ring = tg_poly_exterior(poly);
if (tg_line_covers_point((struct tg_line*)ring, point)) {
return true;
}
int nholes = tg_poly_num_holes(poly);
for (int i = 0; i < nholes; i++) {
const struct tg_ring *ring = tg_poly_hole_at(poly, i);
if (tg_line_covers_point((struct tg_line*)ring, point)) {
return true;
}
}
return false;
}
////////////////////
// segment
////////////////////
static bool point_on_segment(struct tg_point p, struct tg_segment s) {
if (!tg_rect_covers_point(tg_segment_rect(s), p)) {
return false;
}
return collinear(s.a.x, s.a.y, s.b.x, s.b.y, p.x, p.y);
}
enum tg_raycast_result {
TG_OUT, // point is above, below, or to the right of the segment
TG_IN, // point is to the left (and inside the vertical bounds)
TG_ON, // point is on the segment
};
static enum tg_raycast_result raycast(struct tg_segment seg,
struct tg_point p)
{
struct tg_rect r = tg_segment_rect(seg);
if (p.y < r.min.y || p.y > r.max.y) {
return TG_OUT;
}
if (p.x < r.min.x) {
if (p.y != r.min.y && p.y != r.max.y) {
return TG_IN;
}
} else if (p.x > r.max.x) {
if (r.min.y != r.max.y && r.min.x != r.max.x) {
return TG_OUT;
}
}
struct tg_point a = seg.a;
struct tg_point b = seg.b;
if (b.y < a.y) {
struct tg_point t = a;
a = b;
b = t;
}
if (pteq(p, a) || pteq(p, b)) {
return TG_ON;
}
if (a.y == b.y) {
if (a.x == b.x) {
return TG_OUT;
}
if (p.y == b.y) {
if (!(p.x < r.min.x || p.x > r.max.x)) {
return TG_ON;
}
}
}
if (a.x == b.x && p.x == b.x) {
if (p.y >= a.y && p.y <= b.y) {
return TG_ON;
}
}
if (collinear(a.x, a.y, b.x, b.y, p.x, p.y)) {
if (p.x < r.min.x) {
if (r.min.y == r.max.y) {
return TG_OUT;
}
} else if (p.x > r.max.x) {
return TG_OUT;
}
return TG_ON;
}
if (p.y == a.y || p.y == b.y) {
p.y = nexttoward(p.y, INFINITY);
}
if (p.y < a.y || p.y > b.y) {
return TG_OUT;
}
if (a.x > b.x) {
if (p.x >= a.x) {
return TG_OUT;
}
if (p.x <= b.x) {
return TG_IN;
}
} else {
if (p.x >= b.x) {
return TG_OUT;
}
if (p.x <= a.x) {
return TG_IN;
}
}
if ((p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)) {
return TG_IN;
}
return TG_OUT;
}
/// Performs the raycast operation of a point on segment
enum tg_raycast_result tg_raycast(struct tg_segment seg, struct tg_point p) {
return raycast(seg, p);
}
struct tg_point tg_point_move(struct tg_point point,
double delta_x, double delta_y)
{
return (struct tg_point){ .x = point.x + delta_x, .y = point.y + delta_y };
}
struct tg_segment tg_segment_move(struct tg_segment seg,
double delta_x, double delta_y)
{
return (struct tg_segment){
.a = tg_point_move(seg.a, delta_x, delta_y),
.b = tg_point_move(seg.b, delta_x, delta_y),
};
}
/// Tests whether a segment fully contains a point.
/// @see SegmentFuncs
bool tg_segment_covers_point(struct tg_segment seg, struct tg_point p) {
return point_on_segment(p, seg);
}
/// Tests whether a segment fully contains another segment.
/// @see SegmentFuncs
bool tg_segment_covers_segment(struct tg_segment a, struct tg_segment b) {
return tg_segment_covers_point(a, b.a) &&
tg_segment_covers_point(a, b.b);
}
static void segment_fill_rect(const struct tg_segment *seg,
struct tg_rect *rect)
{
rect->min.x = fmin0(seg->a.x, seg->b.x);
rect->min.y = fmin0(seg->a.y, seg->b.y);
rect->max.x = fmax0(seg->a.x, seg->b.x);
rect->max.y = fmax0(seg->a.y, seg->b.y);
}
/// Returns the minimum bounding rectangle of a segment.
/// @see SegmentFuncs
struct tg_rect tg_segment_rect(struct tg_segment seg) {
struct tg_rect rect;
segment_fill_rect(&seg, &rect);
return rect;
}
static bool rect_intersects_rect(struct tg_rect *a, struct tg_rect *b) {
return !(b->min.x > a->max.x || b->max.x < a->min.x ||
b->min.y > a->max.y || b->max.y < a->min.y);
}
/// Tests whether a rectangle intersects another rectangle.
/// @see RectFuncs
bool tg_rect_intersects_rect(struct tg_rect a, struct tg_rect b) {
return rect_intersects_rect(&a, &b);
}
/// Tests whether a rectangle full contains another rectangle.
bool tg_rect_covers_rect(struct tg_rect a, struct tg_rect b) {
return !(b.min.x < a.min.x || b.max.x > a.max.x ||
b.min.y < a.min.y || b.max.y > a.max.y);
}
/// Returns the number of points. Always 5 for rects.
int tg_rect_num_points(struct tg_rect r) {
(void)r;
return 5;
}
/// Returns the number of segments. Always 4 for rects.
int tg_rect_num_segments(struct tg_rect r) {
(void)r;
return 4;
}
/// Returns the point at index.
struct tg_point tg_rect_point_at(struct tg_rect r, int index) {
switch (index) {
case 0:
return (struct tg_point){ r.min.x, r.min.y };
case 1:
return (struct tg_point){ r.max.x, r.min.y };
case 2:
return (struct tg_point){ r.max.x, r.max.y };
case 3:
return (struct tg_point){ r.min.x, r.max.y };
case 4:
return (struct tg_point){ r.min.x, r.min.y };
default:
return (struct tg_point){ 0 };
}
}
/// Returns the segment at index.
struct tg_segment tg_rect_segment_at(struct tg_rect r, int index) {
switch (index) {
case 0:
return (struct tg_segment){ { r.min.x, r.min.y}, { r.max.x, r.min.y} };
case 1:
return (struct tg_segment){ { r.max.x, r.min.y}, { r.max.x, r.max.y} };
case 2:
return (struct tg_segment){ { r.max.x, r.max.y}, { r.min.x, r.max.y} };
case 3:
return (struct tg_segment){ { r.min.x, r.max.y}, { r.min.x, r.min.y} };
default:
return (struct tg_segment){ 0 };
}
}
/// Tests whether a segment intersects another segment.
/// @see SegmentFuncs
bool tg_segment_intersects_segment(struct tg_segment seg_a,
struct tg_segment seg_b)
{
struct tg_point a = seg_a.a;
struct tg_point b = seg_a.b;
struct tg_point c = seg_b.a;
struct tg_point d = seg_b.b;
if (!tg_rect_intersects_rect(tg_segment_rect(seg_a),
tg_segment_rect(seg_b)))
{
return false;
}
if (pteq(seg_a.a, seg_b.a) || pteq(seg_a.a, seg_b.b) ||
pteq(seg_a.b, seg_b.a) || pteq(seg_a.b, seg_b.b))
{
return true;
}
double cmpx = c.x-a.x;
double cmpy = c.y-a.y;
double rx = b.x-a.x;
double ry = b.y-a.y;
double cmpxr = cmpx*ry - cmpy*rx;
if (eq_zero(cmpxr)) {
// collinear, and so intersect if they have any overlap
if (!(((c.x-a.x <= 0) != (c.x-b.x <= 0))) ||
((c.y-a.y <= 0) != (c.y-b.y <= 0)))
{
return tg_segment_covers_point(seg_a, seg_b.a) ||
tg_segment_covers_point(seg_a, seg_b.b) ||
tg_segment_covers_point(seg_b, seg_a.a) ||
tg_segment_covers_point(seg_b, seg_a.b);
}
return true;
}
double sx = d.x-c.x;
double sy = d.y-c.y;
double rxs = rx*sy - ry*sx;
if (eq_zero(rxs)) {
// Segments are parallel.
return false;
}
double cmpxs = cmpx*sy - cmpy*sx;
double rxsr = 1 / rxs;
double t = cmpxs * rxsr;
double u = cmpxr * rxsr;
if (!((t >= 0) && (t <= 1) && (u >= 0) && (u <= 1))) {
return false;
}
return true;
}
/// Tests whether a segment fully contains a rectangle.
/// @see SegmentFuncs
bool tg_segment_covers_rect(struct tg_segment seg, struct tg_rect rect) {
return tg_segment_covers_point(seg, rect.min) &&
tg_segment_covers_point(seg, rect.max);
}
//////////////////
// ystripes
//////////////////
struct ystripe {
int count;
int *indexes;
};
struct buf {
uint8_t *data;
size_t len, cap;
};
static bool buf_ensure(struct buf *buf, size_t len) {
if (buf->cap-buf->len >= len) return true;
size_t cap = buf->cap;
do {
cap = grow_cap(cap, 16);
} while (cap-buf->len < len);
uint8_t *data = tg_realloc(buf->data, cap+1);
if (!data) return false;
buf->data = data;