Files @ r6669:831ea297162a
Branch filter:

Location: cpp/openttd-patchpack/source/src/gfx.cpp

maedhros
(svn r9900) -Codechange: Separate the variables for how to highlight a land area and what to do with it afterwards.
   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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
/* $Id$ */

/** @file gfx.cpp */

#include "stdafx.h"
#include "openttd.h"
#include "functions.h"
#include "macros.h"
#include "spritecache.h"
#include "strings.h"
#include "string.h"
#include "gfx.h"
#include "table/palettes.h"
#include "table/sprites.h"
#include "hal.h"
#include "variables.h"
#include "table/control_codes.h"
#include "fontcache.h"
#include "genworld.h"
#include "debug.h"
#include "zoom.hpp"

#ifdef _DEBUG
bool _dbg_screen_rect;
#endif

byte _dirkeys;        ///< 1 = left, 2 = up, 4 = right, 8 = down
bool _fullscreen;
CursorVars _cursor;
bool _ctrl_pressed;   ///< Is Ctrl pressed?
bool _shift_pressed;  ///< Is Shift pressed?
byte _fast_forward;
bool _left_button_down;
bool _left_button_clicked;
bool _right_button_down;
bool _right_button_clicked;
DrawPixelInfo _screen;
bool _exit_game;
bool _networking;         ///< are we in networking mode?
byte _game_mode;
byte _pause_game;
int _pal_first_dirty;
int _pal_last_dirty;

Colour _cur_palette[256];
byte _stringwidth_table[FS_END][224];

enum BlitterMode {
	BM_NORMAL,
	BM_COLOUR_REMAP,
	BM_TRANSPARENT,
};

static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode);

FontSize _cur_fontsize;
static FontSize _last_fontsize;
static Pixel _cursor_backup[64 * 64];
static Rect _invalid_rect;
static const byte *_color_remap_ptr;
static byte _string_colorremap[3];

#define DIRTY_BYTES_PER_LINE (MAX_SCREEN_WIDTH / 64)
static byte _dirty_blocks[DIRTY_BYTES_PER_LINE * MAX_SCREEN_HEIGHT / 8];

void memcpy_pitch(void *dst, void *src, int w, int h, int srcpitch, int dstpitch)
{
	Pixel *dstp = (Pixel *)dst;
	Pixel *srcp = (Pixel *)src;

	assert(h >= 0);
	for (; h != 0; --h) {
		memcpy(dstp, srcp, w * sizeof(Pixel));
		dstp += dstpitch;
		srcp += srcpitch;
	}
}

void GfxScroll(int left, int top, int width, int height, int xo, int yo)
{
	const Pixel *src;
	Pixel *dst;
	int p;
	int ht;

	if (xo == 0 && yo == 0) return;

	if (_cursor.visible) UndrawMouseCursor();
	UndrawTextMessage();

	p = _screen.pitch;

	if (yo > 0) {
		/*Calculate pointers */
		dst = _screen.dst_ptr + (top + height - 1) * p + left;
		src = dst - yo * p;

		/* Decrease height and increase top */
		top += yo;
		height -= yo;
		assert(height > 0);

		/* Adjust left & width */
		if (xo >= 0) {
			dst += xo;
			left += xo;
			width -= xo;
		} else {
			src -= xo;
			width += xo;
		}

		for (ht = height; ht > 0; --ht) {
			memcpy(dst, src, width * sizeof(Pixel));
			src -= p;
			dst -= p;
		}
	} else {
		/* Calculate pointers */
		dst = _screen.dst_ptr + top * p + left;
		src = dst - yo * p;

		/* Decrese height. (yo is <=0). */
		height += yo;
		assert(height > 0);

		/* Adjust left & width */
		if (xo >= 0) {
			dst += xo;
			left += xo;
			width -= xo;
		} else {
			src -= xo;
			width += xo;
		}

		/* the y-displacement may be 0 therefore we have to use memmove,
		 * because source and destination may overlap */
		for (ht = height; ht > 0; --ht) {
			memmove(dst, src, width * sizeof(Pixel));
			src += p;
			dst += p;
		}
	}
	/* This part of the screen is now dirty. */
	_video_driver->make_dirty(left, top, width, height);
}


void GfxFillRect(int left, int top, int right, int bottom, int color)
{
	const DrawPixelInfo* dpi = _cur_dpi;
	Pixel *dst;
	const int otop = top;
	const int oleft = left;

	if (dpi->zoom != ZOOM_LVL_NORMAL) return;
	if (left > right || top > bottom) return;
	if (right < dpi->left || left >= dpi->left + dpi->width) return;
	if (bottom < dpi->top || top >= dpi->top + dpi->height) return;

	if ( (left -= dpi->left) < 0) left = 0;
	right = right - dpi->left + 1;
	if (right > dpi->width) right = dpi->width;
	right -= left;
	assert(right > 0);

	if ( (top -= dpi->top) < 0) top = 0;
	bottom = bottom - dpi->top + 1;
	if (bottom > dpi->height) bottom = dpi->height;
	bottom -= top;
	assert(bottom > 0);

	dst = dpi->dst_ptr + top * dpi->pitch + left;

	if (!HASBIT(color, PALETTE_MODIFIER_GREYOUT)) {
		if (!HASBIT(color, USE_COLORTABLE)) {
			do {
				memset(dst, color, right * sizeof(Pixel));
				dst += dpi->pitch;
			} while (--bottom);
		} else {
			/* use colortable mode */
			const byte* ctab = GetNonSprite(GB(color, 0, PALETTE_WIDTH)) + 1;

			do {
				int i;
				for (i = 0; i != right; i++) dst[i] = ctab[dst[i]];
				dst += dpi->pitch;
			} while (--bottom);
		}
	} else {
		byte bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
		do {
			int i;
			for (i = (bo ^= 1); i < right; i += 2) dst[i] = (byte)color;
			dst += dpi->pitch;
		} while (--bottom > 0);
	}
}

