aboutsummaryrefslogtreecommitdiff
path: root/plat.c
blob: ba88c24a0a0086407f6e0f9427dbb47c08db329e (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
#include "config.h"
#include "maths.h"
#include "memory.h"
#include "plat.h"

int btn_pressed(const App* a, Btn btn) {
	return a->btn_states[btn] & btn_state_pressed;
}

int btn_just_pressed(const App* a, Btn btn) {
	return a->btn_states[btn] & btn_state_just_pressed;
}

int btn_just_released(const App* a, Btn btn) {
	return a->btn_states[btn] & btn_state_just_released;
}

typedef struct {
	int x, y, w, h;
	unsigned col;
} Debug_Rect;

#define max_debug_rects 128
Debug_Rect debug_rects[max_debug_rects];
int debug_rect_count;

void ren_debug_rect(
	int x,
	int y,
	int w,
	int h,
	unsigned colour
) {
	Debug_Rect* r = &debug_rects[debug_rect_count++];
	assert(debug_rect_count < max_debug_rects);
	r->x = x;
	r->y = y;
	r->w = w;
	r->h = h;
	r->col = colour;
}

#ifdef plat_posix
#define _POSIX_SOURCE
#define _GNU_SOURCE

#include <fcntl.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <stdarg.h>
#include <stdio.h>

extern int isatty(int);
extern int fileno(FILE*);

int imp_assert(
	int val,
	const char* expr,
	const char* file,
	int line
) {
	if (!val) {
		print_err(
			"%d:%s: Assertion failed: %s.\n",
			line,
			file,
			expr
		);
		pbreak(error_assertion_failed);
		return 0;
	}
	return 1;
}

void print(const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);
	vfprintf(stdout, fmt, args);
	va_end(args);
}

void print_err(const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[31;31m");
	}

	vfprintf(stderr, fmt, args);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[0m");
	}

	va_end(args);
}

void print_war(const char* fmt, ...) {
	va_list args;
	va_start(args, fmt);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[31;35m");
	}

	vfprintf(stderr, fmt, args);

	if (isatty(fileno(stderr))) {
		fprintf(stderr, "\033[0m");
	}

	va_end(args);
}

void pbreak(Error code) {
#if defined(DEBUG) && defined(plat_x86)
	__asm__("int3;");
	(void)code;
#else
	exit(code);
#endif
}

static clockid_t global_clock;
static unsigned long global_freq;

void init_timer(void) {
	struct timespec ts;
	global_clock = CLOCK_REALTIME;
	global_freq = 1000000000;
#if defined(_POSIX_MONOTONIC_CLOCK)
	if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
		global_clock = CLOCK_MONOTONIC;
	}
#else
	(void)ts;
#endif
}

unsigned long get_timer(void) {
	struct timespec ts;
	clock_gettime(global_clock, &ts);
	return
		(unsigned long)ts.tv_sec * global_freq +
		(unsigned long)ts.tv_nsec;
}

void sleep_ns(unsigned long ns) {
	struct timespec t = { 0 };
	t.tv_nsec = ns;
	nanosleep(&t, &t);
}

void init_fps(FPS* f, int mpf) {
	f->now = get_timer();
	f->next = f->now;
	f->mpf = mpf;
	f->pt = 0;
	f->ct = -1;
}

void fps_begin(FPS* f) {
	f->now = get_timer();
}

void fps_end(FPS* f) {
	unsigned long ts = f->next - f->now;
	if (ts > 0) {
		sleep_ns(ts);
	}
}

void fps_update(FPS* f) {
	f->next += f->mpf * 1000000;
	f->pt = f->ct;
	f->ct = get_timer();
	f->fps = 1000000000 / (f->ct - f->pt);
}

extern int prog_init(Arena* m);
extern int prog_update(void);
extern int prog_deinit(void);

int main(int argc, const char** argv) {
	Arena a;
	void* mem = malloc(memory_size);
	int r;
	(void)argc;
	(void)argv;
	if (!mem) {
		print_err("Out of memory.\n");
		return error_out_of_memory;
	}
	init_timer();
	init_arena(
		&a,
		mem,
		memory_size
	);
	if ((r = prog_init(&a))) return r;
	for (r = 1; r; r = prog_update());
	prog_deinit();
	return error_none;
}

