summaryrefslogtreecommitdiff
path: root/meme/gui.c
blob: 758d6493a3ae622ed3581afa4628c2b827eaa600 (plain)
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
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
/* * gui.c - User interface
 *
 * Written 2014-2015 by Werner Almesberger
 * Copyright 2014-2015 by Werner Almesberger
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */


#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

#include "SDL.h"
#include "SDL_gfxPrimitives.h"

#include "util.h"
#include "time.h"
#include "mesh.h"
#include "overlay.h"
#include "plane.h"
#include "gaux.h"
#include "text.h"


#define	XRES		640
#define	YRES		480

#define	SDL_SURFACE	SDL_HWSURFACE

#define	CURSOR_R	5

#define	MARK_WIDTH	2
#define	MARK_LEN	20

#define	OVERLAY_WIDTH	4

#define	EDGE_RGBA	0x000000ff
#define	CURSOR_RGBA	0xff202080
#define	PROFILE_RGBA	0x2020ffff
#define	MARK_A_RGBA	0x00ff00ff
#define	MARK_B_RGBA	0x3030ffff
#define	CONTRAST_RGBA	0xffe080ff
#define	EQUAL_RGBA	0xf080ffff
#define	OVERLAY_RGBA	0xffc01060

#define	DEPTH_RANGE	0xc0
#define	DEPTH_OFFSET	0x30


static int x_orig, y_orig;
static Sint16 xres, yres;
static int x_min, x_max, y_min, y_max, z_min, z_max;
static int zoom;
static bool show_grid = 0;
static bool show_profiles = 0;
static bool show_overlay = 0;
static bool show_mesh = 1;
static const struct vertex *cursor;


/* ----- Coordinate transform ---------------------------------------------- */


static inline int x_model2screen(int x)
{
	return ((x-x_orig) >> zoom)+(xres >> 1);
}


static inline int y_model2screen(int y)
{
	return ((y-y_orig) >> zoom)+(yres >> 1);
}


static inline int x_screen2model(int x)
{
	return ((x - (xres >> 1)) << zoom)+x_orig;
}


static inline int y_screen2model(int y)
{
	return ((y - (yres >> 1)) << zoom)+y_orig;
}


static int coord(int x, int y, Sint16 *res_x, Sint16 *res_y)
{
	x = x_model2screen(x);
	y = y_model2screen(y);

	if (x < -32768 || x > 32767)
		return -1;
	if (y < -32768 || y > 32767)
		return -1;

	*res_x = x;
	*res_y = y;

	return x >= 0 && x < xres && y >= 0 && y < yres;
}


static inline int xz_z_model2screen(int z)
{
	/* center at cursor in lower 1/4 of screen */
	return yres-(yres >> 3) - ((z-cursor->z) >> zoom);
}


static int coord_xz(int x, int y, Sint16 *res_x, Sint16 *res_y, Sint16 ymin)
{
	x = x_model2screen(x);
	y = xz_z_model2screen(y);

	if (x < -32768 || x > 32767)
		return -1;
	if (y < -32768 || y > 32767)
		return -1;

	*res_x = x;
	*res_y = y;

	return x >= 0 && x < xres && y >= ymin && y < yres;
}


static inline int yz_z_model2screen(int z)
{
	/* center at cursor in right 1/4 of screen */
	return xres-(xres >> 3) - ((z-cursor->z) >> zoom);
}


static int coord_yz(int x, int y, Sint16 *res_x, Sint16 *res_y, Sint16 xmin)
{
	x = yz_z_model2screen(x);
	y = y_model2screen(y);

	if (x < -32768 || x > 32767)
		return -1;
	if (y < -32768 || y > 32767)
		return -1;

	*res_x = x;
	*res_y = y;

	return x >= xmin && x < xres && y >= 0 && y < yres;
}


/* ----- Depth gradient ---------------------------------------------------- */


static Uint32 *default_z_grad, *zoom_z_grad;
static const Uint32 *z_grad;


static void init_z_grad(void)
{
	int i;
	int div;
	uint8_t col;

	default_z_grad = calloc(3*(z_max-z_min)+1, sizeof(Uint32));
	div = 3*(z_max-z_min);
	for (i = 0; i <= 3*(z_max-z_min); i++) {
		col = i*DEPTH_RANGE/div + DEPTH_OFFSET;
		default_z_grad[i] = col * 0x1010100 + 0xff;
	}
	z_grad = default_z_grad;
}