static void GfxSetPixel(int x, int y, int color)
{
	const DrawPixelInfo* dpi = _cur_dpi;
	if ((x -= dpi->left) < 0 || x >= dpi->width || (y -= dpi->top)<0 || y >= dpi->height)
		return;
	dpi->dst_ptr[y * dpi->pitch + x] = color;
}

void GfxDrawLine(int x, int y, int x2, int y2, int color)
{
	int dy;
	int dx;
	int stepx;
	int stepy;
	int frac;

	/* Check clipping first */
	{
		DrawPixelInfo *dpi = _cur_dpi;
		int t;

		if (x < dpi->left && x2 < dpi->left) return;

		if (y < dpi->top && y2 < dpi->top) return;

		t = dpi->left + dpi->width;
		if (x > t && x2 > t) return;

		t = dpi->top + dpi->height;
		if (y > t && y2 > t) return;
	}

	dy = (y2 - y) * 2;
	if (dy < 0) {
		dy = -dy;
		stepy = -1;
	} else {
		stepy = 1;
	}

	dx = (x2 - x) * 2;
	if (dx < 0) {
		dx = -dx;
		stepx = -1;
	} else {
		stepx = 1;
	}

	GfxSetPixel(x, y, color);
	if (dx > dy) {
		frac = dy - (dx >> 1);
		while (x != x2) {
			if (frac >= 0) {
				y += stepy;
				frac -= dx;
			}
			x += stepx;
			frac += dy;
			GfxSetPixel(x, y, color);
		}
	} else {
		frac = dx - (dy >> 1);
		while (y != y2) {
			if (frac >= 0) {
				x += stepx;
				frac -= dy;
			}
			y += stepy;
			frac += dx;
			GfxSetPixel(x, y, color);
		}
	}
}


/** Truncate a given string to a maximum width if neccessary.
 * If the string is truncated, add three dots ('...') to show this.
 * @param *str string that is checked and possibly truncated
 * @param maxw maximum width in pixels of the string
 * @return new width of (truncated) string */
static int TruncateString(char *str, int maxw)
{
	int w = 0;
	FontSize size = _cur_fontsize;
	int ddd, ddd_w;

	WChar c;
	char *ddd_pos;

	ddd_w = ddd = GetCharacterWidth(size, '.') * 3;

	for (ddd_pos = str; (c = Utf8Consume((const char **)&str)) != '\0'; ) {
		if (IsPrintable(c)) {
			w += GetCharacterWidth(size, c);

			if (w >= maxw) {
				/* string got too big... insert dotdotdot */
				ddd_pos[0] = ddd_pos[1] = ddd_pos[2] = '.';
				ddd_pos[3] = '\0';
				return ddd_w;
			}
		} else {
			if (c == SCC_SETX) str++;
			else if (c == SCC_SETXY) str += 2;
			else if (c == SCC_TINYFONT) {
				size = FS_SMALL;
				ddd = GetCharacterWidth(size, '.') * 3;
			} else if (c == SCC_BIGFONT) {
				size = FS_LARGE;
				ddd = GetCharacterWidth(size, '.') * 3;
			}
		}

		/* Remember the last position where three dots fit. */
		if (w + ddd < maxw) {
			ddd_w = w + ddd;
			ddd_pos = str;
		}
	}

	return w;
}

static inline int TruncateStringID(StringID src, char *dest, int maxw, const char* last)
{
	GetString(dest, src, last);
	return TruncateString(dest, maxw);
}

/* returns right coordinate */
int DrawString(int x, int y, StringID str, uint16 color)
{
	char buffer[512];

	GetString(buffer, str, lastof(buffer));
	return DoDrawString(buffer, x, y, color);
}

int DrawStringTruncated(int x, int y, StringID str, uint16 color, uint maxw)
{
	char buffer[512];
	TruncateStringID(str, buffer, maxw, lastof(buffer));
	return DoDrawString(buffer, x, y, color);
}


int DrawStringRightAligned(int x, int y, StringID str, uint16 color)
{
	char buffer[512];
	int w;

	GetString(buffer, str, lastof(buffer));
	w = GetStringBoundingBox(buffer).width;
	DoDrawString(buffer, x - w, y, color);

	return w;
}

void DrawStringRightAlignedTruncated(int x, int y, StringID str, uint16 color, uint maxw)
{
	char buffer[512];

	TruncateStringID(str, buffer, maxw, lastof(buffer));
	DoDrawString(buffer, x - GetStringBoundingBox(buffer).width, y, color);
}

void DrawStringRightAlignedUnderline(int x, int y, StringID str, uint16 color)
{
	int w = DrawStringRightAligned(x, y, str, color);
	GfxFillRect(x - w, y + 10, x, y + 10, _string_colorremap[1]);
}


int DrawStringCentered(int x, int y, StringID str, uint16 color)
{
	char buffer[512];
	int w;

	GetString(buffer, str, lastof(buffer));

	w = GetStringBoundingBox(buffer).width;
	DoDrawString(buffer, x - w / 2, y, color);

	return w;
}