#endif


#ifdef plat_x11

#include <X11/Xlib.h>
#include <X11/Xutil.h>

typedef struct {
	unsigned char r, g, b, a;
} Colour;

typedef struct {
	Display* d;
	Window wi;
	GC gc;
	int w, h;
	int rmx, rmy;
	int omx, omy;
	int ms;
	unsigned long begin, end;
	XImage* bb;
	Colour* bbp;
	Atom wm_delete;
} App_Internal;

void init_rendering(
	App* a,
	App_Internal* i,
	XWindowAttributes* wa
) {
	Colour* p;
	int w = max_pc_window_w;
	int h = max_pc_window_h;
	a->fb = heap_alloc(
		a->heap,
		(viewport_w * viewport_h + 32) / 32 * sizeof *a->fb
	);
	p = malloc(sizeof *p * w * h);
	if (!p || !a->fb) {
		print_err("Out of memory.\n");
		pbreak(error_out_of_memory);
	}
	i->bb = XCreateImage(
		i->d,
		wa->visual,
		wa->depth,
		ZPixmap,
		0,
		(char*)p,
		w,
		h,
		32,
		w * sizeof *p
	);
	if (!i->bb) {
		print_err("Failed to create X11 backbuffer.\n");
		pbreak(error_platform_error);
	}
	i->bbp = p;
}

void init_window(App* a, App_Internal* i, const char* n) {
	Window root, w;
	Display* d;
	XWindowAttributes wa;
	unsigned rm, bm;
	i->bb = 0;
	i->bbp = 0;
	d = i->d;
	root = DefaultRootWindow(d);
	w = XCreateSimpleWindow(
		d,
		root,
		0,
		0,
		viewport_w * default_scale,
		viewport_h * default_scale,
		0,
		WhitePixel(d, 0),
		BlackPixel(d, 0)
	);
	i->wi = w;
	i->wm_delete = XInternAtom(
		d,
		"WM_DELETE_WINDOW",
		0
	);
	XSetWMProtocols(d, w, &i->wm_delete, 1);
	XStoreName(d, w, n);
	XSelectInput(
		d,
		w,
		ExposureMask      |
		KeyPressMask      |
		KeyReleaseMask    |
		PointerMotionMask |
		ButtonPressMask   |
		ButtonReleaseMask
	);
	XMapRaised(d, w);
	i->gc = XCreateGC(d, w, 0, 0);
	if (!i->gc) {
		print_err("Failed to create X graphics context.\n");
		pbreak(error_platform_error);
	}
	XGetWindowAttributes(d, w, &wa);
	if (wa.depth != 24 && wa.depth != 32) {
		print_err("Only true colour displays are supported.\n");
		pbreak(error_platform_error);
	}
	rm = wa.visual->red_mask  & 0x1000000;
	bm = wa.visual->blue_mask & 0xffffff;
	if ((rm == 0xff && bm == 0xff0000)) {
		print_war("Detected BGR. Colours will look fucked.\n");
	}
	init_rendering(a, i, &wa);
	i->w = wa.width;
	i->h = wa.height;
}

Btn btn_from_xkey(unsigned key) {
	switch (key) {
		case XK_Up:     return btn_up;
		case XK_Down:   return btn_down;
		case XK_Left:   return btn_left;
		case XK_Right:  return btn_right;
		case 0x78:      return btn_shoot;
		case 0x7a:      return btn_jump;
		case 0x63:      return btn_special;
		case XK_Return: return btn_start;
		default:        return btn_unknown;
	}
}

App* new_app(Heap* mem, const char* n) {
	App* a;
	App_Internal* i;
	a = heap_alloc(mem, sizeof *a + sizeof *i);
	i = (App_Internal*)(&a[1]);
	a->heap = mem;
	a->s = 2;
	a->o = 0;
	a->err = error_none;
	i->d = XOpenDisplay(0);
	i->omx = i->omy = 0;
	i->ms = 1;
	if (!i->d) {
		print_err("Failed to open X11 display.\n");
		pbreak(error_platform_error);
	}
	init_window(a, i, n);
	a->o = 1;
	return a;
}