static void calc_z_grad(int center, unsigned c_zoom)
{
	unsigned i;
	int col;
	uint8_t mid = DEPTH_RANGE >> 1;

	if (!zoom_z_grad)
		zoom_z_grad = calloc(3*(z_max-z_min)+1, sizeof(Uint32));
	for (i = 0; i <= 3*(z_max-z_min); i++) {
		col = ((int) i-center*3)/(1 << c_zoom)+mid;
		if (col < 0 || col >= DEPTH_RANGE)
			zoom_z_grad[i] = CONTRAST_RGBA;
		else
			zoom_z_grad[i] = (col+DEPTH_OFFSET) * 0x1010100 + 0xff;
	}
	z_grad = zoom_z_grad;
}


static void reset_z_grad(void)
{
	z_grad = default_z_grad;
}


/* ----- Contrast adjustment ----------------------------------------------- */


static bool contrast_mode = 0;
static int contrast_center;
static unsigned contrast_zoom = 1;


static void contrast_change(bool lower)
{
	if (cursor)
		contrast_center = cursor->z - z_min;
	if (lower) {
		/* limit zoom to 1/12 of the Z range */
		if (1 << contrast_zoom > (z_max-z_min)/4)
			return;
		contrast_zoom++;
	} else {
		if (contrast_zoom == 1)
			return;
		contrast_zoom--;
	}
	calc_z_grad(contrast_center, contrast_zoom);
}


static void begin_contrast(void)
{
	contrast_mode = 1;
	if (cursor)
		contrast_center = cursor->z - z_min;
	contrast_zoom = 1;
	while (DEPTH_RANGE << contrast_zoom < 3*(z_max-z_min))
		contrast_zoom++;
	calc_z_grad(contrast_center, contrast_zoom);
}


static void end_contrast(void)
{
	contrast_mode = 0;
	reset_z_grad();
}


/* ----- Equal height ------------------------------------------------------ */


static int equal = INT_MAX;


static void begin_equal(void)
{
	if (cursor)
		equal = cursor->z;
}


static void end_equal(void)
{
	equal = INT_MAX;
}


#include <assert.h>


/*
 * Draw line between sides AC and BC
 */

static void equal_line(SDL_Surface *s,
    const struct vertex *a, const struct vertex *b, const struct vertex *c,
    Sint16 xa, Sint16 ya, Sint16 xb, Sint16 yb, Sint16 xc, Sint16 yc)
{
	float fa, fb;

assert(a->z != c->z);
assert(b->z != c->z);
	fa = (float) (equal - c->z) / (a->z - c->z);
	fb = (float) (equal - c->z) / (b->z - c->z);

	aalineColor(s, xc+(xa-xc)*fa, yc+(ya-yc)*fa,
	    xc+(xb-xc)*fb, yc+(yb-yc)*fb, EQUAL_RGBA);
}


static inline bool between(int v, int a, int b)
{
	return (a <= v && b >= v) || (b <= v && a >= v);
}


/*
 * This duplicates a lot of things from surface_draw, but there doesn't seem
 * to be an easy way around that problem.
 */

