-
Notifications
You must be signed in to change notification settings - Fork 77
/
aoi.c
7133 lines (6135 loc) · 195 KB
/
aoi.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
/*!
Area Of Interest In Game Developing
Copyright [email protected]
Licence: Apache 2.0
Project: https://github.com/JerryZhou/aoi.git
Purpose: Resolve the AOI problem in game developing
with high run fps
with minimal memory cost,
Please see examples for more details.
*/
#include "aoi.h"
#include <math.h>
#include <stdarg.h>
#include <ctype.h>
#include <assert.h>
#ifdef _WIN32
#ifdef __cplusplus
extern "C" {
#endif
static int gettimeofday(struct timeval *tp, void *tzp)
{
time_t clock;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm.tm_isdst = -1;
clock = mktime(&tm);
tp->tv_sec = clock;
tp->tv_usec = wtm.wMilliseconds * 1000;
return 0;
}
#ifdef __cplusplus
}
#endif /*__cplusplus*/
#endif /*WIN32*/
/* 日志开关 */
#define open_log_code (0) /* 关于编码生成的日志 */
#define open_log_gencode (0)
#define open_log_node (0) /* 关于节点生成的日志 */
#define open_log_node_get (0) /* 关于节点查找的日志 */
#define open_log_unit (0)
#define open_log_unit_update (0)
#define open_log_filter (0)
#define open_log_unit_add (0)
#define open_log_unit_remove (0)
#define open_log_profile (0)
#define open_log_map_construct (0)
/* 状态操作宏 */
#define _state_add(value, state) value |= state
#define _state_remove(value, state) value &= ~state
#define _state_is(value, state) (value & state)
#ifndef __max
#define __max(a, b) ((a) > (b) ? (a) : (b))
#endif
#if (iimeta)
/* 内存统计 */
volatile int64_t gcallocsize = 0;
volatile int64_t gfreesize = 0;
volatile int64_t gholdsize = 0;
#if (iithreadsafe)
static imutex *_imeta_mutex() {
static imutex realmutex;
static imutex *mutex = NULL;
if (mutex == NULL) {
mutex = &realmutex;
imutexinit(mutex);
}
return mutex;
}
#define _imeta_global_lock imutexlock(_imeta_mutex())
#define _imeta_global_unlock imutexunlock(_imeta_mutex())
#define _imeta_lock imutexlock(&meta->mutex)
#define _imeta_unlock imutexunlock(&meta->mutex)
#else
#define _imeta_global_lock (void)0
#define _imeta_global_unlock (void)0
#define _imeta_lock (void)meta
#define _imeta_unlock (void)meta
#endif
#undef __ideclaremeta
#define __ideclaremeta(type, cap) {#type, {NULL, 0, cap}, sizeof(type), -1, 0, 0, NULL, NULL},
/* 所有类型的元信息系统 */
imeta gmetas[] = {__iallmeta(__ideclaremeta)
__ideclaremeta(imeta, 0)
};
/* 所有自定义的类型原系统 */
imeta gmetasuser[IMaxMetaCountForUser] = {{0}};
#undef __ideclaremeta
#define __ideclaremeta(type, cap) EnumMetaTypeIndex_##type
#ifndef __countof
#define __countof(array) (sizeof(array)/sizeof(array[0]))
#endif
/* 内置的meta个数 */
static int const gmetacount = __countof(gmetas);
static int gmetacountuser = 0;
/* 获取类型的元信息 */
imeta *imetaget(int idx) {
imeta *meta = NULL;
if (idx < 0) {
return NULL;
}
if (idx < gmetacount) {
meta = &gmetas[idx];
/*take current as the mark for first time*/
if (meta->current == -1) {
meta->current = 0;
#if (iithreadsafe)
imutexinit(&meta->mutex);
#endif
}
return meta;
}
idx -= gmetacount;
if (idx < gmetacountuser ) {
return &gmetasuser[idx];
}
return NULL;
}
/* 也可以手动注册一个元信息来管理自己的对象: 然后就可以通过 iobjmallocuser 进行对象内存管理 */
int imetaregister(const char* name, int size, int capacity) {
gmetasuser[gmetacountuser].name = name;
gmetasuser[gmetacountuser].size = size;
gmetasuser[gmetacountuser].cache.capacity = capacity;
gmetasuser[gmetacountuser].tracecalloc = NULL;
gmetasuser[gmetacountuser].tracefree = NULL;
#if (iithreadsafe)
imutexinit(&gmetasuser[gmetacountuser].mutex);
#endif
return gmetacount + gmetacountuser++;
}
/*calloc memory for meta*/
static iobj* _imetaobjcalloc(imeta *meta) {
int newsize = sizeof(iobj) + meta->size;
iobj *obj = (iobj*)icalloc(1, newsize);
obj->meta = meta;
obj->size = newsize;
_imeta_lock;
obj->meta->alloced += newsize;
obj->meta->current += newsize;
_imeta_unlock;
_imeta_global_lock;
gcallocsize += newsize;
gholdsize += newsize;
_imeta_global_unlock;
/* tracing the alloc */
if (meta->tracecalloc) {
meta->tracecalloc(meta, obj);
}
return obj;
}
/* 释放对象 */
static void _imetaobjfree(iobj *obj) {
imeta *meta = obj->meta;
/* tracing the alloc */
if (meta->tracefree) {
meta->tracefree(meta, obj);
}
_imeta_lock;
obj->meta->current -= obj->size;
obj->meta->freed += obj->size;
_imeta_unlock;
_imeta_global_lock;
gfreesize += obj->size;
gholdsize -= obj->size;
_imeta_global_unlock;
ifree(obj);
}
/**
* 尝试从缓冲区拿对象
*/
static iobj *_imetapoll(imeta *meta) {
iobj *obj = NULL;
_imeta_lock;
if (meta->cache.length) {
obj = meta->cache.root;
meta->cache.root = meta->cache.root->next;
obj->next = NULL;
--meta->cache.length;
memset(obj->addr, 0, obj->meta->size);
_imeta_unlock;
} else {
_imeta_unlock;
obj = _imetaobjcalloc(meta);
}
return obj;
}
/* Meta 的缓冲区管理 */
void imetapush(iobj *obj) {
imeta *meta = obj->meta;
_imeta_lock;
if (obj->meta->cache.length < obj->meta->cache.capacity) {
obj->next = obj->meta->cache.root;
obj->meta->cache.root = obj;
++obj->meta->cache.length;
_imeta_unlock;
} else {
_imeta_unlock;
_imetaobjfree(obj);
}
}
/* 获取响应的内存:会经过Meta的Cache */
void *iaoicalloc(imeta *meta) {
iobj *obj = _imetapoll(meta);
return obj->addr;
}
/* 偏移一下获得正确的内存对象 */
#define __iobj(p) (iobj*)((char*)(p) - sizeof(iobj))
/* 释放内存:会经过Meta的Cache */
void iaoifree(void *p) {
iobj *newp = __iobj(p);
imetapush(newp);
}
/* 尽可能的释放Meta相关的Cache */
void iaoicacheclear(imeta *meta) {
iobj *next = NULL;
iobj *cur = NULL;
icheck(meta->cache.length);
_imeta_lock;
cur = meta->cache.root;
while (cur) {
next = cur->next;
_imetaobjfree(cur);
cur = next;
}
meta->cache.root = NULL;
meta->cache.length = 0;
_imeta_unlock;
}
/* 打印当前内存状态 */
void iaoimemorystate() {
int i;
ilog("[AOI-Memory] *************************************************************** Begin\n");
ilog("[AOI-Memory] Total---> new: %" PRId64 ", free: %" PRId64 ", hold: %" PRId64 " \n", gcallocsize, gfreesize, gholdsize);
for (i=0; i<gmetacount; ++i) {
ilog("[AOI-Memory] "__imeta_format"\n", __imeta_value(gmetas[i]));
}
for (i=0; i<gmetacountuser; ++i) {
ilog("[AOI-Memory] "__imeta_format"\n", __imeta_value(gmetasuser[i]));
}
ilog("[AOI-Memory] *************************************************************** End\n");
}
/* 获取指定对象的meta信息 */
imeta *iaoigetmeta(const void *p) {
iobj *obj = NULL;
icheckret(p, NULL);
obj = __iobj(p);
return obj->meta;
}
/* 指定对象是响应的类型 */
int iaoiistype(const void *p, const char* type) {
imeta *meta = NULL;
icheckret(type, iino);
meta = iaoigetmeta(p);
icheckret(meta, iino);
if (strlen(type) != strlen(meta->name)) {
return iino;
}
if (strncmp(type, meta->name, strlen(meta->name)) == 0) {
return iiok;
}
return iino;
}
/*获取当前的总的内存统计*/
int64_t iaoimemorysize(void *meta, int kind) {
switch (kind) {
case EnumAoiMemoerySizeKind_Alloced:
return meta ? ((imeta*)(meta))->alloced : gcallocsize;
break;
case EnumAoiMemoerySizeKind_Freed:
return meta ? ((imeta*)(meta))->freed : gfreesize;
break;
case EnumAoiMemoerySizeKind_Hold:
return meta ? ((imeta*)(meta))->current : gholdsize;
break;
default:
break;
}
return 0;
}
#else
void iaoimemorystate() {
ilog("[AOI-Memory] Not Implement IMeta \n");
}
/*获取当前的总的内存统计*/
int64_t iaoimemorysize(void *meta, int kind) {
return 0;
}
#endif
/* 获取当前系统的微秒数 */
int64_t igetcurmicro() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000*1000 + tv.tv_usec;
}
/* 获取当前系统的毫秒数 */
int64_t igetcurtick() {
return igetcurmicro()/1000;
}
/* 获取系统的下一个唯一的事件纳秒数 */
int64_t igetnextmicro(){
static int64_t gseq = 0;
int64_t curseq = igetcurmicro();
if (curseq > gseq) {
gseq = curseq;
}else {
++gseq;
}
return gseq;
}
/* return the next pow of two */
int inextpot(int x) {
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >>16);
return x + 1;
}
/* sleeping the current thread */
void isleep(unsigned int milliseconds) {
#ifdef WIN32
Sleep((DWORD)milliseconds);
#else
sleep(milliseconds);
#endif
}
/*create resource*/
void imutexinit(imutex *mutex) {
#ifdef WIN32
mutex->_mutex = CreateMutex(NULL, 0, NULL);
#else
/* recursive mutex */
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex->_mutex, &attr);
#endif
}
/*release resource*/
void imutexrelease(imutex *mutex) {
#ifdef WIN32
CloseHandle(mutex->_mutex);
#else
pthread_mutex_destroy(&mutex->_mutex);
#endif
}
/*lock mutex*/
void imutexlock(imutex *mx) {
#ifdef WIN32
WaitForSingleObject(mx->_mutex, 0);
#else
pthread_mutex_lock(&mx->_mutex);
#endif
}
/*unlock mutex*/
void imutexunlock(imutex *mx) {
#ifdef WIN32
ReleaseMutex(mx->_mutex);
#else
pthread_mutex_unlock(&mx->_mutex);
#endif
}
/*************************************************************/
/* iatomic */
/*************************************************************/
/* compare the store with expected, than store the value with desired */
uint32_t iatomiccompareexchange(volatile uint32_t *store, uint32_t expected, uint32_t desired) {
#ifdef WIN32
return _InterlockedCompareExchange((volatile LONG*)store, expected, desired);
#else
return __sync_val_compare_and_swap_4(store, expected, desired);
#endif
}
/* fetch the old value and store the with add*/
uint32_t iatomicadd(volatile uint32_t *store, uint32_t add) {
#ifdef WIN32
return _InterlockedExchangeAdd((volatile LONG*)store, add);
#else
return __sync_add_and_fetch_4(store, add);
#endif
}
/* fetch the old value, than do exchange operator */
uint32_t iatomicexchange(volatile uint32_t *store, uint32_t value) {
#ifdef WIN32
return _InterlockedExchange((volatile LONG*)store, value);
#else
return __sync_lock_test_and_set_4(store, value);
#endif
}
/* atomic increment, return the new value */
uint32_t iatomicincrement(volatile uint32_t *store) {
#ifdef WIN32
return _InterlockedIncrement((volatile LONG*)store);
#else
return __sync_add_and_fetch_4(store, 1);
#endif
}
uint32_t iatomicdecrement(volatile uint32_t *store) {
#ifdef WIN32
return _InterlockedDecrement((volatile LONG*)store);
#else
return __sync_sub_and_fetch_4(store, 1);
#endif
}
static const char _base64EncodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const short _base64DecodingTable[256] = {
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
-2, 0, 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, -2, -2, -2, -2, -2,
-2, 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, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};
int ibase64encode_n(const unsigned char *in, size_t inlen, char *out, size_t *outsize) {
const unsigned char * objRawData = in;
char * objPointer;
char * strResult;
/* Get the Raw Data length and ensure we actually have data */
int intLength = inlen;
if (intLength == 0) return iino;
/* Setup the String-based Result placeholder and pointer within that placeholder */
strResult = out;
objPointer = strResult;
/* Iterate through everything */
while (inlen > 2) { /* keep going until we have less than 24 bits */
*objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
*objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
*objPointer++ = _base64EncodingTable[((objRawData[1] & 0x0f) << 2) + (objRawData[2] >> 6)];
*objPointer++ = _base64EncodingTable[objRawData[2] & 0x3f];
/* we just handled 3 octets (24 bits) of data */
objRawData += 3;
inlen -= 3;
}
/* now deal with the tail end of things */
if (intLength != 0) {
*objPointer++ = _base64EncodingTable[objRawData[0] >> 2];
if (intLength > 1) {
*objPointer++ = _base64EncodingTable[((objRawData[0] & 0x03) << 4) + (objRawData[1] >> 4)];
*objPointer++ = _base64EncodingTable[(objRawData[1] & 0x0f) << 2];
*objPointer++ = '=';
} else {
*objPointer++ = _base64EncodingTable[(objRawData[0] & 0x03) << 4];
*objPointer++ = '=';
*objPointer++ = '=';
}
}
/* Terminate the string-based result */
*objPointer = '\0';
/*Give Me the Length*/
if (outsize) {
*outsize = strlen(objPointer);
}
return iiok;
}
int ibase64decode_n(const char *in, size_t inlen, unsigned char *out, size_t *outsize) {
const char *objPointer = in;
size_t intLength = inlen;
int intCurrent;
int i = 0, j = 0, k;
unsigned char *objResult = out;
/* Run through the whole string, converting as we go */
while ( ((intCurrent = *objPointer++) != '\0') && (intLength-- > 0) ) {
if (intCurrent == '=') {
if (*objPointer != '=' && ((i % 4) == 1)) {/* || (intLength > 0)) { */
/* the padding character is invalid at this point -- so this entire string is invalid */
return iino;
}
continue;
}
intCurrent = _base64DecodingTable[intCurrent];
if (intCurrent == -1) {
/* we're at a whitespace -- simply skip over */
continue;
} else if (intCurrent == -2) {
/* we're at an invalid character */
return iino;
}
switch (i % 4) {
case 0:
objResult[j] = intCurrent << 2;
break;
case 1:
objResult[j++] |= intCurrent >> 4;
objResult[j] = (intCurrent & 0x0f) << 4;
break;
case 2:
objResult[j++] |= intCurrent >>2;
objResult[j] = (intCurrent & 0x03) << 6;
break;
case 3:
objResult[j++] |= intCurrent;
break;
}
i++;
}
/* mop things up if we ended on a boundary */
k = j;
if (intCurrent == '=') {
switch (i % 4) {
case 1:
/* Invalid state */
return iino;
case 2:
k++;
/* flow through */
case 3:
objResult[k] = 0;
}
}
/*give me the outsize*/
if (outsize) {
*outsize = k;
}
return iiok;
}
/* zero point */
const ipos kipos_zero = {0,0};
/* 计算距离的平方 */
ireal idistancepow2(const ipos *p, const ipos *t) {
ireal dx = p->x - t->x;
ireal dy = p->y - t->y;
return dx*dx + dy*dy;
}
/* zero point */
const ipos3 kipos3_zero = {0, 0, 0};
/* 计算距离的平方 */
ireal idistancepow3(const ipos3 *p, const ipos3 *t) {
ireal dx = p->x - t->x;
ireal dy = p->y - t->y;
ireal dz = p->z - t->z;
return dx*dx + dy*dy + dz*dz;
}
/* get the xy from the p with xz */
void ipos3takexz(const ipos3 *p, ipos *to) {
to->x = p->x;
to->y = p->z;
}
/* 把点在这个方向上进行移动 */
ipos ivec2movepoint(const ivec2 *dir, ireal dist, const ipos *p) {
ipos to = *p;
to.x += dir->v.x * dist;
to.y += dir->v.y * dist;
return to;
}
/* 两点相减得到向量 */
ivec2 ivec2subtractpoint(const ipos *p0, const ipos *p1) {
ivec2 vec;
vec.v.x = p0->x - p1->x;
vec.v.y = p0->y - p1->y;
return vec;
}
/* 点积 */
ireal ivec2dot(const ivec2 *l, const ivec2 *r) {
icheckret(l, 0);
icheckret(r, 0);
return l->v.x * r->v.x + l->v.y * r->v.y;
}
/* 减法 */
ivec2 ivec2subtract(const ivec2 *l, const ivec2 *r) {
ivec2 vec;
vec.v.x = r->v.x - l->v.x;
vec.v.y = r->v.y - l->v.y;
return vec;
}
/* 加法*/
ivec2 ivec2add(const ivec2 *l, const ivec2 *r) {
ivec2 vec;
vec.v.x = r->v.x + l->v.x;
vec.v.y = r->v.y + l->v.y;
return vec;
}
/* 乘法 */
ivec2 ivec2multipy(const ivec2 *l, const ireal a) {
ivec2 vec;
vec.v.x = l->v.x * a;
vec.v.y = l->v.y * a;
return vec;
}
/* 绝对值 */
ivec2 ivec2abs(const ivec2* l) {
ivec2 vec;
vec.v.x = fabs(l->v.x);
vec.v.y = fabs(l->v.y);
return vec;
}
/* 归一*/
ivec2 ivec2normalize(const ivec2 *l) {
ireal len = ivec2length(l);
return len > 0 ? ivec2multipy(l, 1.0/len) : *l;
}
/* 长度的平方 */
ireal ivec2lengthsqr(const ivec2 *l) {
return ivec2dot(l, l);
}
/* 长度 */
ireal ivec2length(const ivec2 *l) {
return sqrtf(ivec2dot(l, l));
}
/* 平行分量, 确保 r 已经归一化 */
ivec2 ivec2parallel(const ivec2 *l, const ivec2 *r) {
ireal projection = ivec2dot (l, r);
return ivec2multipy(r, projection);
}
/* 垂直分量, 确保 r 已经归一化 */
ivec2 ivec2perpendicular(const ivec2 *l, const ivec2 *r) {
ivec2 p = ivec2parallel(l, r);
return ivec2subtract(l, &p);
}
/*************************************************************/
/* ivec3 */
/*************************************************************/
/* 两点相减得到向量 */
ivec3 ivec3subtractpoint(const ipos3 *p0, const ipos3 *p1) {
ivec3 v;
v.v.x = p0->x - p1->x;
v.v.y = p0->y - p1->y;
v.v.z = p0->z - p1->z;
return v;
}
/* 加法*/
ivec3 ivec3add(const ivec3 *l, const ivec3 *r) {
ivec3 vec;
vec.v.x = r->v.x + l->v.x;
vec.v.y = r->v.y + l->v.y;
vec.v.z = r->v.z + l->v.z;
return vec;
}
/* 减法 */
ivec3 ivec3subtract(const ivec3 *l, const ivec3 *r) {
ivec3 vec;
vec.v.x = r->v.x - l->v.x;
vec.v.y = r->v.y - l->v.y;
vec.v.z = r->v.z - l->v.z;
return vec;
}
/* 乘法 */
ivec3 ivec3multipy(const ivec3 *l, ireal a) {
ivec3 vec;
vec.v.x = l->v.x * a;
vec.v.y = l->v.y * a;
vec.v.z = l->v.z * a;
return vec;
}
/* 点积
* https://en.wikipedia.org/wiki/Dot_product
* */
ireal ivec3dot(const ivec3 *l, const ivec3 *r) {
return l->v.x * r->v.x
+ l->v.y * r->v.y
+ l->v.z * r->v.z;
}
/* 乘积
* https://en.wikipedia.org/wiki/Cross_product
* */
ivec3 ivec3cross(const ivec3 *l, const ivec3 *r) {
ivec3 vec;
vec.v.x = l->v.y * r->v.z - l->v.z * r->v.y;
vec.v.y = l->v.z * r->v.x - l->v.x * r->v.z;
vec.v.z = l->v.x * r->v.y - l->v.y * r->v.x;
return vec;
}
/* 长度的平方 */
ireal ivec3lengthsqr(const ivec3 *l) {
return ivec3dot(l, l);
}
/* 长度 */
ireal ivec3length(const ivec3 *l) {
return sqrtf(ivec3dot(l, l));
}
/* 绝对值 */
ivec3 ivec3abs(const ivec3* l) {
ivec3 vec;
vec.v.x = fabs(l->v.x);
vec.v.y = fabs(l->v.y);
vec.v.z = fabs(l->v.z);
return vec;
}
/* 归一*/
ivec3 ivec3normalize(const ivec3 *l) {
ireal len = ivec3length(l);
return len > 0 ? ivec3multipy(l, 1.0/len) : *l;
}
/* 平行分量, 确保 r 已经归一化 */
ivec3 ivec3parallel(const ivec3 *l, const ivec3 *r) {
ireal projection = ivec3dot (l, r);
return ivec3multipy(r, projection);
}
/* 垂直分量, 确保 r 已经归一化 */
ivec3 ivec3perpendicular(const ivec3 *l, const ivec3 *r) {
ivec3 p = ivec3parallel(l, r);
return ivec3subtract(l, &p);
}
/*************************************************************/
/* iline2d */
/*************************************************************/
/* start ==> end */
ivec2 iline2ddirection(const iline2d *line) {
ivec2 v = ivec2subtractpoint(&line->end, &line->start);
return ivec2normalize(&v);
}
/* start ==> end , rorate -90 */
ivec2 iline2dnormal(const iline2d *line) {
ireal y;
ivec2 v = iline2ddirection(line);
y = v.v.y;
v.v.y = -v.v.x;
v.v.x = y;
return v;
}
/**/
ireal iline2dlength(const iline2d *line) {
ivec2 v = ivec2subtractpoint(&line->end, &line->start);
return ivec2length(&v);
}
/*
* Determines the signed distance from a point to this line. Consider the line as
* if you were standing on start of the line looking towards end. Posative distances
* are to the right of the line, negative distances are to the left.
* */
ireal iline2dsigneddistance(const iline2d *line, const ipos *point) {
ivec2 v = ivec2subtractpoint(point, &line->start);
ivec2 normal = iline2dnormal(line);
return ivec2dot(&v, &normal);
}
/*
* Determines the signed distance from a point to this line. Consider the line as
* if you were standing on start of the line looking towards end. Posative distances
* are to the right of the line, negative distances are to the left.
* */
int iline2dclassifypoint(const iline2d *line, const ipos *point, ireal epsilon) {
int result = EnumPointClass_On;
ireal distance = iline2dsigneddistance(line, point);
if (distance > epsilon) {
result = EnumPointClass_Right;
} else if (distance < -epsilon) {
result = EnumPointClass_Left;
}
return result;
}
/*
* Determines if two segments intersect, and if so the point of intersection. The current
* member line is considered line AB and the incomming parameter is considered line CD for
* the purpose of the utilized equations.
*
* A = PointA of the member line
* B = PointB of the member line
* C = PointA of the provided line
* D = PointB of the provided line
* */
int iline2dintersection(const iline2d *line, const iline2d *other, ipos *intersect) {
ireal Ay_minus_Cy = line->start.y - other->start.y;
ireal Dx_minus_Cx = other->end.x - other->start.x;
ireal Ax_minus_Cx = line->start.x - other->start.x;
ireal Dy_minus_Cy = other->end.y - other->start.y;
ireal Bx_minus_Ax = line->end.x - line->start.x;
ireal By_minus_Ay = line->end.y - line->start.y;
ireal Numerator = (Ay_minus_Cy * Dx_minus_Cx) - (Ax_minus_Cx * Dy_minus_Cy);
ireal Denominator = (Bx_minus_Ax * Dy_minus_Cy) - (By_minus_Ay * Dx_minus_Cx);
ireal FactorAB, FactorCD;
/* if lines do not intersect, return now */
if (!Denominator)
{
if (!Numerator)
{
return EnumLineClass_Collinear;
}
return EnumLineClass_Paralell;
}
FactorAB = Numerator / Denominator;
FactorCD = ((Ay_minus_Cy * Bx_minus_Ax) - (Ax_minus_Cx * By_minus_Ay)) / Denominator;
/* posting (hitting a vertex exactly) is not allowed, shift the results
* if they are within a minute range of the end vertecies */
/*
if (fabs(FactorCD) < 1.0e-6f) {
FactorCD = 1.0e-6f;
} if (fabs(FactorCD - 1.0f) < 1.0e-6f) {
FactorCD = 1.0f - 1.0e-6f;
}
*/
/* if an interection point was provided, fill it in now */
if (intersect)
{
intersect->x = (line->start.x + (FactorAB * Bx_minus_Ax));
intersect->y = (line->start.y + (FactorAB * By_minus_Ay));
}
/* now determine the type of intersection */
if ((FactorAB >= 0.0f) && (FactorAB <= 1.0f) && (FactorCD >= 0.0f) && (FactorCD <= 1.0f)) {
return EnumLineClass_Segments_Intersect;
} else if ((FactorCD >= 0.0f) && (FactorCD <= 1.0f)) {
return (EnumLineClass_A_Bisects_B);
} else if ((FactorAB >= 0.0f) && (FactorAB <= 1.0f)) {
return (EnumLineClass_B_Bisects_A);
}
return EnumLineClass_Lines_Intersect;
}
/* Caculating the closest point in the segment to center pos */
ipos iline2dclosestpoint(const iline2d *line, const ipos *center, ireal epsilon) {
/*@see http://doswa.com/2009/07/13/circle-segment-intersectioncollision.html */
ipos closest;
ivec2 start_to_center = ivec2subtractpoint(center, &line->start);
ivec2 line_direction = iline2ddirection(line);
ireal line_len = iline2dlength(line);
ireal projlen = ivec2dot(&start_to_center, &line_direction);
if (projlen <= 0) {
closest = line->start;
} else if ( ireal_greater_than(projlen, line_len, epsilon)){
closest = line->end;
} else {
closest.x = line->start.x + line_direction.v.x * projlen;
closest.y = line->start.y + line_direction.v.y * projlen;
}
return closest;
}
/*************************************************************/
/* iline3d */
/*************************************************************/
/* start ==> end */
ivec3 iline3ddirection(const iline3d *line) {
ivec3 v = ivec3subtractpoint(&line->end, &line->start);
return ivec3normalize(&v);
}
/**/
ireal iline3dlength(const iline3d *line) {
ivec3 v = ivec3subtractpoint(&line->end, &line->start);
return ivec3length(&v);
}
/* find the closest point in line */
ipos3 iline3dclosestpoint(const iline3d *line, const ipos3 *center, ireal epsilon) {
/*@see http://doswa.com/2009/07/13/circle-segment-intersectioncollision.html */
ipos3 closest;
ivec3 start_to_center = ivec3subtractpoint(center, &line->start);
ivec3 line_direction = iline3ddirection(line);
ireal line_len = iline3dlength(line);
ireal projlen = ivec3dot(&start_to_center, &line_direction);
if (projlen <= 0) {
closest = line->start;