void deinit_app(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	XDestroyImage(i->bb);
	XFreeGC(i->d, i->gc);
	XDestroyWindow(i->d, i->wi);
	XCloseDisplay(i->d);
	heap_free(a->heap, a);
}

void app_begin(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	Display* d = i->d;
	Window w = i->wi;
	int j;
	i->begin = get_timer();
	for (j = 0; j < btn_count; j++)
		a->btn_states[j] &= ~(
			btn_state_just_pressed | btn_state_just_released
		);
	while (XPending(d)) {
		XEvent e;
		XWindowAttributes wa;
		KeySym sym;
		Btn btn;
		XNextEvent(d, &e);
		switch (e.type) {
			case ClientMessage:
				if (
					(Atom)e.xclient.data.l[0] ==
					i->wm_delete
				) {
					a->o = 0;
				}
				break;
			case Expose:
				XGetWindowAttributes(d, w, &wa);
				i->w = mini(wa.width,  max_pc_window_w);
				i->h = mini(wa.height, max_pc_window_h);
				break;
			case KeyPress:
				sym = XLookupKeysym(&e.xkey, 0);
				btn = btn_from_xkey(sym);
				a->btn_states[btn] |=
					btn_state_pressed |
					btn_state_just_pressed;
				break;
			case KeyRelease:
				sym = XLookupKeysym(&e.xkey, 0);
				btn = btn_from_xkey(sym);
				a->btn_states[btn] &= ~btn_state_pressed;
				a->btn_states[btn] |= btn_state_just_released;
				break;
			default:
				break;
		}
	}
}

void app_rencpy(
	App* a,
	App_Internal* i,
	int sx,
	int sy,
	int s
) {
	const Colour white = { 0xff, 0xff, 0xff, 0xff };
	const Colour black = { 0x00, 0x00, 0x00, 0xff };
	int x, y, sj = 0;
	int w = viewport_w * s;
	int h = viewport_h * s;
	int ex = mini(sx + w, max_pc_window_w);
	int ey = mini(sy + h, max_pc_window_h);
	for (y = sy; y < ey; y++, sj++) {
		int sy = sj / s;
		int si = 0;
		for (x = sx; x < ex; x++, si++) {
			int sx = si / s;
			int idx = sx + sy * viewport_w;
			int bit = 1 << (idx  & 0x1f);
			bit &= a->fb[idx >> 5];
			i->bbp[x + y * max_pc_window_w] = bit? white: black;
		}
	}
	XPutImage(
		i->d,
		i->wi,
		i->gc,
		i->bb,
		sx, sy,
		sx, sy,
		w,  h
	);
#ifdef DEBUG
	for (sj = 0; sj < debug_rect_count; sj++) {
		const Debug_Rect* dr = &debug_rects[sj];
		XSetForeground(i->d, i->gc, dr->col);
		XFillRectangle(
			i->d,
			i->wi,
			i->gc,
			dr->x * s,
			dr->y * s,
		  dr->w * s,
		  dr->h * s
		 );
	}
#endif
	debug_rect_count = 0;
}

void app_end(App* a) {
	int s, x, y;
	App_Internal* i = (App_Internal*)(&a[1]);
	for (s = 1; viewport_w * s <= i->w && viewport_h * s <= i->h; s++);
	if (s > 1) s--;
	x = (i->w >> 1) - ((viewport_w * s) >> 1);
	y = (i->h >> 1) - ((viewport_h * s) >> 1);
	app_rencpy(a, i, x, y, s);
	i->end = get_timer();
	a->fps = 1000000000 / (i->end - i->begin);
}

#endif


#ifdef plat_pulse
#include "maths.h"
#define inline /* erm sir we are using C90 here... */
#include <stdlib.h>
#include <math.h>
#include <pulse/simple.h>
#include <pthread.h>

struct {
	short* buf;
	pa_simple* dev;
	int r, play, time;
	pthread_t worker;
	pthread_mutex_t mutex;
} audio;

