-
Notifications
You must be signed in to change notification settings - Fork 11
/
kit.h
1292 lines (1079 loc) · 43.3 KB
/
kit.h
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
// kit v0.2 | public domain - no warranty implied; use at your own risk
#ifndef KIT_H
#define KIT_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <setjmp.h>
#include <time.h>
#include <math.h>
#include <windows.h>
#include <windowsx.h>
#ifdef _MSC_VER
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "winmm.lib")
#endif
enum {
KIT_SCALE2X = (1 << 0),
KIT_SCALE3X = (1 << 1),
KIT_SCALE4X = (1 << 2),
KIT_HIDECURSOR = (1 << 3),
KIT_FPS30 = (1 << 4),
KIT_FPS144 = (1 << 5),
KIT_FPSINF = (1 << 6),
};
typedef union { struct { uint8_t b, g, r, a; }; uint32_t w; } kit_Color;
typedef struct { int x, y, w, h; } kit_Rect;
typedef struct { kit_Color *pixels; int w, h; } kit_Image;
typedef struct { kit_Rect rect; int xadv; } kit_Glyph;
typedef struct { kit_Image *image; kit_Glyph glyphs[256]; } kit_Font;
typedef struct {
bool wants_quit;
bool hide_cursor;
// input
int char_buf[32];
uint8_t key_state[256];
uint8_t mouse_state[16];
struct { int x, y; } mouse_pos;
struct { int x, y; } mouse_delta;
// time
double step_time;
double prev_time;
// graphics
kit_Rect clip;
kit_Font *font;
kit_Image *screen;
// windows
int win_w, win_h;
HWND hwnd;
HDC hdc;
} kit_Context;
#define kit_max(a, b) ((a) > (b) ? (a) : (b))
#define kit_min(a, b) ((a) < (b) ? (a) : (b))
#define kit_lengthof(a) (sizeof(a) / sizeof((a)[0]))
#define kit_rect(X, Y, W, H) ((kit_Rect) { (X), (Y), (W), (H) })
#define kit_rgba(R, G, B, A) ((kit_Color) { .r = (R), .g = (G), .b = (B), .a = (A) })
#define kit_rgb(R, G, B) kit_rgba(R, G, B, 0xff)
#define kit_alpha(A) kit_rgba(0xff, 0xff, 0xff, A)
#define KIT_BIG_RECT kit_rect(0, 0, 0xffffff, 0xffffff)
#define KIT_WHITE kit_rgb(0xff, 0xff, 0xff)
#define KIT_BLACK kit_rgb(0, 0, 0)
kit_Context* kit_create(const char *title, int w, int h, int flags);
void kit_destroy(kit_Context *ctx);
bool kit_step(kit_Context *ctx, double *dt);
void* kit_read_file(char *filename, int *len);
kit_Image* kit_create_image(int w, int h);
kit_Image* kit_load_image_file(char *filename);
kit_Image* kit_load_image_mem(void *data, int len);
void kit_destroy_image(kit_Image *img);
kit_Font* kit_load_font_file(char *filename);
kit_Font* kit_load_font_mem(void *data, int len);
void kit_destroy_font(kit_Font *font);
int kit_text_width(kit_Font *font, char *text);
int kit_get_char(kit_Context *ctx);
bool kit_key_down(kit_Context *ctx, int key);
bool kit_key_pressed(kit_Context *ctx, int key);
bool kit_key_released(kit_Context *ctx, int key);
void kit_mouse_pos(kit_Context *ctx, int *x, int *y);
void kit_mouse_delta(kit_Context *ctx, int *x, int *y);
bool kit_mouse_down(kit_Context *ctx, int button);
bool kit_mouse_pressed(kit_Context *ctx, int button);
bool kit_mouse_released(kit_Context *ctx, int button);
void kit_clear(kit_Context *ctx, kit_Color color);
void kit_set_clip(kit_Context *ctx, kit_Rect rect);
void kit_draw_point(kit_Context *ctx, kit_Color color, int x, int y);
void kit_draw_rect(kit_Context *ctx, kit_Color color, kit_Rect rect);
void kit_draw_line(kit_Context *ctx, kit_Color color, int x1, int y1, int x2, int y2);
void kit_draw_image(kit_Context *ctx, kit_Image *img, int x, int y);
void kit_draw_image2(kit_Context *ctx, kit_Color color, kit_Image *img, int x, int y, kit_Rect src);
void kit_draw_image3(kit_Context *ctx, kit_Color mul_color, kit_Color add_color, kit_Image *img, kit_Rect dst, kit_Rect src);
int kit_draw_text(kit_Context *ctx, kit_Color color, char *text, int x, int y);
int kit_draw_text2(kit_Context *ctx, kit_Color color, kit_Font *font, char *text, int x, int y);
#endif // KIT_H
//////////////////////////////////////////////////////////////////////////////
#ifdef KIT_IMPL
enum {
KIT_INPUT_DOWN = (1 << 0),
KIT_INPUT_PRESSED = (1 << 1),
KIT_INPUT_RELEASED = (1 << 2),
};
#define kit__expect(x) if (!(x)) { kit__panic("assertion failure: %s", #x); }
static void kit__panic(char *fmt, ...) {
fprintf(stderr, "kit fatal error: ");
va_list ap;
va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
fprintf(stderr, "\n");
exit(1);
}
static void* kit__alloc(int n) {
void *res = calloc(1, n);
if (!res) { kit__panic("out of memory"); }
return res;
}
static bool kit__check_input_flag(uint8_t *t, uint32_t idx, uint32_t cap, int flag) {
if (idx > cap) { return false; }
return t[idx] & flag ? true : false;
}
static void kit__scale_size_by_flags(int *w, int *h, int flags) {
if (flags & KIT_SCALE2X) { *w *= 2; *h *= 2; } else
if (flags & KIT_SCALE3X) { *w *= 3; *h *= 3; } else
if (flags & KIT_SCALE4X) { *w *= 4; *h *= 4; }
}
static double kit__flags_to_step_time(int flags) {
if (flags & KIT_FPS30 ) { return 1.0 / 30.0; }
if (flags & KIT_FPS144) { return 1.0 / 144.0; }
if (flags & KIT_FPSINF) { return 0; }
return 1.0 / 60.0;
}
static double kit__now(void) {
return clock() / 1000.0;
}
static kit_Rect kit__intersect_rects(kit_Rect a, kit_Rect b) {
int x1 = kit_max(a.x, b.x);
int y1 = kit_max(a.y, b.y);
int x2 = kit_min(a.x + a.w, b.x + b.w);
int y2 = kit_min(a.y + a.h, b.y + b.h);
return (kit_Rect) { x1, y1, x2 - x1, y2 - y1 };
}
static inline kit_Color kit__blend_pixel(kit_Color dst, kit_Color src) {
kit_Color res;
res.w = (dst.w & 0xff00ff) + ((((src.w & 0xff00ff) - (dst.w & 0xff00ff)) * src.a) >> 8);
res.g = dst.g + (((src.g - dst.g) * src.a) >> 8);
res.a = dst.a;
return res;
}
static inline kit_Color kit__blend_pixel2(kit_Color dst, kit_Color src, kit_Color clr) {
src.a = (src.a * clr.a) >> 8;
int ia = 0xff - src.a;
dst.r = ((src.r * clr.r * src.a) >> 16) + ((dst.r * ia) >> 8);
dst.g = ((src.g * clr.g * src.a) >> 16) + ((dst.g * ia) >> 8);
dst.b = ((src.b * clr.b * src.a) >> 16) + ((dst.b * ia) >> 8);
return dst;
}
static inline kit_Color kit__blend_pixel3(kit_Color dst, kit_Color src, kit_Color clr, kit_Color add) {
src.r = kit_min(255, src.r + add.r);
src.g = kit_min(255, src.g + add.g);
src.b = kit_min(255, src.b + add.b);
return kit__blend_pixel2(dst, src, clr);
}
static kit_Rect kit__get_adjusted_window_rect(kit_Context *ctx) {
// work out maximum size to retain aspect ratio
float src_ar = (float) ctx->screen->h / ctx->screen->w;
float dst_ar = (float) ctx->win_h / ctx->win_w;
int w, h;
if (src_ar < dst_ar) {
w = ctx->win_w; h = ceil(w * src_ar);
} else {
h = ctx->win_h; w = ceil(h / src_ar);
}
// return centered rect
return kit_rect((ctx->win_w - w) / 2, (ctx->win_h - h) / 2, w, h);
}
static LRESULT CALLBACK kit__wndproc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
kit_Context *ctx = (void*) GetProp(hWnd, "kit_Context");
switch (message) {
case WM_PAINT:;
BITMAPINFO bmi = {
.bmiHeader.biSize = sizeof(BITMAPINFOHEADER),
.bmiHeader.biBitCount = 32,
.bmiHeader.biCompression = BI_RGB,
.bmiHeader.biPlanes = 1,
.bmiHeader.biWidth = ctx->screen->w,
.bmiHeader.biHeight = -ctx->screen->h
};
kit_Rect wr = kit__get_adjusted_window_rect(ctx);
StretchDIBits(ctx->hdc,
wr.x, wr.y, wr.w, wr.h,
0, 0, ctx->screen->w, ctx->screen->h,
ctx->screen->pixels, &bmi, DIB_RGB_COLORS, SRCCOPY);
ValidateRect(hWnd, 0);
break;
case WM_SETCURSOR:
if (ctx->hide_cursor && LOWORD(lParam) == HTCLIENT) {
SetCursor(0);
break;
}
goto unhandled;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (lParam & (1 << 30)) { // key repeat
break;
}
ctx->key_state[(uint8_t) wParam] = KIT_INPUT_DOWN | KIT_INPUT_PRESSED;
break;
case WM_KEYUP:
case WM_SYSKEYUP:
ctx->key_state[(uint8_t) wParam] &= ~KIT_INPUT_DOWN;
ctx->key_state[(uint8_t) wParam] |= KIT_INPUT_RELEASED;
break;
case WM_CHAR:
if (wParam < 32) { break; }
for (int i = 0; i < kit_lengthof(ctx->char_buf); i++) {
if (ctx->char_buf[i]) { continue; }
ctx->char_buf[i] = wParam;
break;
}
break;
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
case WM_MBUTTONDOWN: case WM_MBUTTONUP:;
int button = (message == WM_LBUTTONDOWN || message == WM_LBUTTONUP) ? 1 :
(message == WM_RBUTTONDOWN || message == WM_RBUTTONUP) ? 2 : 3;
if (message == WM_LBUTTONDOWN || message == WM_RBUTTONDOWN || message == WM_MBUTTONDOWN) {
SetCapture(hWnd);
ctx->mouse_state[button] = KIT_INPUT_DOWN | KIT_INPUT_PRESSED;
} else {
ReleaseCapture();
ctx->mouse_state[button] &= ~KIT_INPUT_DOWN;
ctx->mouse_state[button] |= KIT_INPUT_RELEASED;
}
// fallthrough
case WM_MOUSEMOVE:;
wr = kit__get_adjusted_window_rect(ctx);
int prevx = ctx->mouse_pos.x;
int prevy = ctx->mouse_pos.y;
ctx->mouse_pos.x = (GET_X_LPARAM(lParam) - wr.x) * ctx->screen->w / wr.w;
ctx->mouse_pos.y = (GET_Y_LPARAM(lParam) - wr.y) * ctx->screen->h / wr.h;
ctx->mouse_delta.x += ctx->mouse_pos.x - prevx;
ctx->mouse_delta.y += ctx->mouse_pos.y - prevy;
break;
case WM_SIZE:
if (wParam != SIZE_MINIMIZED) {
// set size
ctx->win_w = LOWORD(lParam);
ctx->win_h = HIWORD(lParam);
// paint window black
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
HBRUSH brush = CreateSolidBrush(RGB(0, 0, 0));
FillRect(hdc, &ps.rcPaint, brush);
DeleteObject(brush);
EndPaint(hWnd, &ps);
// redraw
RedrawWindow(ctx->hwnd, 0, 0, RDW_INVALIDATE | RDW_UPDATENOW);
}
break;
case WM_QUIT:
case WM_CLOSE:
ctx->wants_quit = true;
break;
default:
unhandled:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
static void *kit__font_png_data;
static int kit__font_png_size;
kit_Context* kit_create(const char *title, int w, int h, int flags) {
kit_Context *ctx = kit__alloc(sizeof(kit_Context));
ctx->screen = kit_create_image(w, h);
ctx->step_time = kit__flags_to_step_time(flags);
ctx->hide_cursor = !!(flags & KIT_HIDECURSOR);
ctx->clip = kit_rect(0, 0, w, h);
RegisterClass(&(WNDCLASS) {
.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW,
.lpfnWndProc = kit__wndproc,
.hCursor = LoadCursor(0, IDC_ARROW),
.lpszClassName = title,
.hIcon = LoadIcon(GetModuleHandle(0), "icon"),
});
kit__scale_size_by_flags(&w, &h, flags);
RECT rect = { .right = w, .bottom = h };
int style = WS_OVERLAPPEDWINDOW;
AdjustWindowRect(&rect, style, 0);
ctx->hwnd = CreateWindow(
title, title, style,
CW_USEDEFAULT, CW_USEDEFAULT,
rect.right - rect.left, rect.bottom - rect.top,
0, 0, 0, 0
);
SetProp(ctx->hwnd, "kit_Context", ctx);
ShowWindow(ctx->hwnd, SW_NORMAL);
ctx->hdc = GetDC(ctx->hwnd);
timeBeginPeriod(1);
ctx->font = kit_load_font_mem(kit__font_png_data, kit__font_png_size);
ctx->prev_time = kit__now();
return ctx;
}
void kit_destroy(kit_Context *ctx) {
ReleaseDC(ctx->hwnd, ctx->hdc);
DestroyWindow(ctx->hwnd);
kit_destroy_image(ctx->screen);
kit_destroy_font(ctx->font);
free(ctx);
}
int kit_text_width(kit_Font *font, char *text) {
int x = 0;
for (uint8_t *p = (void*) text; *p; p++) {
x += font->glyphs[*p].xadv;
}
return x;
}
bool kit_step(kit_Context *ctx, double *dt) {
// present
RedrawWindow(ctx->hwnd, 0, 0, RDW_INVALIDATE | RDW_UPDATENOW);
// handle delta time / wait for next frame
double now = kit__now();
double wait = (ctx->prev_time + ctx->step_time) - now;
double prev = ctx->prev_time;
if (wait > 0) {
Sleep(wait * 1000);
ctx->prev_time += ctx->step_time;
} else {
ctx->prev_time = now;
}
if (dt) { *dt = ctx->prev_time - prev; }
// reset input state
memset(ctx->char_buf, 0, sizeof(ctx->char_buf));
for (int i = 0; i < sizeof(ctx->key_state); i++) {
ctx->key_state[i] &= ~(KIT_INPUT_PRESSED | KIT_INPUT_RELEASED);
}
for (int i = 0; i < sizeof(ctx->mouse_state); i++) {
ctx->mouse_state[i] &= ~(KIT_INPUT_PRESSED | KIT_INPUT_RELEASED);
}
// handle events
MSG msg;
while (PeekMessage(&msg, ctx->hwnd, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return !ctx->wants_quit;
}
void* kit_read_file(char *filename, int *len) {
FILE *fp = fopen(filename, "rb");
if (!fp) { return NULL; }
fseek(fp, 0, SEEK_END);
int n = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buf = kit__alloc(n + 1);
fread(buf, 1, n, fp);
fclose(fp);
if (len) { *len = n; }
return buf;
}
kit_Image* kit_create_image(int w, int h) {
kit__expect(w > 0 && h > 0);
kit_Image *img = kit__alloc(sizeof(kit_Image) + w * h * sizeof(kit_Color));
img->pixels = (void*) (img + 1);
img->w = w;
img->h = h;
return img;
}
kit_Image* kit_load_image_file(char *filename) {
int len;
void *data = kit_read_file(filename, &len);
if (!data) { return NULL; }
kit_Image *res = kit_load_image_mem(data, len);
free(data);
return res;
}
static kit_Image* kit__load_png(void *data, int len);
kit_Image* kit_load_image_mem(void *data, int len) {
return kit__load_png(data, len);
}
void kit_destroy_image(kit_Image *img) {
free(img);
}
static bool kit__check_column(kit_Image *img, int x, int y, int h) {
while (h > 0) {
if (img->pixels[x + y * img->w].a) {
return true;
}
y++; h--;
}
return false;
}
static kit_Font* kit__load_font_from_image(kit_Image *img) {
if (!img) { return NULL; }
kit_Font *font = kit__alloc(sizeof(kit_Font));
font->image = img;
// init glyphs
for (int i = 0; i < 256; i++) {
kit_Glyph *g = &font->glyphs[i];
kit_Rect r = {
(img->w / 16) * (i % 16),
(img->h / 16) * (i / 16),
img->w / 16,
img->h / 16
};
// right-trim rect
for (int x = r.x + r.w - 1; x >= r.x; x--) {
if (kit__check_column(font->image, x, r.y, r.h)) { break; }
r.w--;
}
// left-trim rect
for (int x = r.x; x < r.x + r.w; x++) {
if (kit__check_column(font->image, x, r.y, r.h)) { break; }
r.x++;
r.w--;
}
// set xadvance and rect
g->xadv = r.w + 1;
g->rect = r;
}
font->glyphs[' '].rect = (kit_Rect) {0};
font->glyphs[' '].xadv = font->glyphs['a'].xadv;
return font;
}
kit_Font* kit_load_font_file(char *filename) {
return kit__load_font_from_image(kit_load_image_file(filename));
}
kit_Font* kit_load_font_mem(void *data, int len) {
return kit__load_font_from_image(kit_load_image_mem(data, len));
}
void kit_destroy_font(kit_Font *font) {
free(font->image);
free(font);
}
int kit_get_char(kit_Context *ctx) {
for (int i = 0; i < kit_lengthof(ctx->char_buf); i++) {
if (!ctx->char_buf[i]) { continue; }
int res = ctx->char_buf[i];
ctx->char_buf[i] = 0;
return res;
}
return 0;
}
bool kit_key_down(kit_Context *ctx, int key) {
return kit__check_input_flag(ctx->key_state, key, sizeof(ctx->key_state), KIT_INPUT_DOWN);
}
bool kit_key_pressed(kit_Context *ctx, int key) {
return kit__check_input_flag(ctx->key_state, key, sizeof(ctx->key_state), KIT_INPUT_PRESSED);
}
bool kit_key_released(kit_Context *ctx, int key) {
return kit__check_input_flag(ctx->key_state, key, sizeof(ctx->key_state), KIT_INPUT_RELEASED);
}
void kit_mouse_pos(kit_Context *ctx, int *x, int *y) {
if (x) { *x = ctx->mouse_pos.x; }
if (y) { *y = ctx->mouse_pos.y; }
}
void kit_mouse_delta(kit_Context *ctx, int *x, int *y) {
if (x) { *x = ctx->mouse_delta.x; }
if (y) { *y = ctx->mouse_delta.y; }
}
bool kit_mouse_down(kit_Context *ctx, int button) {
return kit__check_input_flag(ctx->mouse_state, button, sizeof(ctx->mouse_state), KIT_INPUT_DOWN);
}
bool kit_mouse_pressed(kit_Context *ctx, int button) {
return kit__check_input_flag(ctx->mouse_state, button, sizeof(ctx->mouse_state), KIT_INPUT_PRESSED);
}
bool kit_mouse_released(kit_Context *ctx, int button) {
return kit__check_input_flag(ctx->mouse_state, button, sizeof(ctx->mouse_state), KIT_INPUT_RELEASED);
}
void kit_clear(kit_Context *ctx, kit_Color color) {
kit_draw_rect(ctx, color, KIT_BIG_RECT);
}
void kit_set_clip(kit_Context *ctx, kit_Rect rect) {
kit_Rect screen_rect = kit_rect(0, 0, ctx->screen->w, ctx->screen->h);
ctx->clip = kit__intersect_rects(rect, screen_rect);
}
void kit_draw_point(kit_Context *ctx, kit_Color color, int x, int y) {
if (color.a == 0) { return; }
kit_Rect r = ctx->clip;
if (x < r.x || y < r.y || x >= r.x + r.w || y >= r.y + r.h ) {
return;
}
kit_Color *dst = &ctx->screen->pixels[x + y * ctx->screen->w];
*dst = kit__blend_pixel(*dst, color);
}
void kit_draw_rect(kit_Context *ctx, kit_Color color, kit_Rect rect) {
if (color.a == 0) { return; }
rect = kit__intersect_rects(rect, ctx->clip);
kit_Color *d = &ctx->screen->pixels[rect.x + rect.y * ctx->screen->w];
int dr = ctx->screen->w - rect.w;
for (int y = 0; y < rect.h; y++) {
for (int x = 0; x < rect.w; x++) {
*d = kit__blend_pixel(*d, color);
d++;
}
d += dr;
}
}
void kit_draw_line(kit_Context *ctx, kit_Color color, int x1, int y1, int x2, int y2) {
int dx = abs(x2-x1);
int sx = x1 < x2 ? 1 : -1;
int dy = -abs(y2 - y1);
int sy = y1 < y2 ? 1 : -1;
int err = dx + dy;
for (;;) {
kit_draw_point(ctx, color, x1, y1);
if (x1 == x2 && y1 == y2) { break; }
int e2 = err << 1;
if (e2 >= dy) { err += dy; x1 += sx; }
if (e2 <= dx) { err += dx; y1 += sy; }
}
}
void kit_draw_image(kit_Context *ctx, kit_Image *img, int x, int y) {
kit_Rect dst = kit_rect(x, y, img->w, img->h);
kit_Rect src = kit_rect(0, 0, img->w, img->h);
kit_draw_image3(ctx, KIT_WHITE, KIT_BLACK, img, dst, src);
}
void kit_draw_image2(kit_Context *ctx, kit_Color color, kit_Image *img, int x, int y, kit_Rect src) {
kit_Rect dst = kit_rect(x, y, abs(src.w), abs(src.h));
kit_draw_image3(ctx, color, KIT_BLACK, img, dst, src);
}
void kit_draw_image3(kit_Context *ctx, kit_Color mul_color, kit_Color add_color, kit_Image *img, kit_Rect dst, kit_Rect src) {
// early exit on zero-sized anything
if (!src.w || !src.w || !dst.w || !dst.h) {
return;
}
/* do scaled render */
int cx1 = ctx->clip.x;
int cy1 = ctx->clip.y;
int cx2 = cx1 + ctx->clip.w;
int cy2 = cy1 + ctx->clip.h;
int stepx = (src.w << 10) / dst.w;
int stepy = (src.h << 10) / dst.h;
int sy = src.y << 10;
/* vertical clipping */
int dy = dst.y;
if (dy < cy1) { sy += (cy1 - dy) * stepy; dy = cy1; }
int ey = kit_min(cy2, dst.y + dst.h);
int blend_fn = 1;
if (mul_color.w != 0xffffffff) { blend_fn = 2; }
if ((add_color.w & 0xffffff00) != 0xffffff00) { blend_fn = 3; }
for (; dy < ey; dy++) {
if (dy >= cy1 && dy < cy2) {
int sx = src.x << 10;
kit_Color *srow = &img->pixels[(sy >> 10) * img->w];
kit_Color *drow = &ctx->screen->pixels[dy * ctx->screen->w];
/* horizontal clipping */
int dx = dst.x;
if (dx < cx1) { sx += (cx1 - dx) * stepx; dx = cx1; }
int ex = kit_min(cx2, dst.x + dst.w);
for (; dx < ex; dx++) {
kit_Color *s = &srow[sx >> 10];
kit_Color *d = &drow[dx];
switch (blend_fn) {
case 1: *d = kit__blend_pixel (*d, *s); break;
case 2: *d = kit__blend_pixel2(*d, *s, mul_color); break;
case 3: *d = kit__blend_pixel3(*d, *s, mul_color, add_color); break;
}
sx += stepx;
}
}
sy += stepy;
}
}
int kit_draw_text(kit_Context *ctx, kit_Color color, char *text, int x, int y) {
return kit_draw_text2(ctx, color, ctx->font, text, x, y);
}
int kit_draw_text2(kit_Context *ctx, kit_Color color, kit_Font *font, char *text, int x, int y) {
for (uint8_t *p = (void*) text; *p; p++) {
kit_Glyph g = font->glyphs[*p];
kit_draw_image2(ctx, color, font->image, x, y, g.rect);
x += g.xadv;
}
return x;
}
//////////////////////////////////////////////////////////////////////////////
// PNG loader | borrowed from tigr : https://github.com/erkkah/tigr
//////////////////////////////////////////////////////////////////////////////
typedef struct {
const unsigned char *p, *end;
} kit__Png;
typedef struct {
unsigned bits, count;
const unsigned char *in, *inend;
unsigned char *out, *outend;
jmp_buf jmp;
unsigned litcodes[288], distcodes[32], lencodes[19];
int tlit, tdist, tlen;
} kit__PngState;
#define FAIL() longjmp(s->jmp, 1)
#define CHECK(X) if (!(X)) { FAIL(); }
// Built-in DEFLATE standard tables.
static char kit__png_order[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static char kit__png_len_bits[29 + 2] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 };
static int kit__png_len_base[29 + 2] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 };
static char kit__png_dist_bits[30 + 2] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0 };
static int kit__png_dist_base[30 + 2] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 };
// Table to bit-reverse a byte.
static const unsigned char kit__png_reverse_table[256] = {
#define R2(n) n, n + 128, n + 64, n + 192
#define R4(n) R2(n), R2(n + 32), R2(n + 16), R2(n + 48)
#define R6(n) R4(n), R4(n + 8), R4(n + 4), R4(n + 12)
R6(0), R6(2), R6(1), R6(3)
};
#undef R2
#undef R4
#undef R6
static unsigned kit__png_rev16(unsigned n) {
return (kit__png_reverse_table[n & 0xff] << 8) | kit__png_reverse_table[(n >> 8) & 0xff];
}
static int kit__png_bits(kit__PngState* s, int n) {
int v = s->bits & ((1 << n) - 1);
s->bits >>= n;
s->count -= n;
while (s->count < 16) {
CHECK(s->in != s->inend);
s->bits |= (*s->in++) << s->count;
s->count += 8;
}
return v;
}
static unsigned char* kit__png_emit(kit__PngState* s, int len) {
s->out += len;
CHECK(s->out <= s->outend);
return s->out - len;
}
static void kit__png_copy(kit__PngState* s, const unsigned char* src, int len) {
unsigned char* dest = kit__png_emit(s, len);
while (len--) { *dest++ = *src++; }
}
static int kit__png_build(kit__PngState* s, unsigned* tree, unsigned char* lens, int symcount) {
int n, codes[16], first[16], counts[16] = { 0 };
// Frequency count.
for (n = 0; n < symcount; n++)
counts[lens[n]]++;
// Distribute codes.
counts[0] = codes[0] = first[0] = 0;
for (n = 1; n <= 15; n++) {
codes[n] = (codes[n - 1] + counts[n - 1]) << 1;
first[n] = first[n - 1] + counts[n - 1];
}
CHECK(first[15] + counts[15] <= symcount);
// Insert keys into the tree for each symbol.
for (n = 0; n < symcount; n++) {
int len = lens[n];
if (len != 0) {
int code = codes[len]++, slot = first[len]++;
tree[slot] = (code << (32 - len)) | (n << 4) | len;
}
}
return first[15];
}
static int kit__png_decode(kit__PngState* s, unsigned tree[], int max) {
// Find the next prefix code.
unsigned lo = 0, hi = max, key;
unsigned search = (kit__png_rev16(s->bits) << 16) | 0xffff;
while (lo < hi) {
unsigned guess = (lo + hi) / 2;
if (search < tree[guess]) {
hi = guess;
} else {
lo = guess + 1;
}
}
// Pull out the key and check it.
key = tree[lo - 1];
CHECK(((search ^ key) >> (32 - (key & 0xf))) == 0);
kit__png_bits(s, key & 0xf);
return (key >> 4) & 0xfff;
}
static void kit__png_run(kit__PngState* s, int sym) {
int length = kit__png_bits(s, kit__png_len_bits[sym]) + kit__png_len_base[sym];
int dsym = kit__png_decode(s, s->distcodes, s->tdist);
int offs = kit__png_bits(s, kit__png_dist_bits[dsym]) + kit__png_dist_base[dsym];
kit__png_copy(s, s->out - offs, length);
}
static void kit__png_block(kit__PngState* s) {
for (;;) {
int sym = kit__png_decode(s, s->litcodes, s->tlit);
if (sym < 256) { *kit__png_emit(s, 1) = (unsigned char)sym; } else
if (sym > 256) { kit__png_run(s, sym - 257); } else { break; }
}
}
static void kit__png_stored(kit__PngState* s) {
// Uncompressed data kit__png_block.
int len;
kit__png_bits(s, s->count & 7);
len = kit__png_bits(s, 16);
CHECK(((len ^ s->bits) & 0xffff) == 0xffff);
CHECK(s->in + len <= s->inend);
kit__png_copy(s, s->in, len);
s->in += len;
kit__png_bits(s, 16);
}
static void kit__png_fixed(kit__PngState* s) {
// Fixed set of Huffman codes.
int n;
unsigned char lens[288 + 32];
for (n = 0; n <= 143; n++) { lens[n] = 8; }
for (n = 144; n <= 255; n++) { lens[n] = 9; }
for (n = 256; n <= 279; n++) { lens[n] = 7; }
for (n = 280; n <= 287; n++) { lens[n] = 8; }
for (n = 0; n < 32; n++) { lens[288 + n] = 5; }
// Build lit/dist trees.
s->tlit = kit__png_build(s, s->litcodes, lens, 288);
s->tdist = kit__png_build(s, s->distcodes, lens + 288, 32);
}
static void kit__png_dynamic(kit__PngState* s) {
int n, i, nlit, ndist, nlen;
unsigned char lenlens[19] = { 0 }, lens[288 + 32];
nlit = 257 + kit__png_bits(s, 5);
ndist = 1 + kit__png_bits(s, 5);
nlen = 4 + kit__png_bits(s, 4);
for (n = 0; n < nlen; n++)
lenlens[(uint8_t) kit__png_order[n]] = (unsigned char)kit__png_bits(s, 3);
// Build the tree for decoding code lengths.
s->tlen = kit__png_build(s, s->lencodes, lenlens, 19);
// Decode code lengths.
for (n = 0; n < nlit + ndist;) {
int sym = kit__png_decode(s, s->lencodes, s->tlen);
switch (sym) {
case 16: for (i = 3 + kit__png_bits(s, 2); i; i--, n++) { lens[n] = lens[n - 1]; } break;
case 17: for (i = 3 + kit__png_bits(s, 3); i; i--, n++) { lens[n] = 0; } break;
case 18: for (i = 11 + kit__png_bits(s, 7); i; i--, n++) { lens[n] = 0; } break;
default: lens[n++] = (unsigned char)sym; break;
}
}
// Build lit/dist trees.
s->tlit = kit__png_build(s, s->litcodes, lens, nlit);
s->tdist = kit__png_build(s, s->distcodes, lens + nlit, ndist);
}
int kit__png_inflate(void* out, unsigned outlen, const void* in, unsigned inlen) {
int last;
kit__PngState state = {0};
kit__PngState *s = &state;
// We assume we can buffer 2 extra bytes from off the end of 'in'.
s->in = (unsigned char*)in;
s->inend = s->in + inlen + 2;
s->out = (unsigned char*)out;
s->outend = s->out + outlen;
s->bits = 0;
s->count = 0;
kit__png_bits(s, 0);
if (setjmp(s->jmp) == 1) { return 0; }
do {
last = kit__png_bits(s, 1);
switch (kit__png_bits(s, 2)) {
case 0: kit__png_stored(s); break;
case 1: kit__png_fixed(s); kit__png_block(s); break;
case 2: kit__png_dynamic(s); kit__png_block(s); break;
case 3: FAIL();
}
} while (!last);
return 1;
}
#undef CHECK
#undef FAIL
static unsigned kit__png_get32(const unsigned char* v) {
return (v[0] << 24) | (v[1] << 16) | (v[2] << 8) | v[3];
}
static const unsigned char* kit__png_find(kit__Png* png, const char* chunk, unsigned minlen) {
const unsigned char* start;
while (png->p < png->end) {
unsigned len = kit__png_get32(png->p + 0);
start = png->p;
png->p += len + 12;
if (memcmp(start + 4, chunk, 4) == 0 && len >= minlen && png->p <= png->end)
return start + 8;
}
return NULL;
}
static unsigned char kit__png_paeth(unsigned char a, unsigned char b, unsigned char c) {
int p = a + b - c;
int pa = abs(p - a), pb = abs(p - b), pc = abs(p - c);
return (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c;
}
static int kit__png_row_bytes(int w, int bipp) {
int rowBits = w * bipp;
return rowBits / 8 + ((rowBits % 8) ? 1 : 0);
}
static int kit__png_unfilter(int w, int h, int bipp, unsigned char* raw) {
int len = kit__png_row_bytes(w, bipp);
int bpp = kit__png_row_bytes(1, bipp);
int x, y;
unsigned char* first = (unsigned char*)malloc(len + 1);
memset(first, 0, len + 1);
unsigned char* prev = first;
for (y = 0; y < h; y++, prev = raw, raw += len) {
#define LOOP(A, B) \
for (x = 0; x < bpp; x++) \
raw[x] += A; \
for (; x < len; x++) \
raw[x] += B; \
break
switch (*raw++) {
case 0: break;
case 1: LOOP(0, raw[x - bpp]);
case 2: LOOP(prev[x], prev[x]);
case 3: LOOP(prev[x] / 2, (raw[x - bpp] + prev[x]) / 2);
case 4: LOOP(prev[x], kit__png_paeth(raw[x - bpp], prev[x], prev[x - bpp]));
default: return 0;
}
#undef LOOP
}
free(first);
return 1;
}
static void kit__png_convert(int bypp, int w, int h, const unsigned char* src, kit_Color* dest, const unsigned char* trns) {
int x, y;
for (y = 0; y < h; y++) {
src++; // skip filter byte
for (x = 0; x < w; x++, src += bypp) {
switch (bypp) {
case 1: {
unsigned char c = src[0];