static void equal_draw(SDL_Surface *s)
{
	const struct facet *f;
	Sint16 xa, ya, xb, yb, xc, yc;
	int a, b, c;
	bool ab, ac, bc;
	
	for (f = facets; f; f = f->next) {
		a = coord(f->v[0]->x, f->v[0]->y, &xa, &ya);
		if (a < 0)
			continue;
		b = coord(f->v[1]->x, f->v[1]->y, &xb, &yb);
		if (b < 0)
			continue;
		c = coord(f->v[2]->x, f->v[2]->y, &xc, &yc);
		if (c < 0)
			continue;
		if (!(a || b || c))
			continue;

		ab = f->v[0]->z == equal && f->v[1]->z == equal;
		ac = f->v[0]->z == equal && f->v[2]->z == equal;
		bc = f->v[1]->z == equal && f->v[2]->z == equal;

		if (ab && ac) {
			filledTrigonColor(s, xa, ya, xb, yb, xc, yc,
			    EQUAL_RGBA);
			continue;
		}
		if (ab) {
			aalineColor(s, xa, ya, xb, yb, EQUAL_RGBA);
			continue;
		}
		if (ac) {
			aalineColor(s, xa, ya, xc, yc, EQUAL_RGBA);
			continue;
		}
		if (bc) {
			aalineColor(s, xb, yb, xc, yc, EQUAL_RGBA);
			continue;
		}

		ab = between(equal, f->v[0]->z, f->v[1]->z);
		ac = between(equal, f->v[0]->z, f->v[2]->z);
		bc = between(equal, f->v[1]->z, f->v[2]->z);
		if (!(ab || ac || bc))
			continue;
		if (ac && bc) {
			equal_line(s, f->v[0], f->v[1], f->v[2],
			    xa, ya, xb, yb, xc, yc);
			continue;
		}
		if (ab && ac) {
			equal_line(s, f->v[1], f->v[2], f->v[0],
			    xb, yb, xc, yc, xa, ya);
			continue;
		}
		if (ab && bc) {
			equal_line(s, f->v[0], f->v[2], f->v[1],
			    xa, ya, xc, yc, xb, yb);
			continue;
		}
abort();
	}
}


/* ----- Draw the mesh ----------------------------------------------------- */


static void surface_draw(SDL_Surface *s)
{
	const struct facet *f;
	Sint16 xa, ya, xb, yb, xc, yc;
	int a, b, c;
	int z_off = z_min*3;
	
	for (f = facets; f; f = f->next) {
		a = coord(f->v[0]->x, f->v[0]->y, &xa, &ya);
		if (a < 0)
			continue;
		b = coord(f->v[1]->x, f->v[1]->y, &xb, &yb);
		if (b < 0)
			continue;
		c = coord(f->v[2]->x, f->v[2]->y, &xc, &yc);
		if (c < 0)
			continue;
		if (!(a || b || c))
			continue;
		filledTrigonColor(s, xa, ya, xb, yb, xc, yc,
		    z_grad[f->v[0]->z + f->v[1]->z + f->v[2]->z - z_off]);
	}
}


static bool edge_draw(const struct vertex *a, const struct vertex *b,
    void *user)
{
	SDL_Surface *s = user;
	Sint16 xa, ya, xb, yb;
	int res_a, res_b;

	res_a = coord(a->x, a->y, &xa, &ya);
	if (res_a < 0)
		return 0;
	res_b = coord(b->x, b->y, &xb, &yb);
	if (res_b < 0)
		return 0;
	if (!(res_a || res_b))
		return 0;
	aalineColor(s, xa, ya, xb, yb, EDGE_RGBA);
	return 0;
}


static void edges_draw(SDL_Surface *s)
{
	edge_foreach(edge_draw, s);
}


static void draw(SDL_Surface *s)
{
	SDL_FillRect(s, NULL, SDL_MapRGB(s->format, 0xff, 0xff, 0xff));
	if (show_mesh)
		surface_draw(s);
	if (show_grid)
		edges_draw(s);
	if (equal != INT_MAX)
		equal_draw(s);
}


/* ----- Backing store ----------------------------------------------------- */


static struct change {
	SDL_Surface *s;
	SDL_Rect r;
	struct change *prev;
	struct change *next;
} changes = {
	.prev = &changes,
	.next = &changes,
};


static void change(SDL_Surface *s, int x, int y, int w, int h)
{
	struct change *c;

	if (x < 0) {
		w += x;
		x = 0;
	}
	if (y < 0) {
		h += y;
		y = 0;
	}
	if (x+w >= xres)
		w = xres-x-1;
	if (y+h >= yres)
		h = yres-y-1;

	if (h <= 0 || w <= 0)
		return;

	c = alloc_type(struct change);
	c->s = sdl_surface(SDL_SURFACE, w, h);
	if (!c->s) {
		fprintf(stderr, "sdl_surface failed: %s\n", SDL_GetError());
		exit(1);
	}

	c->r.x = x;
	c->r.y = y;
	c->r.w = w;
	c->r.h = h;
	if (SDL_BlitSurface(s, &c->r, c->s, NULL)) {
		fprintf(stderr, "SDL_BlitSurface failed\n");
		exit(1);
	}

	/* append */
	c->next = &changes;
	c->prev = changes.prev;
	changes.prev->next = c;
	changes.prev = c;
}