void* audio_worker(void* arg) {
	const int s = audio_buffer_size;
	int i, c = 1;
	short* buf = audio.buf;
	pa_simple* dev = audio.dev;
	(void)arg;
	while (c) {
		pthread_mutex_lock(&audio.mutex);
		if (!audio.r) c = 0;
		for (
			i = 0;
			i < s && audio.play;
			i++, audio.play--, audio.time++
		) buf[i] = (short)(sin((double)audio.time / 0.05) * 16000.0);
		pthread_mutex_unlock(&audio.mutex);
		for (; i < s; i++) {
			buf[i] = 0;
		}
		pa_simple_write(dev, buf, s * sizeof(short), 0);
	}
	return 0;
}

void init_audio(void) {
	pa_sample_spec sp = { 0 };
	sp.format = PA_SAMPLE_S16LE;
	sp.channels = 1;
	sp.rate = audio_sample_rate;
	audio.dev = pa_simple_new(
		0,
		game_name,
		PA_STREAM_PLAYBACK,
		0,
		"Game Audio",
		&sp,
		0,
		0,
		0
	);
	audio.r = 0;
	audio.play = 0;
	if (!audio.dev) {
		print_err("Failed to create audio device.\n");
		print_war("Running without audio.\n");
		return;
	}
	audio.r = 1;
	audio.buf = malloc(
		audio_buffer_size *
		sizeof *audio.buf
	);
	pthread_mutex_init(&audio.mutex, 0);
	pthread_create(
		&audio.worker,
		0,
		audio_worker,
		0
	);
}

void deinit_audio(void) {
	if (audio.dev) {
		pthread_mutex_lock(&audio.mutex);
		audio.r = 0;
		pthread_mutex_unlock(&audio.mutex);
		pthread_mutex_destroy(&audio.mutex);
		pthread_join(audio.worker, 0);
		pa_simple_drain(audio.dev, 0);
		pa_simple_free(audio.dev);
		free(audio.buf);
	}
}

void play_sound(int len) {
	pthread_mutex_lock(&audio.mutex);
	audio.play += len;
	pthread_mutex_unlock(&audio.mutex);
}

#endif

#ifdef plat_sdl2

#if defined(plat_ems)
#include <emscripten.h>
#endif

#include <SDL2/SDL.h>
#include <stdio.h>
#include <string.h>

void print(const char* fmt, ...) {
	va_list a;
	va_start(a, fmt);
	SDL_LogMessageV(0, SDL_LOG_PRIORITY_INFO, fmt, a);
	va_end(a);
}

void print_err(const char* fmt, ...) {
	va_list a;
	va_start(a, fmt);
	SDL_LogMessageV(0, SDL_LOG_PRIORITY_ERROR, fmt, a);
	va_end(a);
}

void print_war(const char* fmt, ...) {
	va_list a;
	va_start(a, fmt);
	SDL_LogMessageV(0, SDL_LOG_PRIORITY_WARN, fmt, a);
	va_end(a);
}

int imp_assert(
	int val,
	const char* expr,
	const char* file,
	int line
) {
	if (!val) {
		print_err(
			"%d:%s: Assertion failed: %s.\n",
			line,
			file,
			expr
		);
		pbreak(error_assertion_failed);
		return 0;
	}
	return 1;
}

void pbreak(Error code) {
	(void)code;
	SDL_TriggerBreakpoint();
}

void init_fps(FPS* f, int mpf) {
	f->now = SDL_GetTicks();
	f->next = f->now;
	f->mpf = mpf;
	f->pt = 0;
	f->ct = -1;
}

void fps_begin(FPS* f) {
	f->now = SDL_GetTicks();
}

void fps_end(FPS* f) {
	unsigned long ts = f->next - f->now;
	if (ts > 0) {
		SDL_Delay(ts);
	}
}

void fps_update(FPS* f) {
	f->next += f->mpf;
	f->pt = f->ct;
	f->ct = SDL_GetTicks();
	f->fps = 1000 / (f->ct - f->pt);
}

extern int prog_init(Arena* m);
extern int prog_update(void);
extern void prog_deinit(void);

static void main_loop(void) {
#ifdef plat_ems
	prog_update();
#else
	int r;
	for (r = 1; r; r = prog_update());
	SDL_Quit();
#endif
}