int DrawStringCenteredTruncated(int xl, int xr, int y, StringID str, uint16 color)
{
	char buffer[512];
	int w = TruncateStringID(str, buffer, xr - xl, lastof(buffer));
	return DoDrawString(buffer, (xl + xr - w) / 2, y, color);
}

int DoDrawStringCentered(int x, int y, const char *str, uint16 color)
{
	int w = GetStringBoundingBox(str).width;
	DoDrawString(str, x - w / 2, y, color);
	return w;
}

void DrawStringCenterUnderline(int x, int y, StringID str, uint16 color)
{
	int w = DrawStringCentered(x, y, str, color);
	GfxFillRect(x - (w >> 1), y + 10, x - (w >> 1) + w, y + 10, _string_colorremap[1]);
}

void DrawStringCenterUnderlineTruncated(int xl, int xr, int y, StringID str, uint16 color)
{
	int w = DrawStringCenteredTruncated(xl, xr, y, str, color);
	GfxFillRect((xl + xr - w) / 2, y + 10, (xl + xr + w) / 2, y + 10, _string_colorremap[1]);
}

/** 'Correct' a string to a maximum length. Longer strings will be cut into
 * additional lines at whitespace characters if possible. The string parameter
 * is modified with terminating characters mid-string which are the
 * placeholders for the newlines.
 * The string WILL be truncated if there was no whitespace for the current
 * line's maximum width.
 *
 * @note To know if the terminating '\0' is the string end or just a
 * newline, the returned 'num' value should be consulted. The num'th '\0',
 * starting with index 0 is the real string end.
 *
 * @param str string to check and correct for length restrictions
 * @param maxw the maximum width the string can have on one line
 * @return return a 32bit wide number consisting of 2 packed values:
 *  0 - 15 the number of lines ADDED to the string
 * 16 - 31 the fontsize in which the length calculation was done at */
uint32 FormatStringLinebreaks(char *str, int maxw)
{
	FontSize size = _cur_fontsize;
	int num = 0;

	assert(maxw > 0);

	for (;;) {
		char *last_space = NULL;
		int w = 0;

		for (;;) {
			WChar c = Utf8Consume((const char **)&str);
			/* whitespace is where we will insert the line-break */
			if (IsWhitespace(c)) last_space = str;

			if (IsPrintable(c)) {
				w += GetCharacterWidth(size, c);
				/* string is longer than maximum width so we need to decide what to
				 * do. We can do two things:
				 * 1. If no whitespace was found at all up until now (on this line) then
				 *    we will truncate the string and bail out.
				 * 2. In all other cases force a linebreak at the last seen whitespace */
				if (w > maxw) {
					if (last_space == NULL) {
						*Utf8PrevChar(str) = '\0';
						return num + (size << 16);
					}
					str = last_space;
					break;
				}
			} else {
				switch (c) {
					case '\0': return num + (size << 16); break;
					case SCC_SETX:  str++; break;
					case SCC_SETXY: str += 2; break;
					case SCC_TINYFONT: size = FS_SMALL; break;
					case SCC_BIGFONT:  size = FS_LARGE; break;
					case '\n': goto end_of_inner_loop;
				}
			}
		}
end_of_inner_loop:
		/* String didn't fit on line (or a '\n' was encountered), so 'dummy' terminate
		 * and increase linecount. We use Utf8PrevChar() as also non 1 char long
		 * whitespace seperators are supported */
		num++;
		char *s = Utf8PrevChar(str);
		*s++ = '\0';

		/* In which case (see above) we will shift remainder to left and close the gap */
		if (str - s >= 1) {
			for (; str[-1] != '\0';) *s++ = *str++;
		}
	}
}

/** Draw a given string with the centre around the given x coordinates
 * @param x Centre the string around this pixel width
 * @param y Draw the string at this pixel height (first line's bottom)
 * @param str String to draw
 * @param maxw Maximum width the string can have before it is wrapped */
void DrawStringMultiCenter(int x, int y, StringID str, int maxw)
{
	char buffer[512];
	uint32 tmp;
	int num, w, mt;
	const char *src;
	WChar c;

	GetString(buffer, str, lastof(buffer));

	tmp = FormatStringLinebreaks(buffer, maxw);
	num = GB(tmp, 0, 16);

	mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));

	y -= (mt >> 1) * num;

	src = buffer;

	for (;;) {
		w = GetStringBoundingBox(src).width;
		DoDrawString(src, x - (w >> 1), y, 0xFE);
		_cur_fontsize = _last_fontsize;

		for (;;) {
			c = Utf8Consume(&src);
			if (c == 0) {
				y += mt;
				if (--num < 0) {
					_cur_fontsize = FS_NORMAL;
					return;
				}
				break;
			} else if (c == SCC_SETX) {
				src++;
			} else if (c == SCC_SETXY) {
				src += 2;
			}
		}
	}
}


uint DrawStringMultiLine(int x, int y, StringID str, int maxw, int maxh)
{
	char buffer[512];
	uint32 tmp;
	int num, mt;
	uint total_height;
	const char *src;
	WChar c;

	GetString(buffer, str, lastof(buffer));

	tmp = FormatStringLinebreaks(buffer, maxw);
	num = GB(tmp, 0, 16);

	mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
	total_height = (num + 1) * mt;

	if (maxh != -1 && (int)total_height > maxh) {
		/* Check there's room enough for at least one line. */
		if (maxh < mt) return 0;

		num = maxh / mt - 1;
		total_height = (num + 1) * mt;
	}

	src = buffer;

	for (;;) {
		DoDrawString(src, x, y, 0xFE);
		_cur_fontsize = _last_fontsize;

		for (;;) {
			c = Utf8Consume(&src);
			if (c == 0) {
				y += mt;
				if (--num < 0) {
					_cur_fontsize = FS_NORMAL;
					return total_height;
				}
				break;
			} else if (c == SCC_SETX) {
				src++;
			} else if (c == SCC_SETXY) {
				src += 2;
			}
		}
	}
}