static void apply_changes(SDL_Surface *s)
{
	const struct change *c;

	for (c = changes.next; c != &changes; c = c->next)
		SDL_UpdateRect(s, c->r.x, c->r.y, c->r.w, c->r.h);
}


static void no_changes(void)
{
	changes.next = &changes;
	changes.prev = &changes;
}


static void rollback_changes(SDL_Surface *s)
{
	struct change *c, *prev;

	for (c = changes.prev; c != &changes; c = prev) {
		prev = c->prev;
		if (SDL_BlitSurface(c->s, NULL, s, &c->r)) {
			fprintf(stderr, "SDL_BlitSurface failed\n");
			exit(1);
		}
		SDL_FreeSurface(c->s);
		SDL_UpdateRect(s, c->r.x, c->r.y, c->r.w, c->r.h);
		free(c);
	}
	no_changes();
}


static void discard_changes(void)
{
	struct change *c, *next;

	for (c = changes.next; c != &changes; c = next) {
		next = c->next;
		SDL_FreeSurface(c->s);
		free(c);
	}
	no_changes();
}


/* ----- Cursor handling --------------------------------------------------- */


static void hide_cursor(SDL_Surface *s)
{
	rollback_changes(s);
}


static void show_cursor(SDL_Surface *s, const struct vertex *v)
{
	int x = x_model2screen(v->x);
	int y = y_model2screen(v->y);

	change(s, x-CURSOR_R, y-CURSOR_R, 2*CURSOR_R+1, 2*CURSOR_R+1);
	change(s, 0, y, xres-1, 1);
	change(s, x, 0, 1, yres-1);
	SDL_LockSurface(s);
	aalineColor(s, 0, y, xres-1, y, CURSOR_RGBA);
	aalineColor(s, x, 0, x, yres-1, CURSOR_RGBA);
	filledCircleColor(s, x, y, CURSOR_R, CURSOR_RGBA);
	SDL_UnlockSurface(s);
}


/* ----- Profiles ---------------------------------------------------------- */


static void show_xz_profile(SDL_Surface *s)
{
	struct point *xz;
	unsigned n, i;
	Sint16 ymin;
	Sint16 xa = 0, ya = 0, xb = 0, yb = 0;
		/* initialize because gcc seems to "see" that they can be left
		   uninitialized by coord_xz but then fails to notice that
		   we track this via the return value. */
	int a, b;

	xz = plane_xz(cursor->y, &n);

	ymin = yres - (yres >> 2)-1;
	a = coord_xz(xz[0].x, xz[0].y, &xa, &ya, ymin);
	change(s, 0, ymin, xres, yres >> 2);
	SDL_LockSurface(s);
	for (i = 1; i < n; i++) {
		b = coord_xz(xz[i].x, xz[i].y, &xb, &yb, ymin);
		if (a >= 0 && b >= 0 && (a || b))
			aalineColor(s, xa, ya, xb, yb, PROFILE_RGBA);
		xa = xb;
		ya = yb;
		a = b;
	}
	aalineColor(s, 0, yres - (yres >> 3), xres-1, yres - (yres >> 3),
	    PROFILE_RGBA);
	SDL_UnlockSurface(s);

	free(xz);
}


static void show_yz_profile(SDL_Surface *s)
{
	struct point *yz;
	unsigned n, i;
	Sint16 xmin;
	Sint16 xa = 0, ya = 0, xb = 0, yb = 0;
		/* initialize because gcc seems to "see" that they can be left
		   uninitialized by coord_yz but then fails to notice that
		   we track this via the return value. */
	int a, b;

	yz = plane_yz(cursor->x, &n);

	xmin =  xres - (xres >> 2)-1;
	a = coord_yz(yz[0].x, yz[0].y, &xa, &ya, xmin);
	change(s, xmin, 0, xres >> 2, yres);
	SDL_LockSurface(s);
	for (i = 1; i < n; i++) {
		b = coord_yz(yz[i].x, yz[i].y, &xb, &yb, xmin);
		if (a >= 0 && b >= 0 && (a || b))
			aalineColor(s, xa, ya, xb, yb, PROFILE_RGBA);
		xa = xb;
		ya = yb;
		a = b;
	}
	aalineColor(s, xres - (xres >> 3), 0, xres - (xres >> 3), yres-1,
	    PROFILE_RGBA);
	SDL_UnlockSurface(s);

	free(yz);
}