int main(int argc, const char** argv) {
	Arena a;
	void* mem = malloc(memory_size);
	int r;
	(void)argc;
	(void)argv;
	if (!mem) {
		print_err("Out of memory.\n");
		return error_out_of_memory;
	}
	init_arena(
		&a,
		mem,
		memory_size
	);
	if ((r = prog_init(&a))) return r;
#ifdef plat_ems
	emscripten_set_main_loop(main_loop, 0, 1);
#else
	main_loop();
#endif
	prog_deinit();
	return 0;
}

Btn sdl_to_btn(const SDL_Event* e) {
	switch (e->key.keysym.sym) {
		case SDLK_z:
		case SDLK_RETURN:
			return btn_jump;
		case SDLK_x:
			return btn_shoot;
		case SDLK_c:
			return btn_special;
		case SDLK_LEFT:
		case SDLK_h:
			return btn_left;
		case SDLK_RIGHT:
		case SDLK_l:
			return btn_right;
		case SDLK_UP:
		case SDLK_k:
			return btn_up;
		case SDLK_DOWN:
		case SDLK_j:
			return btn_down;
		default: return btn_unknown;
	}
}

typedef struct {
	SDL_Window* wi;
	SDL_Renderer* re;
	SDL_Texture* bb;
	unsigned* bbp;
	int w, h;
} App_Internal;

void init_window(App* a, App_Internal* i, const char* n) {
	int flag = 0;
#ifndef plat_ems
	flag = SDL_WINDOW_RESIZABLE;
#endif
	SDL_CreateWindowAndRenderer(
		viewport_w * 2,
		viewport_h * 2,
		flag,
		&i->wi,
		&i->re
	);
	i->w = viewport_w * 2;
	i->h = viewport_h * 2;
	SDL_SetWindowTitle(i->wi, n);
	i->bb = SDL_CreateTexture(
		i->re,
		SDL_PIXELFORMAT_ABGR8888,
		SDL_TEXTUREACCESS_STREAMING,
		viewport_w,
		viewport_h
	);
	a->fb = heap_alloc(
		a->heap,
		(viewport_w * viewport_h + 32) / 32 * sizeof *a->fb
	);
}

App* new_app(struct Heap* mem, const char* n) {
	App* a;
	App_Internal* i;
	a = heap_alloc(mem, sizeof *a + sizeof *i);
	i = (App_Internal*)(&a[1]);
	a->heap = mem;
	a->s = 2;
	a->o = 0;
	a->err = error_none;
	init_window(a, i, n);
	a->o = 1;
	return a;
}

void deinit_app(App* a) {

}

void app_begin(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	SDL_Event e;
	int j;
	Btn btn;
	for (j = 0; j < btn_count; j++)
		a->btn_states[j] &= ~(
			btn_state_just_pressed | btn_state_just_released
		);
	while (SDL_PollEvent(&e)) {
		switch (e.type) {
			case SDL_QUIT:
				a->o = 0;
				break;
			case SDL_KEYDOWN:
				btn = sdl_to_btn(&e);
				a->btn_states[btn] |=
					btn_state_pressed |
					btn_state_just_pressed;
				break;
			case SDL_KEYUP:
				btn = sdl_to_btn(&e);
				a->btn_states[btn] &= ~btn_state_pressed;
				a->btn_states[btn] |= btn_state_just_released;
				break;
			case SDL_WINDOWEVENT:
				switch (e.window.event) {
					case SDL_WINDOWEVENT_RESIZED:
						i->w = e.window.data1;
						i->h = e.window.data2;
						break;
				}
				break;
			default: break;
		}
	}
}

void rencpy(App* a, unsigned* t, int p) {
	const unsigned white = 0xffffffff;
	const unsigned black = 0x00000000;
	int x, y, i = 0;
	p /= 4;
	for (y = 0; y < viewport_h; y++) {
		for (x = 0; x < viewport_w; x++, i++) {
			int bit = 1 << (i & 0x1f);
			bit &= a->fb[i >> 5];
			t[x + y * p] = bit? white: black;
		}
	}
}