/** Return the string dimension in pixels. The height and width are returned
 * in a single BoundingRect value. TINYFONT, BIGFONT modifiers are only
 * supported as the first character of the string. The returned dimensions
 * are therefore a rough estimation correct for all the current strings
 * but not every possible combination
 * @param str string to calculate pixel-width
 * @return string width and height in pixels */
BoundingRect GetStringBoundingBox(const char *str)
{
	FontSize size = _cur_fontsize;
	BoundingRect br;
	int max_width;
	WChar c;

	br.width = br.height = max_width = 0;
	for (;;) {
		c = Utf8Consume(&str);
		if (c == 0) break;
		if (IsPrintable(c)) {
			br.width += GetCharacterWidth(size, c);
		} else {
			switch (c) {
				case SCC_SETX: br.width += (byte)*str++; break;
				case SCC_SETXY:
					br.width += (byte)*str++;
					br.height += (byte)*str++;
					break;
				case SCC_TINYFONT: size = FS_SMALL; break;
				case SCC_BIGFONT:  size = FS_LARGE; break;
				case '\n':
					br.height += GetCharacterHeight(size);
					if (br.width > max_width) max_width = br.width;
					br.width = 0;
					break;
			}
		}
	}
	br.height += GetCharacterHeight(size);

	br.width  = max(br.width, max_width);
	return br;
}

/** Draw a string at the given coordinates with the given colour
 * @param string the string to draw
 * @param x offset from left side of the screen, if negative offset from the right side
 * @param y offset from top side of the screen, if negative offset from the bottom
 * @param real_color colour of the string, see _string_colormap in
 * table/palettes.h or docs/ottd-colourtext-palette.png
 * @return the x-coordinates where the drawing has finished. If nothing is drawn
 * the originally passed x-coordinate is returned */
int DoDrawString(const char *string, int x, int y, uint16 real_color)
{
	DrawPixelInfo *dpi = _cur_dpi;
	FontSize size = _cur_fontsize;
	WChar c;
	byte color;
	int xo = x, yo = y;

	color = real_color & 0xFF;

	if (color != 0xFE) {
		if (x >= dpi->left + dpi->width ||
				x + _screen.width * 2 <= dpi->left ||
				y >= dpi->top + dpi->height ||
				y + _screen.height <= dpi->top)
					return x;

		if (color != 0xFF) {
switch_color:;
			if (real_color & IS_PALETTE_COLOR) {
				_string_colorremap[1] = color;
				_string_colorremap[2] = _use_dos_palette ? 1 : 215;
			} else {
				uint palette = _use_dos_palette ? 1 : 0;
				_string_colorremap[1] = _string_colormap[palette][color].text;
				_string_colorremap[2] = _string_colormap[palette][color].shadow;
			}
			_color_remap_ptr = _string_colorremap;
		}
	}

check_bounds:
	if (y + 19 <= dpi->top || dpi->top + dpi->height <= y) {
skip_char:;
		for (;;) {
			c = Utf8Consume(&string);
			if (!IsPrintable(c)) goto skip_cont;
		}
	}

	for (;;) {
		c = Utf8Consume(&string);
skip_cont:;
		if (c == 0) {
			_last_fontsize = size;
			return x;
		}
		if (IsPrintable(c)) {
			if (x >= dpi->left + dpi->width) goto skip_char;
			if (x + 26 >= dpi->left) {
				GfxMainBlitter(GetGlyph(size, c), x, y, BM_COLOUR_REMAP);
			}
			x += GetCharacterWidth(size, c);
		} else if (c == '\n') { // newline = {}
			x = xo;
			y += GetCharacterHeight(size);
			goto check_bounds;
		} else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change color?
			color = (byte)(c - SCC_BLUE);
			goto switch_color;
		} else if (c == SCC_SETX) { // {SETX}
			x = xo + (byte)*string++;
		} else if (c == SCC_SETXY) {// {SETXY}
			x = xo + (byte)*string++;
			y = yo + (byte)*string++;
		} else if (c == SCC_TINYFONT) { // {TINYFONT}
			size = FS_SMALL;
		} else if (c == SCC_BIGFONT) { // {BIGFONT}
			size = FS_LARGE;
		} else {
			DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
		}
	}
}

int DoDrawStringTruncated(const char *str, int x, int y, uint16 color, uint maxw)
{
	char buffer[512];
	ttd_strlcpy(buffer, str, sizeof(buffer));
	TruncateString(buffer, maxw);
	return DoDrawString(buffer, x, y, color);
}

void DrawSprite(SpriteID img, SpriteID pal, int x, int y)
{
	if (HASBIT(img, PALETTE_MODIFIER_TRANSPARENT)) {
		_color_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH)) + 1;
		GfxMainBlitter(GetSprite(GB(img, 0, SPRITE_WIDTH)), x, y, BM_TRANSPARENT);
	} else if (pal != PAL_NONE) {
		_color_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH)) + 1;
		GfxMainBlitter(GetSprite(GB(img, 0, SPRITE_WIDTH)), x, y, BM_COLOUR_REMAP);
	} else {
		GfxMainBlitter(GetSprite(GB(img, 0, SPRITE_WIDTH)), x, y, BM_NORMAL);
	}
}