/* ----- Find nearest vertex ----------------------------------------------- */


struct proximity {
	int x, y;
	const struct vertex *best;
	float best_d;
};


#if 0
static bool proximity_fn(const struct vertex *v, void *user)
{
	struct proximity *p = user;
	float d = hypotf(v->x - p->x, v->y - p->y);

	if (!p->best || d < p->best_d) {
		p->best_d = d;
		p->best = v;
	}
	return 0;
}

#else


static bool proximity_fn(const struct vertex *v, void *user)
{
	struct proximity *p = user;
	float d;

	if (p->best &&
	    (abs(v->x - p->x) >= p->best_d || abs(v->y - p->y) >= p->best_d))
		return 0;

	d = hypotf(v->x - p->x, v->y - p->y);
	if (p->best && d >= p->best_d)
		return 0;

	p->best_d = d;
	p->best = v;
	return 0;
}
#endif


static const struct vertex *find_nearest(int x, int y)
{
	struct proximity p = {
		.x	= x,
		.y	= y,
		.best	= NULL,
	};
//	struct time t;

//	time_start(&t);
	vertex_foreach_const(proximity_fn, &p);
//	time_stop(&t);
//	fprintf(stderr, "%.3f\t", time_ms(&t)/1000.0);
	return p.best;
}


/* ----- Add text change --------------------------------------------------- */


#include <stdarg.h>


static void text_change(SDL_Surface *s, int x, int y, const char *fmt, ...)
{
	SDL_Surface *t;
	SDL_Rect r;
	va_list ap;

	va_start(ap, fmt);
	t = vtextf(fmt, ap);
	va_end(ap);

	change(s, x, y, t->w, t->h);
	r.x = x;
	r.y = y;
	r.w = t->w;
	r.h = t->h;
	if (SDL_BlitSurface(t, NULL, s, &r)) {
		fprintf(stderr, "SDL_BlitSurface failed\n");
		exit(1);
	}
	SDL_FreeSurface(t);
}


/* ----- Markers ----------------------------------------------------------- */


static const struct vertex *mark_a, *mark_b;
static bool curr_mark;


static void show_marker(SDL_Surface *s, const struct vertex *v, Uint32 color)
{
	int x = x_model2screen(v->x);
	int y = y_model2screen(v->y);

	change(s, x-MARK_LEN, y-MARK_WIDTH, 2*MARK_LEN+1, 2*MARK_WIDTH+1);
	change(s, x-MARK_WIDTH, y-MARK_LEN, 2*MARK_WIDTH+1, 2*MARK_LEN+1);
	thickLineColor(s, x-MARK_LEN, y, x+MARK_LEN, y, MARK_WIDTH, color);
	thickLineColor(s, x, y-MARK_LEN, x, y+MARK_LEN, MARK_WIDTH, color);
}


static void show_meas(SDL_Surface *s, int x, int y,
    const struct vertex *a, const struct vertex *b,
    Uint32 color)
{
	float dx, dy, dz;

	dx = abs(a->x - b->x) / 1000.0;
	dy = abs(a->y - b->y) / 1000.0;
	dz = abs(a->z - b->z) / 1000.0;

#define	LS 12

	text_color(color);
	if (dx) {
		text_change(s, x, y, "X  %7.3f", dx);
		y += LS;
	}
	if (dy) {
		text_change(s, x, y, "Y  %7.3f", dy);
		y += LS;
	}
	if (dz) {
		text_change(s, x, y, "Z  %7.3f", dz);
		y += LS;
	}
	if (dx && dy) {
		text_change(s, x, y, "XY %7.3f", hypotf(dx, dy));
		y += LS;
	}
	if (dx && dz) {
		text_change(s, x, y, "XZ %7.3f", hypotf(dx, dz));
		y += LS;
	}
	if (dy && dz) {
		text_change(s, x, y, "YZ %7.3f", hypotf(dy, dz));
		y += LS;
	}
	if (dx && dy && dz) {
		text_change(s, x, y, "3D %7.3f", hypotf(hypotf(dx, dy), dz));
		y += LS;
	}
}