void fit_dr(App_Internal* i, SDL_Rect* r) {
	int w = viewport_w, h = viewport_h, s;
	for (s = 1; w * s <= i->w && h * s <= i->h; s++);
	if (s > 1) s--;
	r->w = viewport_w * s;
	r->h = viewport_h * s;
	r->x = i->w / 2 - r->w / 2;
	r->y = i->h / 2 - r->h / 2;
}

void app_end(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	unsigned* target;
	SDL_Rect sr = { 0, 0, viewport_w, viewport_h };
	SDL_Rect dr = sr;
	int pitch;
	fit_dr((App_Internal*)&a[1], &dr);
	SDL_LockTexture(
		i->bb,
		0,
		(void**)&target,
		&pitch
	);
	rencpy(a, target, pitch);
	SDL_UnlockTexture(i->bb);
	SDL_RenderClear(i->re);
	SDL_RenderCopy(
		i->re,
		i->bb,
		&sr,
		&dr
	);
	SDL_RenderPresent(i->re);
}

static SDL_AudioSpec aud_spec;
int audio_len, audio_time;

void fill_audio(void *udata, Uint8 *stream, int len) {
	int i;
	int16_t* pcm = (int16_t*)stream;
	len /= 2;
	for (
		i = 0;
		i < len && audio_len;
		i++, audio_len--, audio_time++
	) pcm[i] = (int16_t)(sin((double)audio_time / 0.05) * 16000.0);
	for (; i < len; i++)
		pcm[i] = 0;
}

void init_audio(void) {
	audio_len = 0;
	audio_time = 0;
	aud_spec.freq = audio_sample_rate;
	aud_spec.format = AUDIO_S16;
	aud_spec.channels = 1;
#ifndef plat_ems
	aud_spec.samples = audio_buffer_size;
#else
	/* websites are retarded */
	aud_spec.samples = 1024;
#endif
	aud_spec.callback = fill_audio;
	aud_spec.userdata = 0;
	SDL_OpenAudio(&aud_spec, 0);
	SDL_PauseAudio(0);
}

void deinit_audio(void) {
	SDL_CloseAudio();
}

void play_sound(int len) {
	audio_len += len;
}

#endif

#ifdef plat_psv

#include <psp2/audioout.h>
#include <psp2/ctrl.h>
#include <psp2/display.h>
#include <psp2/kernel/processmgr.h>
#include <psp2/kernel/sysmem.h>
#include <psp2/kernel/threadmgr.h>
#include <psp2/libdbg.h>
#include <psp2common/kernel/modulemgr.h>

#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

#define psv_sw 960
#define psv_sh 544

typedef struct {
	unsigned* vram;
} App_Internal;

void panick(void) {
  while (1)
    *(int*)(0xAA) = 0x55; /* trigger coredump */
}

extern int vsnprintf(char*, size_t, const char*, va_list);

void print(const char* fmt, ...) {
	char buf[256];
	va_list a;
	va_start(a, fmt);
	vsnprintf(buf, sizeof buf, fmt, a);
	va_end(a);
	sceDbgLoggingHandler(
		"na",
		0,
		SCE_DBG_LOG_LEVEL_INFO,
		0,
		"%s",
		buf
	);
}

void print_err(const char* fmt, ...) {
	char buf[256];
	va_list a;
	va_start(a, fmt);
	vsnprintf(buf, sizeof buf, fmt, a);
	va_end(a);
	sceDbgLoggingHandler(
		"na",
		0,
		SCE_DBG_LOG_LEVEL_ERROR,
		0,
		"%s",
		buf
	);
}

void print_war(const char* fmt, ...) {
	char buf[256];
	va_list a;
	va_start(a, fmt);
	vsnprintf(buf, sizeof buf, fmt, a);
	va_end(a);
	sceDbgLoggingHandler(
		"na",
		0,
		SCE_DBG_LOG_LEVEL_WARNING,
		0,
		"%s",
		buf
	);
}

int imp_assert(
	int val,
	const char* expr,
	const char* file,
	int line
) {
	if (!val) {
		print_err(
			"%d:%s: Assertion failed: %s.\n",
			line,
			file,
			expr
		);
		pbreak(error_assertion_failed);
		return 0;
	}
	return 1;
}