struct BlitterParams {
	int start_x, start_y;
	const byte *sprite;
	Pixel *dst;
	BlitterMode mode;
	int width, height;
	int width_org;
	int pitch;
};

static void GfxBlitZoomUncomp(BlitterParams *bp, ZoomLevel zoom)
{
	const byte *src = bp->sprite;
	Pixel *dst = bp->dst;
	int height = bp->height;
	int width = bp->width;
	int i;

	assert(height > 0);
	assert(width > 0);

	height = UnScaleByZoom(height, zoom);

	switch (bp->mode) {
		case BM_COLOUR_REMAP: {
			const byte *ctab = _color_remap_ptr;

			for (; height != 0; height--) {
				for (i = 0; i != UnScaleByZoom(width, zoom); i++) {
					byte b = ctab[src[ScaleByZoom(i, zoom)]];

					if (b != 0) dst[i] = b;
				}
				src += ScaleByZoom(bp->width_org, zoom);
				dst += bp->pitch;
			}
			break;
		}

		case BM_TRANSPARENT: {
			const byte *ctab = _color_remap_ptr;

			for (; height != 0; height--) {
				for (i = 0; i != UnScaleByZoom(width, zoom); i++)
					if (src[ScaleByZoom(i, zoom)] != 0) dst[i] = ctab[dst[i]];
				src += ScaleByZoom(bp->width_org, zoom);
				dst += bp->pitch;
			}
			break;
		}

		default:
			for (; height != 0; height--) {
				for (i = 0; i != UnScaleByZoom(width, zoom); i++)
					if (src[ScaleByZoom(i, zoom)] != 0) dst[i] = src[ScaleByZoom(i, zoom)];
				src += ScaleByZoom(bp->width_org, zoom);
				dst += bp->pitch;
			}
			break;
	}
}

static void GfxBlitTileZoom(BlitterParams *bp, ZoomLevel zoom)
{
	const byte *src_o = bp->sprite;
	const byte *src;
	int num, skip;
	byte done;
	Pixel *dst;
	const byte *ctab;

	src_o += ReadLE16Aligned(src_o + bp->start_y * 2);

	for (;;) {
		do {
			done = src_o[0];
			num = done & 0x7F;
			skip = src_o[1];
			src = src_o + 2;
			src_o += num + 2;

			dst = bp->dst;

			if (zoom >= ZOOM_LVL_OUT_2X && (skip & 1)) {
				skip += 1;
				src += 1;
				num -= 1;
				if (num <= 0) continue;
			}

			if (zoom >= ZOOM_LVL_OUT_4X && (skip & 2)) {
				skip += 2;
				src += 2;
				num -= 2;
				if (num <= 0) continue;
			}

			if (zoom >= ZOOM_LVL_OUT_8X && (skip & 4)) {
				skip += 4;
				src += 4;
				num -= 4;
				if (num <= 0) continue;
			}

			if (zoom >= ZOOM_LVL_OUT_16X && (skip & 8)) {
				skip += 8;
				src += 8;
				num -= 8;
				if (num <= 0) continue;
			}

			if ( (skip -= bp->start_x) > 0) {
				dst += UnScaleByZoom(skip, zoom);
			} else {
				src -= skip;
				num += skip;
				if (num <= 0) continue;
				skip = 0;
			}

			skip = skip + num - bp->width;
			if (skip > 0) {
				num -= skip;
				if (num <= 0) continue;
			}

			num = UnScaleByZoom(num + ScaleByZoom(1, zoom) - 1, zoom);

			switch (bp->mode) {
				case BM_COLOUR_REMAP:
					ctab = _color_remap_ptr;
					for (; num != 0; num--) {
							*dst = ctab[*src];
							dst++;
							src += ScaleByZoom(1, zoom);
					}
					break;

				case BM_TRANSPARENT:
					ctab = _color_remap_ptr;
					for (; num != 0; num--) {
							*dst = ctab[*dst];
							dst++;
					}
					break;

				default:
					for (; num != 0; num--) {
							*dst = *src;
							dst++;
							src += ScaleByZoom(1, zoom);
					}
					break;
			}


		} while (!(done & 0x80));

		bp->dst += bp->pitch;
		if (--bp->height == 0) return;

		for (int i = 0; i < ScaleByZoom(1, zoom) - 1; i++) {
			do {
				done = src_o[0];
				src_o += (done & 0x7F) + 2;
			} while (!(done & 0x80));
			if (--bp->height == 0) return;
		}
	}
}