static void show_markers(SDL_Surface *s)
{
	if (mark_a)
		show_marker(s, mark_a, MARK_A_RGBA);
	if (mark_b)
		show_marker(s, mark_b, MARK_B_RGBA);
	if (mark_a && mark_b)
		show_meas(s, 10, 10, mark_a, mark_b, 0x000000ff);
}


static bool select_marker(const struct vertex *v)
{
	if (v == mark_a) {
		mark_a = NULL;
		curr_mark = 0;
		return 1;
	}
	if (v == mark_b) {
		mark_b = NULL;
		curr_mark = 1;
		return 1;
	}
	if (!mark_a && !mark_b) {
		curr_mark = 0;
		return 0;
	}
	if (mark_a && mark_b)
		return 0;
	if (mark_a)
		curr_mark = 1;
	else
		curr_mark = 0;
	return 0;
}


static void print_marker(FILE *file)
{
	double dx, dy, dz;

	fprintf(file, "%c:\tX  %.3f\tY  %.3f\tZ  %.3f\n",
	    curr_mark ? 'B' : 'A',
	    cursor->x/1000.0, cursor->y/1000.0, cursor->z/1000.0);
	if (!mark_a || !mark_b)
		return;

	dx = abs(mark_a->x - mark_b->x) / 1000.0;
	dy = abs(mark_a->y - mark_b->y) / 1000.0;
	dz = abs(mark_a->z - mark_b->z) / 1000.0;

	fprintf(file, "D:\tX  %.3f\tY  %.3f\tZ  %.3f\n", dx, dy, dz);
	fprintf(file, "  \tXY %.3f\tXZ %.3f\tYZ %.3f\n",
	    hypot(dx, dy), hypot(dx, dz), hypot(dy, dz));
	fprintf(file, "   \tXYZ %.3f\n", hypot(hypot(dx, dy), dz));
}


static void log_marker(const char *logfile)
{
	FILE *file;

	file = fopen(logfile, "a");
	if (!file) {
		perror(logfile);
		return;
	}
	print_marker(file);
	if (fclose(file) == EOF)
		perror(logfile);
}


static void set_marker(const struct vertex *v, const char *logfile)
{
	if (select_marker(v))
		return;

	if (curr_mark)
		mark_b = cursor;
	else
		mark_a = cursor;

	print_marker(stderr);
	if (logfile)
		log_marker(logfile);
}


static void clear_markers(void)
{
	mark_a = mark_b = NULL;
}


/* ----- Overlay ----------------------------------------------------------- */



static Sint16 ovl_x, ovl_y;
static int ovl_ok;


static void moveto(void *user, int x, int y)
{
	ovl_ok = coord(x, y, &ovl_x, &ovl_y);
}


static void lineto(void *user, int x, int y)
{
	SDL_Surface *s = user;
	Sint16 to_x = 0, to_y = 0; /* @@@ suppress warning */
	bool ok;

	ok = coord(x, y, &to_x, &to_y);
	if (ovl_ok >= 0 && ok >= 0 && (ovl_ok || ok))
		aalineColor(s, ovl_x, ovl_y, to_x, to_y,
		    OVERLAY_RGBA);
#if 0
	/*
	 * Something's wrong with thickLineColor. It places the lines with a
	 * substantial offset from the correct position, or even makes them
	 * veer off the screen.
	 */
		thickLineColor(s, ovl_x, ovl_y, to_x, to_y,
		    OVERLAY_WIDTH, OVERLAY_RGBA);
#endif
	ovl_x = to_x;
	ovl_y = to_y;
	ovl_ok = ok;
}


static void draw_overlay(SDL_Surface *s)
{
	overlay_draw(moveto, lineto, s);
}


/* ----- Last mouse position  ---------------------------------------------- */


static int mouse_x, mouse_y;


static void update_mouse_pos(Uint16 x, Uint16 y)
{
	mouse_x = x_screen2model(x);
	mouse_y = y_screen2model(y);
}


static void init_mouse_pos(void)
{
	mouse_x = (x_min+x_max)/2;
	mouse_y = (y_min+y_max)/2;
}


/* ----- Scaling ----------------------------------------------------------- */


static void auto_scale(void)
{
	x_orig = (x_min+x_max) >> 1;
	y_orig = (y_min+y_max) >> 1;

	for (zoom = 0; (x_max-x_min) >> zoom > xres*0.9 ||
	    (y_max-y_min) >> zoom > yres*0.9; zoom++);
}