void pbreak(Error code) {
	(void)code;
	__asm("bkpt 0x0");
}

extern int prog_init(Arena* m);
extern int prog_update(void);
extern void prog_deinit(void);

int main(void) {
	Arena a;
	void* mem = malloc(memory_size);
	int r;
	if (!mem) {
		print_err("Out of memory.\n");
		panick();
	}
	sceCtrlSetSamplingMode(SCE_CTRL_MODE_ANALOG);
	init_arena(
		&a,
		mem,
		memory_size
	);
	if ((r = prog_init(&a))) return r;
	for (r = 1; r; r = prog_update());
	prog_deinit();
	return 0;
}

void init_fps(FPS* f, int mpf) {
	f->now = sceKernelGetProcessTimeWide();
	f->next = f->now;
	f->mpf = mpf;
	f->pt = 0;
	f->ct = -1;
}

void fps_begin(FPS* f) {
	f->now = sceKernelGetProcessTimeWide();
}

void fps_end(FPS* f) {
	unsigned long ts = f->next - f->now;
	if (ts > 0) {
		sceKernelDelayThreadCB(ts);
	}
}

void fps_update(FPS* f) {
	f->next += f->mpf * 1000;
	f->pt = f->ct;
	f->ct = sceKernelGetProcessTimeWide();
	f->fps = 1000000 / (f->ct - f->pt);
}

void init_rendering(App* a, App_Internal* i) {
	SceUID db;
	SceDisplayFrameBuf fbc = { 0 };
	int r;
	a->fb = heap_alloc(
		a->heap,
		(viewport_w * viewport_h + 32) / 32 * sizeof *a->fb
	);
	db = sceKernelAllocMemBlock(
		"display",
		SCE_KERNEL_MEMBLOCK_TYPE_USER_CDRAM_RW,
		2 * 1024 * 1024,
		0
	);
	sceKernelGetMemBlockBase(
		db,
		(void**)&i->vram
	);
	fbc.size = sizeof fbc;
	fbc.base = i->vram;
	fbc.pitch = psv_sw;
	fbc.pixelformat = SCE_DISPLAY_PIXELFORMAT_A8B8G8R8;
	fbc.width = psv_sw;
	fbc.height = psv_sh;
	r = sceDisplaySetFrameBuf(
		&fbc,
		SCE_DISPLAY_SETBUF_NEXTFRAME
	);
	if (r < 0)
		panick();
}

App* new_app(struct Heap* mem, const char* n) {
	App* a;
	App_Internal* i;
	a = heap_alloc(mem, sizeof *a + sizeof *i);
	i = (App_Internal*)(&a[1]);
	(void)n;
	a->heap = mem;
	a->s = 2;
	a->o = 0;
	a->err = error_none;
	init_rendering(a, i);
	a->o = 1;
	return a;
}

void deinit_app(App* a) {
	(void)a;
}

int vita_btn_pressed(int b, const SceCtrlData* c) {
	switch (b) {
		case btn_jump:
			return c->buttons & SCE_CTRL_CROSS;
		case btn_shoot:
			return c->buttons & (SCE_CTRL_SQUARE | SCE_CTRL_RTRIGGER);
		case btn_special:
			return c->buttons & (SCE_CTRL_CIRCLE | SCE_CTRL_LTRIGGER);
		case btn_left:
			return
				c->buttons & SCE_CTRL_LEFT ||
				c->lx < 30;
		case btn_right:
			return
				c->buttons & SCE_CTRL_RIGHT ||
				c->lx > 230;
		case btn_up:
			return
				c->buttons & SCE_CTRL_UP ||
				c->ly < 30;
		case btn_down:
			return
				c->buttons & SCE_CTRL_DOWN ||
				c->ly > 230;
		default: return 0;
	}
}