static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode)
{
	const DrawPixelInfo *dpi = _cur_dpi;
	int start_x, start_y;
	BlitterParams bp;
	int zoom_mask = ~(ScaleByZoom(1, dpi->zoom) - 1);

	/* decode sprite header */
	x += sprite->x_offs;
	y += sprite->y_offs;
	bp.width_org = bp.width = sprite->width;
	bp.height = sprite->height;
	bp.sprite = sprite->data;
	bp.dst = dpi->dst_ptr;
	bp.mode = mode;
	bp.pitch = dpi->pitch;

	assert(bp.height > 0);
	assert(bp.width > 0);

	if (sprite->info & 8) {
		/* tile blit */
		start_y = 0;

		if (dpi->zoom > ZOOM_LVL_NORMAL) {
			start_y += bp.height & ~zoom_mask;
			bp.height &= zoom_mask;
			if (bp.height == 0) return;
			y &= zoom_mask;
		}

		if ( (y -= dpi->top) < 0) {
			bp.height += y;
			if (bp.height <= 0) return;
			start_y -= y;
			y = 0;
		} else {
			bp.dst += bp.pitch * UnScaleByZoom(y, dpi->zoom);
		}
		bp.start_y = start_y;

		if ( (y = y + bp.height - dpi->height) > 0) {
			bp.height -= y;
			if (bp.height <= 0) return;
		}

		start_x = 0;
		x &= zoom_mask;
		if ( (x -= dpi->left) < 0) {
			bp.width += x;
			if (bp.width <= 0) return;
			start_x -= x;
			x = 0;
		}
		bp.start_x = start_x;
		bp.dst += UnScaleByZoom(x, dpi->zoom);

		if ( (x = x + bp.width - dpi->width) > 0) {
			bp.width -= x;
			if (bp.width <= 0) return;
		}

		GfxBlitTileZoom(&bp, dpi->zoom);
	} else {
		bp.sprite += bp.width * (bp.height & ~zoom_mask);
		bp.height &= zoom_mask;
		if (bp.height == 0) return;

		y &= zoom_mask;

		if ( (y -= dpi->top) < 0) {
			bp.height += y;
			if (bp.height <= 0) return;
			bp.sprite -= bp.width * y;
			y = 0;
		} else {
			bp.dst += bp.pitch * UnScaleByZoom(y, dpi->zoom);
		}

		if (bp.height > dpi->height - y) {
			bp.height = dpi->height - y;
			if (bp.height <= 0) return;
		}

		x &= zoom_mask;

		if ( (x -= dpi->left) < 0) {
			bp.width += x;
			if (bp.width <= 0) return;
			bp.sprite -= x;
			x = 0;
		}
		bp.dst += UnScaleByZoom(x, dpi->zoom);

		if (bp.width > dpi->width - x) {
			bp.width = dpi->width - x;
			if (bp.width <= 0) return;
		}

		GfxBlitZoomUncomp(&bp, dpi->zoom);
	}
}

void DoPaletteAnimations();

void GfxInitPalettes()
{
	memcpy(_cur_palette, _palettes[_use_dos_palette ? 1 : 0], sizeof(_cur_palette));

	_pal_first_dirty = 0;
	_pal_last_dirty = 255;
	DoPaletteAnimations();
}

#define EXTR(p, q) (((uint16)(_timer_counter * (p)) * (q)) >> 16)
#define EXTR2(p, q) (((uint16)(~_timer_counter * (p)) * (q)) >> 16)

void DoPaletteAnimations()
{
	const Colour *s;
	Colour *d;
	/* Amount of colors to be rotated.
	 * A few more for the DOS palette, because the water colors are
	 * 245-254 for DOS and 217-226 for Windows.  */
	const ExtraPaletteValues *ev = &_extra_palette_values;
	int c = _use_dos_palette ? 38 : 28;
	Colour old_val[38]; // max(38, 28)
	uint i;
	uint j;

	d = &_cur_palette[217];
	memcpy(old_val, d, c * sizeof(*old_val));

	/* Dark blue water */
	s = (_opt.landscape == LT_TOYLAND) ? ev->ac : ev->a;
	j = EXTR(320, 5);
	for (i = 0; i != 5; i++) {
		*d++ = s[j];
		j++;
		if (j == 5) j = 0;
	}

	/* Glittery water */
	s = (_opt.landscape == LT_TOYLAND) ? ev->bc : ev->b;
	j = EXTR(128, 15);
	for (i = 0; i != 5; i++) {
		*d++ = s[j];
		j += 3;
		if (j >= 15) j -= 15;
	}

	s = ev->e;
	j = EXTR2(512, 5);
	for (i = 0; i != 5; i++) {
		*d++ = s[j];
		j++;
		if (j == 5) j = 0;
	}

	/* Oil refinery fire animation */
	s = ev->oil_ref;
	j = EXTR2(512, 7);
	for (i = 0; i != 7; i++) {
		*d++ = s[j];
		j++;
		if (j == 7) j = 0;
	}

	/* Radio tower blinking */
	{
		byte i = (_timer_counter >> 1) & 0x7F;
		byte v;

		(v = 255, i < 0x3f) ||
		(v = 128, i < 0x4A || i >= 0x75) ||
		(v = 20);
		d->r = v;
		d->g = 0;
		d->b = 0;
		d++;

		i ^= 0x40;
		(v = 255, i < 0x3f) ||
		(v = 128, i < 0x4A || i >= 0x75) ||
		(v = 20);
		d->r = v;
		d->g = 0;
		d->b = 0;
		d++;
	}

	/* Handle lighthouse and stadium animation */
	s = ev->lighthouse;
	j = EXTR(256, 4);
	for (i = 0; i != 4; i++) {
		*d++ = s[j];
		j++;
		if (j == 4) j = 0;
	}

	/* Animate water for old DOS graphics */
	if (_use_dos_palette) {
		/* Dark blue water DOS */
		s = (_opt.landscape == LT_TOYLAND) ? ev->ac : ev->a;
		j = EXTR(320, 5);
		for (i = 0; i != 5; i++) {
			*d++ = s[j];
			j++;
			if (j == 5) j = 0;
		}

		/* Glittery water DOS */
		s = (_opt.landscape == LT_TOYLAND) ? ev->bc : ev->b;
		j = EXTR(128, 15);
		for (i = 0; i != 5; i++) {
			*d++ = s[j];
			j += 3;
			if (j >= 15) j -= 15;
		}
	}

	if (memcmp(old_val, &_cur_palette[217], c * sizeof(*old_val)) != 0) {
		if (_pal_first_dirty > 217) _pal_first_dirty = 217;
		if (_pal_last_dirty < 217 + c) _pal_last_dirty = 217 + c;
	}
}