static void zoom_in(int x, int y)
{
	if (contrast_mode) {
		contrast_change(0);
		return;
	}
	if (zoom == 1)
		return;
	zoom--;
	x_orig = (x_orig+x)/2;
	y_orig = (y_orig+y)/2;
}


static void zoom_out(int x, int y)
{
	if (contrast_mode) {
		contrast_change(1);
		return;
	}
	if (1 << (zoom+1) > x_max-x_min && 1 << (zoom+1) > y_max-y_min)
		return;
	zoom++;
	x_orig = 2*x_orig-x;
	y_orig = 2*y_orig-y;
}


/* ----- Event handling ---------------------------------------------------- */


static void motion_event(SDL_Surface *s, SDL_MouseMotionEvent *motion)
{
	int x = x_screen2model(motion->x);
	int y = y_screen2model(motion->y);

	if (cursor)
		hide_cursor(s);
	cursor = find_nearest(x, y);
	show_cursor(s, cursor);
	if (show_profiles) {
		show_xz_profile(s);
		show_yz_profile(s);
	}
	apply_changes(s);
}


static void button_event(SDL_MouseButtonEvent *button, const char *logfile)
{
	switch (button->button) {
	case 1:
		if (!cursor)
			break;
		set_marker(cursor, logfile);
		break;
	case 2:
		x_orig = mouse_x;
		y_orig = mouse_y;
		break;
	case 3:
		clear_markers();
		break;
	case 4: /* wheel forward */
		zoom_in(mouse_x, mouse_y);
		break;
	case 5: /* wheel backward */
		zoom_out(mouse_x, mouse_y);
		break;
	}
}


/* ----- Determine model extrema ------------------------------------------- */


static bool extrema_vertex(const struct vertex *v, void *user)
{
	bool *first = user;

	if (*first) {
		x_min = x_max = v->x;
		y_min = y_max = v->y;
		z_min = z_max = v->z;
		*first = 0;
	} else {
		if (x_min > v->x)
			x_min = v->x;
		if (x_max < v->x)
			x_max = v->x;
		if (y_min > v->y)
			y_min = v->y;
		if (y_max < v->y)
			y_max = v->y;
		if (z_min > v->z)
			z_min = v->z;
		if (z_max < v->z)
			z_max = v->z;
	}
	return 0;
}


static void extrema(void)
{
	bool first = 1;

	vertex_foreach_const(extrema_vertex, &first);
}


/* ----- Timers ------------------------------------------------------------ */


#include <time.h>
#include <sys/time.h>


static struct timer {
	struct timeval expires;
	struct timer *next;
	void (*fn)(void *user);
	void *user;
} *timers = NULL;


static void cancel_timer(const struct timer *t)
{
	struct timer **anchor;

	for (anchor = &timers; *anchor; anchor = &(*anchor)->next)
		if (*anchor == t) {
			*anchor = t->next;
			return;
		}
}


static int timeval_cmp(const struct timeval *a, const struct timeval *b)
{
	if (a->tv_sec < b->tv_sec)
		return -1;
	if (a->tv_sec > b->tv_sec)
		return 1;
	if (a->tv_usec < b->tv_usec)
		return -1;
	if (a->tv_usec > b->tv_usec)
		return 1;
	return 0;
}


static void start_timer(struct timer *t,
    void (*fn)(void *user), void *user, unsigned delta_ms)
{
	struct timer **anchor;

	cancel_timer(t);
	gettimeofday(&t->expires, NULL);

	t->expires.tv_usec += 1000*delta_ms;
	t->expires.tv_sec -= t->expires.tv_usec/1000000;
	t->expires.tv_usec %= 1000000;

	t->fn = fn;
	t->user = user;

	for (anchor = &timers;
	    *anchor && timeval_cmp(&t->expires, &(*anchor)->expires) >= 0;
	    anchor = &(*anchor)->next);
	t->next = *anchor;
	*anchor = t;
}


static void run_timers(void)
{
	struct timeval now;
	struct timer *t;

	while (timers) {
		gettimeofday(&now, NULL);
		if (timeval_cmp(&now, &timers->expires) < 0)
			return;
		t = timers;
		timers = t->next;
		t->fn(t->user);
	}
}


/* ----- Event polling ----------------------------------------------------- */