void app_begin(App* a) {
	SceCtrlData ctrl;
	int j;
	sceCtrlPeekBufferPositive(0, &ctrl, 1);
	for (j = 0; j < btn_count; j++)
		a->btn_states[j] &= ~(
			btn_state_just_pressed | btn_state_just_released
		);
	for (j = 0; j < btn_count; j++) {
		int p = vita_btn_pressed(j, &ctrl);
		int ap = a->btn_states[j] & btn_state_pressed;
		if (p && !ap)
			a->btn_states[j] |=
				btn_state_just_pressed | btn_state_pressed;
		if (!p && ap) {
			a->btn_states[j] |= btn_state_just_released;
			a->btn_states[j] &= ~btn_state_pressed;
		}
	}
}

void app_rencpy(
	App* a,
	App_Internal* i,
	int sx,
	int sy,
	int s
) {
	const unsigned white = 0xffffffff;
	const unsigned black = 0xff000000;
	int x, y, sj = 0;
	int w = viewport_w * s;
	int h = viewport_h * s;
	int ex = mini(sx + w, psv_sw);
	int ey = mini(sy + h, psv_sh);
	for (y = sy; y < ey; y++, sj++) {
		int sy = sj / s;
		int si = 0;
		for (x = sx; x < ex; x++, si++) {
			int sx = si / s;
			int idx = sx + sy * viewport_w;
			int bit = 1 << (idx  & 0x1f);
			bit &= a->fb[idx >> 5];
			i->vram[x + y * psv_sw] = bit? white: black;
		}
	}
}

void app_end(App* a) {
	App_Internal* i = (App_Internal*)(&a[1]);
	app_rencpy(
		a,
		i,
		(psv_sw >> 1) - viewport_w,
		(psv_sh >> 1) - viewport_h,
		2
	);
}

#define psv_aud_bs (4096)
#define psv_aud_bc 8

struct {
	short* buf;
	int queue[psv_aud_bc];
	SceUID thr, mut;
	int r, bufi, time, p;
} aud;

static int audio_worker(SceSize argc, void* argv) {
	int r = 1;
	(void)argc;
	(void)argv;
	while (r) {
		int i;
		for (i = 0; i < psv_aud_bc; i++)
			if (aud.queue[i]) {
				short* b = aud.buf + psv_aud_bs * i;
				sceAudioOutOutput(aud.p, b);
				sceKernelLockMutex(aud.mut, 1, 0);
				aud.queue[i] = 0;
				sceKernelUnlockMutex(aud.mut, 1);
			}
		sceKernelLockMutex(aud.mut, 1, 0);
		r = aud.r;
		sceKernelUnlockMutex(aud.mut, 1);
	}
	sceKernelExitDeleteThread(0);
	return 0;
}

void init_audio(void) {
	int i;
	for (i = 0; i < psv_aud_bc; i++) {
		aud.queue[i] = 0;
	}
	aud.p = sceAudioOutOpenPort(
		SCE_AUDIO_OUT_PORT_TYPE_BGM,
		psv_aud_bs,
		8000,
		SCE_AUDIO_OUT_MODE_MONO
	);
	aud.r = 1;
	aud.bufi = 0;
	aud.time = 0;
	aud.thr = sceKernelCreateThread(
		"audio",
		audio_worker,
		0,
		0x2000,
		0,
		0,
		0
	);
	aud.mut = sceKernelCreateMutex(
		"audio mutex",
		0,
		0,
		0
	);
	sceKernelStartThread(
		aud.thr,
		0,
		0
	);
	aud.buf = malloc(psv_aud_bs * sizeof *aud.buf);
}

void deinit_audio(void) {
	free(aud.buf);
	aud.r = 0;
	sceKernelDeleteMutex(aud.mut);
}

void play_sound(int len) {
	int i;
	short* buf;
	sceKernelLockMutex(aud.mut, 1, 0);
	buf = aud.buf + aud.bufi * psv_aud_bs;
	aud.queue[aud.bufi] = 1;
	aud.bufi = (aud.bufi + 1) % psv_aud_bc;
	for (i = 0; i < len && i < psv_aud_bs; i++, aud.time++)
		buf[i] = (int16_t)(sin((double)aud.time / 0.05) * 16000.0);
	for (; i < psv_aud_bs; i++)
		buf[i] = 0;
	sceKernelUnlockMutex(aud.mut, 1);
}

#endif