void LoadStringWidthTable()
{
	uint i;

	/* Normal font */
	for (i = 0; i != 224; i++) {
		_stringwidth_table[FS_NORMAL][i] = GetGlyphWidth(FS_NORMAL, i + 32);
	}

	/* Small font */
	for (i = 0; i != 224; i++) {
		_stringwidth_table[FS_SMALL][i] = GetGlyphWidth(FS_SMALL, i + 32);
	}

	/* Large font */
	for (i = 0; i != 224; i++) {
		_stringwidth_table[FS_LARGE][i] = GetGlyphWidth(FS_LARGE, i + 32);
	}
}


byte GetCharacterWidth(FontSize size, WChar key)
{
	if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];

	return GetGlyphWidth(size, key);
}


void ScreenSizeChanged()
{
	/* check the dirty rect */
	if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
	if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;

	/* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
	_cursor.visible = false;
}

void UndrawMouseCursor()
{
	if (_cursor.visible) {
		_cursor.visible = false;
		memcpy_pitch(
			_screen.dst_ptr + _cursor.draw_pos.x + _cursor.draw_pos.y * _screen.pitch,
			_cursor_backup,
			_cursor.draw_size.x, _cursor.draw_size.y, _cursor.draw_size.x, _screen.pitch);

		_video_driver->make_dirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
	}
}

void DrawMouseCursor()
{
	int x;
	int y;
	int w;
	int h;

	/* Redraw mouse cursor but only when it's inside the window */
	if (!_cursor.in_window) return;

	/* Don't draw the mouse cursor if it's already drawn */
	if (_cursor.visible) {
		if (!_cursor.dirty) return;
		UndrawMouseCursor();
	}

	w = _cursor.size.x;
	x = _cursor.pos.x + _cursor.offs.x;
	if (x < 0) {
		w += x;
		x = 0;
	}
	if (w > _screen.width - x) w = _screen.width - x;
	if (w <= 0) return;
	_cursor.draw_pos.x = x;
	_cursor.draw_size.x = w;

	h = _cursor.size.y;
	y = _cursor.pos.y + _cursor.offs.y;
	if (y < 0) {
		h += y;
		y = 0;
	}
	if (h > _screen.height - y) h = _screen.height - y;
	if (h <= 0) return;
	_cursor.draw_pos.y = y;
	_cursor.draw_size.y = h;

	assert(w * h < (int)sizeof(_cursor_backup));

	/* Make backup of stuff below cursor */
	memcpy_pitch(
		_cursor_backup,
		_screen.dst_ptr + _cursor.draw_pos.x + _cursor.draw_pos.y * _screen.pitch,
		_cursor.draw_size.x, _cursor.draw_size.y, _screen.pitch, _cursor.draw_size.x);

	/* Draw cursor on screen */
	_cur_dpi = &_screen;
	DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x, _cursor.pos.y);

	_video_driver->make_dirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);

	_cursor.visible = true;
	_cursor.dirty = false;
}

#if defined(_DEBUG)
static void DbgScreenRect(int left, int top, int right, int bottom)
{
	DrawPixelInfo dp;
	DrawPixelInfo *old;

	old = _cur_dpi;
	_cur_dpi = &dp;
	dp = _screen;
	GfxFillRect(left, top, right - 1, bottom - 1, rand() & 255);
	_cur_dpi = old;
}
#endif

void RedrawScreenRect(int left, int top, int right, int bottom)
{
	assert(right <= _screen.width && bottom <= _screen.height);
	if (_cursor.visible) {
		if (right > _cursor.draw_pos.x &&
				left < _cursor.draw_pos.x + _cursor.draw_size.x &&
				bottom > _cursor.draw_pos.y &&
				top < _cursor.draw_pos.y + _cursor.draw_size.y) {
			UndrawMouseCursor();
		}
	}
	UndrawTextMessage();

#if defined(_DEBUG)
	if (_dbg_screen_rect)
		DbgScreenRect(left, top, right, bottom);
	else
#endif
		DrawOverlappedWindowForAll(left, top, right, bottom);

	_video_driver->make_dirty(left, top, right - left, bottom - top);
}

void DrawDirtyBlocks()
{
	byte *b = _dirty_blocks;
	const int w = ALIGN(_screen.width, 64);
	const int h = ALIGN(_screen.height, 8);
	int x;
	int y;

	if (IsGeneratingWorld() && !IsGeneratingWorldReadyForPaint()) return;

	y = 0;
	do {
		x = 0;
		do {
			if (*b != 0) {
				int left;
				int top;
				int right = x + 64;
				int bottom = y;
				byte *p = b;
				int h2;

				/* First try coalescing downwards */
				do {
					*p = 0;
					p += DIRTY_BYTES_PER_LINE;
					bottom += 8;
				} while (bottom != h && *p != 0);

				/* Try coalescing to the right too. */
				h2 = (bottom - y) >> 3;
				assert(h2 > 0);
				p = b;

				while (right != w) {
					byte *p2 = ++p;
					int h = h2;
					/* Check if a full line of dirty flags is set. */
					do {
						if (!*p2) goto no_more_coalesc;
						p2 += DIRTY_BYTES_PER_LINE;
					} while (--h != 0);

					/* Wohoo, can combine it one step to the right!
					 * Do that, and clear the bits. */
					right += 64;

					h = h2;
					p2 = p;
					do {
						*p2 = 0;
						p2 += DIRTY_BYTES_PER_LINE;
					} while (--h != 0);
				}
				no_more_coalesc:

				left = x;
				top = y;

				if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
				if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
				if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
				if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;

				if (left < right && top < bottom) {
					RedrawScreenRect(left, top, right, bottom);
				}

			}
		} while (b++, (x += 64) != w);
	} while (b += -(w >> 6) + DIRTY_BYTES_PER_LINE, (y += 8) != h);

	_invalid_rect.left = w;
	_invalid_rect.top = h;
	_invalid_rect.right = 0;
	_invalid_rect.bottom = 0;

	/* If we are generating a world, and waiting for a paint run, mark it here
	 *  as done painting, so we can continue generating. */
	if (IsGeneratingWorld() && IsGeneratingWorldReadyForPaint()) {
		SetGeneratingWorldPaintStatus(false);
	}
}