static void sdl_event(SDL_Event *ev)
{
	struct timespec ts = {
		.tv_sec = 0,
		.tv_nsec = 20*1000*1000, // 20 ms
	};

	while (1) {
		if (!timers) {
			SDL_WaitEvent(ev);
			return;
		}

		if (SDL_PollEvent(ev))
			return;
		run_timers();
		nanosleep(&ts, NULL);
	}
}


/* ----- Main loop --------------------------------------------------------- */


static struct motion {
	SDL_Surface *s;
	SDL_MouseMotionEvent event;
} motion;

static struct timer motion_timer;


static void delayed_motion(void *user)
{
	struct motion *m = user;

	motion_event(m->s, &m->event);
}


static bool event_loop(SDL_Surface **surf, const char *logfile)
{
	SDL_Surface *s = *surf;
	SDL_Event event;

	cancel_timer(&motion_timer);
	while (1) {
		sdl_event(&event);

		switch (event.type) {
		case SDL_MOUSEMOTION:
			update_mouse_pos(event.motion.x, event.motion.y);
			if (cursor)
				hide_cursor(s);
			show_markers(s);
			cursor = NULL;
			motion.s = s;
			motion.event = event.motion;
			start_timer(&motion_timer, delayed_motion, &motion,
			    50);
			break;
		case SDL_MOUSEBUTTONDOWN:
			update_mouse_pos(event.button.x, event.button.y);
			button_event(&event.button, logfile);
			return 0;
		case SDL_VIDEORESIZE:
			xres = event.resize.w;
			yres = event.resize.h;
			*surf = SDL_SetVideoMode(xres, yres, 0,
			    SDL_SURFACE | SDL_RESIZABLE);
			return 0;
		case SDL_KEYDOWN:
			switch (event.key.keysym.sym) {
			case SDLK_c:
				begin_contrast();
				return 0;
			case SDLK_e:
				begin_equal();
				return 0;
			case SDLK_g:
				show_grid = !show_grid;
				return 0;
			case SDLK_m:
				show_mesh = !show_mesh;
				return 0;
			case SDLK_o:
				show_overlay = !show_overlay;
				return 0;
			case SDLK_p:
				show_profiles = !show_profiles;
				return 0;
			case SDLK_q:
				return 1;
			default:
				break;
			}
			if (event.key.keysym.unicode & 0xFF80)
				break;
			switch (event.key.keysym.unicode) {
			case '*':
				auto_scale();
				return 0;
			case '+':
				zoom_in(mouse_x, mouse_y);
				return 0;
			case '-':
				zoom_out(mouse_x, mouse_y);
				return 0;
			}
			break;
		case SDL_KEYUP:
			switch (event.key.keysym.sym) {
			case SDLK_c:
				end_contrast();
				return 0;
			case SDLK_e:
				end_equal();
				return 0;
			default:
				break;
			}
			break;
		case SDL_QUIT:
			return 1;
		}
	}
	return 0;
}


void gui(const char *logfile)
{
	SDL_Surface *surf;

	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf(stderr, "SDL_init: %s\n", SDL_GetError());
		exit(1);
	}
	atexit(SDL_Quit);

	surf = SDL_SetVideoMode(XRES, YRES, 0, SDL_SURFACE | SDL_RESIZABLE);
	if (!surf) {
		fprintf(stderr, "SDL_SetVideoMode: %s\n", SDL_GetError());
		exit(1);
	}

	xres = surf->w;
	yres = surf->h;

	SDL_EnableUNICODE(1);

	extrema();
	init_mouse_pos();
	init_z_grad();
	auto_scale();

	while (1) {
struct time t;
		discard_changes();
		SDL_LockSurface(surf);
time_start(&t);
		draw(surf);
time_stop(&t);
fprintf(stderr, "%.3f s @ zoom %d\n", time_ms(&t)/1000.0, zoom);
		if (show_overlay)
			draw_overlay(surf);
		SDL_UnlockSurface(surf);
		SDL_UpdateRect(surf, 0, 0, 0, 0);

		show_markers(surf);
		if (cursor) {
			if (show_profiles) {
				show_xz_profile(surf);
				show_yz_profile(surf);
			}
			show_cursor(surf, cursor);
//			apply_changes(surf);
		}
		apply_changes(surf);

		if (event_loop(&surf, logfile))
			break;
	}
}