void SetDirtyBlocks(int left, int top, int right, int bottom)
{
	byte *b;
	int width;
	int height;

	if (left < 0) left = 0;
	if (top < 0) top = 0;
	if (right > _screen.width) right = _screen.width;
	if (bottom > _screen.height) bottom = _screen.height;

	if (left >= right || top >= bottom) return;

	if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
	if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
	if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
	if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;

	left >>= 6;
	top  >>= 3;

	b = _dirty_blocks + top * DIRTY_BYTES_PER_LINE + left;

	width  = ((right  - 1) >> 6) - left + 1;
	height = ((bottom - 1) >> 3) - top  + 1;

	assert(width > 0 && height > 0);

	do {
		int i = width;

		do b[--i] = 0xFF; while (i);

		b += DIRTY_BYTES_PER_LINE;
	} while (--height != 0);
}

void MarkWholeScreenDirty()
{
	SetDirtyBlocks(0, 0, _screen.width, _screen.height);
}

/** Set up a clipping area for only drawing into a certain area. To do this,
 * Fill a DrawPixelInfo object with the supplied relative rectangle, backup
 * the original (calling) _cur_dpi and assign the just returned DrawPixelInfo
 * _cur_dpi. When you are done, give restore _cur_dpi's original value
 * @param *n the DrawPixelInfo that will be the clipping rectangle box allowed
 * for drawing
 * @param left,top,width,height the relative coordinates of the clipping
 * rectangle relative to the current _cur_dpi. This will most likely be the
 * offset from the calling window coordinates
 * @return return false if the requested rectangle is not possible with the
 * current dpi pointer. Only continue of the return value is true, or you'll
 * get some nasty results */
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
{
	const DrawPixelInfo *o = _cur_dpi;

	n->zoom = ZOOM_LVL_NORMAL;

	assert(width > 0);
	assert(height > 0);

	if ((left -= o->left) < 0) {
		width += left;
		if (width <= 0) return false;
		n->left = -left;
		left = 0;
	} else {
		n->left = 0;
	}

	if (width > o->width - left) {
		width = o->width - left;
		if (width <= 0) return false;
	}
	n->width = width;

	if ((top -= o->top) < 0) {
		height += top;
		if (height <= 0) return false;
		n->top = -top;
		top = 0;
	} else {
		n->top = 0;
	}

	n->dst_ptr = o->dst_ptr + left + top * (n->pitch = o->pitch);

	if (height > o->height - top) {
		height = o->height - top;
		if (height <= 0) return false;
	}
	n->height = height;

	return true;
}

static void SetCursorSprite(SpriteID cursor, SpriteID pal)
{
	CursorVars *cv = &_cursor;
	const Sprite *p;

	if (cv->sprite == cursor) return;

	p = GetSprite(GB(cursor, 0, SPRITE_WIDTH));
	cv->sprite = cursor;
	cv->pal    = pal;
	cv->size.y = p->height;
	cv->size.x = p->width;
	cv->offs.x = p->x_offs;
	cv->offs.y = p->y_offs;

	cv->dirty = true;
}

static void SwitchAnimatedCursor()
{
	const AnimCursor *cur = _cursor.animate_cur;

	if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;

	SetCursorSprite(cur->sprite, _cursor.pal);

	_cursor.animate_timeout = cur->display_time;
	_cursor.animate_cur     = cur + 1;
}

void CursorTick()
{
	if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0)
		SwitchAnimatedCursor();
}

void SetMouseCursor(SpriteID sprite, SpriteID pal)
{
	/* Turn off animation */
	_cursor.animate_timeout = 0;
	/* Set cursor */
	SetCursorSprite(sprite, pal);
}

void SetAnimatedMouseCursor(const AnimCursor *table)
{
	_cursor.animate_list = table;
	_cursor.animate_cur = NULL;
	_cursor.pal = PAL_NONE;
	SwitchAnimatedCursor();
}

bool ChangeResInGame(int w, int h)
{
	return
		(_screen.width == w && _screen.height == h) ||
		_video_driver->change_resolution(w, h);
}

void ToggleFullScreen(bool fs)
{
	_video_driver->toggle_fullscreen(fs);
	if (_fullscreen != fs && _num_resolutions == 0) {
		DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
	}
}

static int CDECL compare_res(const void *pa, const void *pb)
{
	int x = ((const uint16*)pa)[0] - ((const uint16*)pb)[0];
	if (x != 0) return x;
	return ((const uint16*)pa)[1] - ((const uint16*)pb)[1];
}

void SortResolutions(int count)
{
	qsort(_resolutions, count, sizeof(_resolutions[0]), compare_res);
}