aboutsummaryrefslogtreecommitdiff
path: root/engines/tsage/graphics.cpp
blob: eb7adbe53abd7748b59c864beb50a220fe440b13 (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
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
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * 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.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "tsage/events.h"
#include "tsage/graphics.h"
#include "tsage/resources.h"
#include "tsage/tsage.h"
#include "tsage/core.h"
#include "common/algorithm.h"
#include "graphics/palette.h"
#include "graphics/surface.h"
#include "tsage/globals.h"

namespace TsAGE {

/**
 * Creates a new graphics surface with the specified area of another surface
 *
 * @src Source surface
 * @bounds Area to backup
 */
GfxSurface *surfaceGetArea(GfxSurface &src, const Rect &bounds) {
	assert(bounds.isValidRect());
	GfxSurface *dest = new GfxSurface();
	dest->create(bounds.width(), bounds.height());

	Graphics::Surface srcSurface = src.lockSurface();
	Graphics::Surface destSurface = dest->lockSurface();

	byte *srcP = (byte *)srcSurface.getBasePtr(bounds.left, bounds.top);
	byte *destP = (byte *)destSurface.getPixels();

	for (int y = bounds.top; y < bounds.bottom; ++y, srcP += srcSurface.pitch, destP += destSurface.pitch)
		Common::copy(srcP, srcP + destSurface.pitch, destP);

	src.unlockSurface();
	dest->unlockSurface();
	return dest;
}

/**
 * Translates a raw image resource into a graphics surface. The caller is then responsible
 * for managing and destroying the surface when done with it
 *
 * @imgData Raw image resource
 * @size Size of the resource
 */
GfxSurface surfaceFromRes(const byte *imgData) {
	Rect r(0, 0, READ_LE_UINT16(imgData), READ_LE_UINT16(imgData + 2));
	GfxSurface s;
	s.create(r.width(), r.height());
	s._transColor = *(imgData + 8);

	byte flags = imgData[9];
	s._flags = (g_vm->getGameID() != GType_Ringworld) ? flags : 0;

	bool rleEncoded = (flags & 2) != 0;

	// Figure out the centroid
	s._centroid.x = READ_LE_UINT16(imgData + 4);
	s._centroid.y = READ_LE_UINT16(imgData + 6);

	const byte *srcP = imgData + 10;
	Graphics::Surface destSurface = s.lockSurface();
	byte *destP = (byte *)destSurface.getPixels();

	if (!rleEncoded) {
		Common::copy(srcP, srcP + (r.width() * r.height()), destP);
	} else {
		Common::fill(destP, destP + (r.width() * r.height()), s._transColor);

		for (int yp = 0; yp < r.height(); ++yp) {
			int width = r.width();
			destP = (byte *)destSurface.getBasePtr(0, yp);

			while (width > 0) {
				uint8 controlVal = *srcP++;
				if ((controlVal & 0x80) == 0) {
					// Copy specified number of bytes

					Common::copy(srcP, srcP + controlVal, destP);
					width -= controlVal;
					srcP += controlVal;
					destP += controlVal;
				} else if ((controlVal & 0x40) == 0) {
					// Skip a specified number of output pixels
					destP += controlVal & 0x3f;
					width -= controlVal & 0x3f;
				} else {
					// Copy a specified pixel a given number of times
					controlVal &= 0x3f;
					int pixel = *srcP++;

					Common::fill(destP, destP + controlVal, pixel);
					destP += controlVal;
					width -= controlVal;
				}
			}
			assert(width == 0);
		}
	}

	s.unlockSurface();
	return s;
}

GfxSurface surfaceFromRes(int resNum, int rlbNum, int subNum) {
	uint size;
	byte *imgData = g_resourceManager->getSubResource(resNum, rlbNum, subNum, &size);
	GfxSurface surface = surfaceFromRes(imgData);
	DEALLOCATE(imgData);

	return surface;
}
/*--------------------------------------------------------------------------*/

void Rect::set(int16 x1, int16 y1, int16 x2, int16 y2) {
	left = x1; top = y1;
	right = x2; bottom = y2;
}

/**
 * Collapses the rectangle in all four directions by the given x and y amounts
 *
 * @dx x amount to collapse x edges by
 * @dy y amount to collapse y edges by
 */
void Rect::collapse(int dx, int dy) {
	left += dx; right -= dx;
	top += dy; bottom -= dy;
}

/**
 * Centers the rectangle at a given position
 *
 * @xp x position for new center
 * @yp y position for new center
 */
void Rect::center(int xp, int yp) {
	moveTo(xp - (width() / 2), yp - (height() / 2));
}

/**
 * Centers the rectangle at the center of a second passed rectangle
 *
 * @r Second rectangle whose center to use
 */
void Rect::center(const Rect &r) {
	center(r.left + (r.width() / 2), r.top + (r.height() / 2));
}

/*
 * Repositions the bounds if necessary so it falls entirely within the passed bounds
 *
 * @r The bounds the current rect should be within
 */
void Rect::contain(const Rect &r) {
	if (left < r.left) translate(r.left - left, 0);
	if (right > r.right) translate(r.right - right, 0);
	if (top < r.top) translate(0, r.top - top);
	if (bottom > r.bottom) translate(0, r.bottom - bottom);
}

/**
 * Resizes and positions a given rect based on raw image data and a passed scaling percentage
 *
 * @frame Raw image frame
 * @xp New x position
 * @yp New y position
 * @percent Scaling percentage
 */
void Rect::resize(const GfxSurface &surface, int xp, int yp, int percent) {
	const Rect &bounds = surface.getBounds();
	int xe = bounds.width() * percent / 100;
	int ye = bounds.height() * percent / 100;
	this->set(0, 0, xe, ye);

	if (!right) ++right;
	if (!bottom) ++bottom;

	this->moveTo(xp, yp);

	int xa = (surface._flags & FRAME_FLIP_CENTROID_X) == 0 ? surface._centroid.x : 
		bounds.width() - (surface._centroid.x + 1);
	int ya = (surface._flags & FRAME_FLIP_CENTROID_Y) == 0 ? surface._centroid.y : 
		bounds.height() - (surface._centroid.y + 1);

	int xd = xa * percent / 100;
	int yd = ya * percent / 100;
	this->translate(-xd, -yd);
}

/**
 * Expands the pane region to contain the specified Rect
 */
void Rect::expandPanes() {
	g_globals->_paneRegions[0].uniteRect(*this);
	g_globals->_paneRegions[1].uniteRect(*this);
}

/**
 * Serialises the given rect
 */
void Rect::synchronize(Serializer &s) {
	s.syncAsSint16LE(left);
	s.syncAsSint16LE(top);
	s.syncAsSint16LE(right);
	s.syncAsSint16LE(bottom);
}

/*--------------------------------------------------------------------------*/

GfxSurface::GfxSurface() : _bounds(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) {
	_disableUpdates = false;
	_lockSurfaceCtr = 0;
	_customSurface = NULL;
	_transColor = -1;
	_trackDirtyRects = false;
	_flags = 0;
}

GfxSurface::GfxSurface(const GfxSurface &s) {
	_lockSurfaceCtr = 0;
	_customSurface = NULL;
	_trackDirtyRects = false;
	*this = s;
}

GfxSurface::~GfxSurface() {
	clear();
}

void GfxSurface::clear() {
	if (_customSurface) {
		_customSurface->free();
		delete _customSurface;
		_customSurface = NULL;
	}
}

/**
 * Specifies that the surface will encapsulate the ScummVM screen surface
 */
void GfxSurface::setScreenSurface() {
	_trackDirtyRects = true;
	create(SCREEN_WIDTH, SCREEN_HEIGHT);
}

/**
 * Updates the physical screen with the screen surface buffer
 */
void GfxSurface::updateScreen() {
	assert(_trackDirtyRects);

	// Merge any overlapping dirty rects
	mergeDirtyRects();

	// Loop through the dirty rect list to copy the affected areas to the sc
	for (Common::List<Rect>::iterator i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
		Rect r = *i;

		// Make sure that there is something to update. If not, skip this
		// rectangle. An example case is the speedbike closeup at the beginning
		// of Ringworld (third screen).
		if (r.isEmpty())
			continue;

		const byte *srcP = (const byte *)_customSurface->getBasePtr(r.left, r.top);
		g_system->copyRectToScreen(srcP, _customSurface->pitch, r.left, r.top,
			r.width(), r.height());
	}

	// Update the physical screen
	g_system->updateScreen();

	// Now that the dirty rects have been copied, clear the dirty rect list
	_dirtyRects.clear();
}

/**
 * Adds a rect to the dirty rect list
 */
void GfxSurface::addDirtyRect(const Rect &r) {
	if (_trackDirtyRects) {
		// Get the bounds and adjust to allow for sub-screen areas
		Rect r2 = r;
		r2.translate(_bounds.left, _bounds.top);

		// Add to the dirty rect list
		r2.right = MIN(r2.right + 1, SCREEN_WIDTH);
		r2.bottom = MIN(r2.bottom + 1, SCREEN_HEIGHT);

		if (r2.isValidRect())
			_dirtyRects.push_back(r2);
	}
}



/**
 * Specifies that the surface should maintain it's own internal surface
 */
void GfxSurface::create(int width, int height) {
	assert((width >= 0) && (height >= 0));

	if (_customSurface) {
		_customSurface->free();
		delete _customSurface;
	}
	_customSurface = new Graphics::Surface();
	_customSurface->create(width, height, Graphics::PixelFormat::createFormatCLUT8());
	Common::fill((byte *)_customSurface->getPixels(), (byte *)_customSurface->getBasePtr(0, height), 0);
	_bounds = Rect(0, 0, width, height);
}

/**
 * Locks the surface for access, and returns a raw ScummVM surface to manipulate it
 */
Graphics::Surface GfxSurface::lockSurface() {
	++_lockSurfaceCtr;

	Graphics::Surface *src = _customSurface;
	assert(src);

	// Setup the returned surface either as one pointing to the same pixels as the source, or
	// as a subset of the source one based on the currently set bounds
	Graphics::Surface result;
	result.init(_bounds.width(), _bounds.height(), src->pitch, src->getBasePtr(_bounds.left, _bounds.top), src->format);
	return result;
}

/**
 * Unlocks the surface after having accessed it with the lockSurface method
 */
void GfxSurface::unlockSurface() {
	assert(_lockSurfaceCtr > 0);
	--_lockSurfaceCtr;
}

void GfxSurface::synchronize(Serializer &s) {
	assert(!_lockSurfaceCtr);

	s.syncAsByte(_disableUpdates);
	_bounds.synchronize(s);
	s.syncAsSint16LE(_centroid.x);
	s.syncAsSint16LE(_centroid.y);
	s.syncAsSint16LE(_transColor);

	if (s.isSaving()) {
		// Save contents of the surface
		if (_customSurface) {
			s.syncAsSint16LE(_customSurface->w);
			s.syncAsSint16LE(_customSurface->h);
			s.syncBytes((byte *)_customSurface->getPixels(), _customSurface->w * _customSurface->h);
		} else {
			int zero = 0;
			s.syncAsSint16LE(zero);
			s.syncAsSint16LE(zero);
		}
	} else {
		int w = 0, h = 0;
		s.syncAsSint16LE(w);
		s.syncAsSint16LE(h);

		if ((w == 0) || (h == 0)) {
			if (_customSurface)
				delete _customSurface;
			_customSurface = NULL;
		} else {
			create(w, h);
			s.syncBytes((byte *)_customSurface->getPixels(), w * h);
		}
	}
}

/**
 * Fills a specified rectangle on the surface with the specified color
 *
 * @bounds Area to fill
 * @color Color to use
 */
void GfxSurface::fillRect(const Rect &bounds, int color) {
	Graphics::Surface surface = lockSurface();
	surface.fillRect(bounds, color);
	unlockSurface();
	addDirtyRect(bounds);
}

GfxSurface &GfxSurface::operator=(const GfxSurface &s) {
	assert(_lockSurfaceCtr == 0);
	assert(s._lockSurfaceCtr == 0);

	if (_customSurface) {
		_customSurface->free();
		delete _customSurface;
	}

	_customSurface = s._customSurface;
	_disableUpdates = s._disableUpdates;
	_bounds = s._bounds;
	_centroid = s._centroid;
	_transColor = s._transColor;
	_flags = s._flags;

	if (_customSurface) {
		// Surface owns the internal data, so replicate it so new surface owns it's own
		_customSurface = new Graphics::Surface();
		_customSurface->create(s._customSurface->w, s._customSurface->h, Graphics::PixelFormat::createFormatCLUT8());
		const byte *srcP = (const byte *)s._customSurface->getPixels();
		byte *destP = (byte *)_customSurface->getPixels();

		Common::copy(srcP, srcP + (_bounds.width() * _bounds.height()), destP);
	}

	return *this;
}

/**
 * Displays a message on-screen until either a mouse or keypress
 */
bool GfxSurface::displayText(const Common::String &msg, const Common::Point &pt) {
	// Set up a new graphics manager
	GfxManager gfxManager;
	gfxManager.activate();
	gfxManager._font._colors.background = 0;
	gfxManager._font._colors.foreground = 7;
	gfxManager._font.setFontNumber(2);

	// Get the area for text display
	Rect textRect;
	gfxManager.getStringBounds(msg.c_str(), textRect, 200);
	textRect.center(pt.x, pt.y);

	// Make a backup copy of the area the text will occupy
	Rect saveRect = textRect;
	saveRect.collapse(-20, -8);
	GfxSurface *savedArea = surfaceGetArea(gfxManager.getSurface(), saveRect);

	// Display the text
	gfxManager._font.writeLines(msg.c_str(), textRect, ALIGN_LEFT);

	// Wait for a mouse or keypress
	Event event;
	while (!g_globals->_events.getEvent(event, EVENT_BUTTON_DOWN | EVENT_KEYPRESS) && !g_vm->shouldQuit())
		;

	// Restore the display area
	gfxManager.copyFrom(*savedArea, saveRect.left, saveRect.top);
	delete savedArea;

	gfxManager.deactivate();
	return (event.eventType == EVENT_KEYPRESS) && (event.kbd.keycode == Common::KEYCODE_RETURN);
}

/**
 * Loads a quarter of a screen from a resource
 */
void GfxSurface::loadScreenSection(Graphics::Surface &dest, int xHalf, int yHalf, int xSection, int ySection) {
	int screenNum = g_globals->_sceneManager._scene->_activeScreenNumber;
	Rect updateRect(0, 0, 160, 100);
	updateRect.translate(xHalf * 160, yHalf * 100);
	int xHalfCount = (g_globals->_sceneManager._scene->_backgroundBounds.right + 159) / 160;
	int yHalfCount = (g_globals->_sceneManager._scene->_backgroundBounds.bottom + 99) / 100;

	if (xSection < xHalfCount && ySection < yHalfCount) {
		int rlbNum = xSection * yHalfCount + ySection;
		byte *data = g_resourceManager->getResource(RES_BITMAP, screenNum, rlbNum);

		for (int y = 0; y < updateRect.height(); ++y) {
			byte *pSrc = data + y * 160;
			byte *pDest = (byte *)dest.getBasePtr(updateRect.left, updateRect.top + y);

			for (int x = 0; x < updateRect.width(); ++x, ++pSrc, ++pDest) {
				*pDest = *pSrc;
			}
		}

		DEALLOCATE(data);
	}
}

/**
 * Returns an array indicating which pixels of a source image horizontally or vertically get
 * included in a scaled image
 */
static int *scaleLine(int size, int srcSize) {
	const int PRECISION_FACTOR = 1000;
	int scale = PRECISION_FACTOR * size / srcSize;
	assert(scale >= 0);
	int *v = new int[size];
	Common::fill(v, &v[size], -1);

	int distCtr = PRECISION_FACTOR / 2;
	int *destP = v;
	for (int distIndex = 0; distIndex < srcSize; ++distIndex) {
		distCtr += scale;
		while (distCtr > PRECISION_FACTOR) {
			assert(destP < &v[size]);
			*destP++ = distIndex;
			distCtr -= PRECISION_FACTOR;
		}
	}

	return v;
}

/**
 * Scales a passed surface, creating a new surface with the result
 * @param srcImage		Source image to scale
 * @param NewWidth		New width for scaled image
 * @param NewHeight		New height for scaled image
 * @remarks Caller is responsible for freeing the returned surface
 */
static GfxSurface ResizeSurface(GfxSurface &src, int xSize, int ySize, int transIndex) {
	GfxSurface s;
	s.create(xSize, ySize);

	Graphics::Surface srcImage = src.lockSurface();
	Graphics::Surface destImage = s.lockSurface();

	int *horizUsage = scaleLine(xSize, srcImage.w);
	int *vertUsage = scaleLine(ySize, srcImage.h);

	// Loop to create scaled version
	for (int yp = 0; yp < ySize; ++yp) {
		byte *destP = (byte *)destImage.getBasePtr(0, yp);

		if (vertUsage[yp] == -1) {
			Common::fill(destP, destP + xSize, transIndex);
		} else {
			const byte *srcP = (const byte *)srcImage.getBasePtr(0, vertUsage[yp]);

			for (int xp = 0; xp < xSize; ++xp) {
				if (horizUsage[xp] != -1) {
					const byte *tempSrcP = srcP + horizUsage[xp];
					*destP++ = *tempSrcP++;
				} else {
					// Pixel overrun at the end of the line
					*destP++ = transIndex;
				}
			}
		}
	}

	// Unlock surfaces
	src.unlockSurface();
	s.unlockSurface();

	// Delete arrays and return surface
	delete[] horizUsage;
	delete[] vertUsage;
	return s;
}

/**
 * Copys an area from one GfxSurface to another.
 *
 */
void GfxSurface::copyFrom(GfxSurface &src, Rect srcBounds, Rect destBounds,
		Region *priorityRegion, const byte *shadowMap) {
	GfxSurface srcImage;
	if (srcBounds.isEmpty())
		return;

	if (srcBounds == src.getBounds())
		srcImage = src;
	else {
		// Set the source image to be the subset specified by the source bounds
		Graphics::Surface srcSurface = src.lockSurface();

		srcImage.create(srcBounds.width(), srcBounds.height());
		Graphics::Surface destSurface = srcImage.lockSurface();

		const byte *srcP = (const byte *)srcSurface.getBasePtr(srcBounds.left, srcBounds.top);
		byte *destP = (byte *)destSurface.getPixels();
		for (int yp = srcBounds.top; yp < srcBounds.bottom; ++yp, srcP += srcSurface.pitch, destP += destSurface.pitch) {
			Common::copy(srcP, srcP + srcBounds.width(), destP);
		}

		srcImage.unlockSurface();
		src.unlockSurface();
	}

	if ((destBounds.width() != srcBounds.width()) || (destBounds.height() != srcBounds.height()))
		srcImage = ResizeSurface(srcImage, destBounds.width(), destBounds.height(), src._transColor);

	Graphics::Surface srcSurface = srcImage.lockSurface();
	Graphics::Surface destSurface = lockSurface();

	// Get clipping area
	Rect clipRect = !_clipRect.isEmpty() ? _clipRect :
		Rect(0, 0, destSurface.w, destSurface.h);

	// Adjust bounds to ensure destination will be on-screen
	int srcX = 0, srcY = 0;
	if (destBounds.left < clipRect.left) {
		srcX = clipRect.left - destBounds.left;
		destBounds.left = clipRect.left;
	}
	if (destBounds.top < clipRect.top) {
		srcY = clipRect.top - destBounds.top;
		destBounds.top = clipRect.top;
	}
	if (destBounds.right > clipRect.right)
		destBounds.right = clipRect.right;
	if (destBounds.bottom > clipRect.bottom)
		destBounds.bottom = clipRect.bottom;

	if (destBounds.isValidRect() && !((destBounds.right < 0) || (destBounds.bottom < 0)
		|| (destBounds.left >= destSurface.w) || (destBounds.top >= destSurface.h))) {
		// Register the affected area as dirty
		addDirtyRect(destBounds);

		const byte *pSrc = (const byte *)srcSurface.getBasePtr(srcX, srcY);
		byte *pDest = (byte *)destSurface.getBasePtr(destBounds.left, destBounds.top);

		for (int y = 0; y < destBounds.height(); ++y, pSrc += srcSurface.pitch, pDest += destSurface.pitch) {

			if (!priorityRegion && (src._transColor == -1))
				Common::copy(pSrc, pSrc + destBounds.width(), pDest);
			else {
				const byte *tempSrc = pSrc;
				byte *tempDest = pDest;
				int xp = destBounds.left;

				while (tempSrc < (pSrc + destBounds.width())) {
					if (!priorityRegion || !priorityRegion->contains(Common::Point(
							xp + g_globals->_sceneManager._scene->_sceneBounds.left,
							destBounds.top + y + g_globals->_sceneManager._scene->_sceneBounds.top))) {
						if (*tempSrc != src._transColor) {
							if (shadowMap) {
								// Using a shadow map, so translate the dest pixel using the mapping array
								*tempDest = shadowMap[*tempDest];
							} else {
								// Otherwise, it's a standard pixel copy
								*tempDest = *tempSrc;
							}
						}
					}
					++tempSrc;
					++tempDest;
					++xp;
				}
			}
		}
	}

	unlockSurface();
	srcImage.unlockSurface();
}

void GfxSurface::draw(const Common::Point &pt, Rect *rect) {
	Rect tempRect = getBounds();
	tempRect.translate(-_centroid.x, -_centroid.y);
	tempRect.translate(pt.x, pt.y);

	if (rect) {
		// Only copy needed rect out without drawing
		*rect = tempRect;
	} else {
		// Draw image
		g_globals->gfxManager().copyFrom(*this, tempRect, NULL);
	}
}

/**
 * Merges any clipping rectangles that overlap to try and reduce
 * the total number of clip rectangles.
 */
void GfxSurface::mergeDirtyRects() {
	if (_dirtyRects.size() <= 1)
		return;

	Common::List<Rect>::iterator rOuter, rInner;

	for (rOuter = _dirtyRects.begin(); rOuter != _dirtyRects.end(); ++rOuter) {
		rInner = rOuter;
		while (++rInner != _dirtyRects.end()) {

			if ((*rOuter).intersects(*rInner)) {
				// these two rectangles overlap or
				// are next to each other - merge them

				unionRectangle(*rOuter, *rOuter, *rInner);

				// remove the inner rect from the list
				_dirtyRects.erase(rInner);

				// move back to beginning of list
				rInner = rOuter;
			}
		}
	}
}

/**
 * Creates the union of two rectangles.
 * Returns True if there is a union.
 * @param pDest			destination rectangle that is to receive the new union
 * @param pSrc1			a source rectangle
 * @param pSrc2			a source rectangle
 */
bool GfxSurface::unionRectangle(Common::Rect &destRect, const Rect &src1, const Rect &src2) {
	destRect = src1;
	destRect.extend(src2);

	return !destRect.isEmpty();
}

/*--------------------------------------------------------------------------*/

GfxElement::GfxElement() {
	_owner = NULL;
	_keycode = 0;
	_flags = 0;

	_fontNumber = 0;
	_color1 = 0;
	_color2 = 0;
	_color3 = 0;
}

void GfxElement::setDefaults() {
	_flags = 0;
	_fontNumber = g_globals->_gfxFontNumber;
	_colors = g_globals->_gfxColors;
	_fontColors = g_globals->_fontColors;
	_color1 = g_globals->_color1;
	_color2 = g_globals->_color2;
	_color3 = g_globals->_color3;
}

/**
 * Highlights the specified graphics element
 */
void GfxElement::highlight() {
	// Get a lock on the surface
	GfxManager &gfxManager = g_globals->gfxManager();
	Graphics::Surface surface = gfxManager.lockSurface();

	// Scan through the contents of the element, switching any occurances of the foreground
	// color with the background color and vice versa
	Rect tempRect(_bounds);
	tempRect.collapse(g_globals->_gfxEdgeAdjust - 1, g_globals->_gfxEdgeAdjust - 1);

	for (int yp = tempRect.top; yp < tempRect.bottom; ++yp) {
		byte *lineP = (byte *)surface.getBasePtr(tempRect.left, yp);
		for (int xp = tempRect.left; xp < tempRect.right; ++xp, ++lineP) {
			if (*lineP == _colors.background) *lineP = _colors.foreground;
			else if (*lineP == _colors.foreground) *lineP = _colors.background;
		}
	}

	// Mark the affected area as dirty
	gfxManager.getSurface().addDirtyRect(tempRect);

	// Release the surface
	gfxManager.unlockSurface();
}

/**
 * Fills the background of the specified element with a border frame
 */
void GfxElement::drawFrame() {
	// Get a lock on the surface and save the active font
	GfxManager &gfxManager = g_globals->gfxManager();
	gfxManager.lockSurface();

	uint8 bgColor, fgColor;
	if (_flags & GFXFLAG_THICK_FRAME) {
		bgColor = 0;
		fgColor = 0;
	} else {
		bgColor = _fontColors.background;
		fgColor = _fontColors.foreground;
	}

	Rect tempRect = _bounds;
	tempRect.collapse(g_globals->_gfxEdgeAdjust, g_globals->_gfxEdgeAdjust);
	tempRect.collapse(-1, -1);

	if (g_vm->getGameID() == GType_Ringworld2) {
		// For Return to Ringworld, use palette shading

		// Get the current palette and determining a shading translation list
		ScenePalette tempPalette;
		tempPalette.getPalette(0, 256);
		int transList[256];

		for (int i = 0; i < 256; ++i) {
			uint r, g, b, v;
			tempPalette.getEntry(i, &r, &g, &b);
			v = ((r >> 1) + (g >> 1) + (b >> 1)) / 4;

			transList[i] = tempPalette.indexOf(v, v, v);
		}

		// Loop through the surface area to replace each pixel
		// with its proper shaded replacement
		Graphics::Surface surface = gfxManager.lockSurface();
		for (int y = tempRect.top; y < tempRect.bottom; ++y) {
			byte *lineP = (byte *)surface.getBasePtr(tempRect.left, y);
			for (int x = 0; x < tempRect.width(); ++x) {
				*lineP = transList[*lineP];
				lineP++;
			}
		}

		// Draw the edge frame
		// Outer frame border
		surface.hLine(tempRect.left + 2, tempRect.top, tempRect.right - 2, 0);
		surface.hLine(tempRect.left + 2, tempRect.bottom, tempRect.right - 2, 0);
		surface.vLine(tempRect.left, tempRect.top + 2, tempRect.bottom - 2, 0);
		surface.vLine(tempRect.right, tempRect.top + 2, tempRect.bottom - 2, 0);
		*((byte *)surface.getBasePtr(tempRect.left + 1, tempRect.top + 1)) = 0;
		*((byte *)surface.getBasePtr(tempRect.right - 1, tempRect.top + 1)) = 0;
		*((byte *)surface.getBasePtr(tempRect.left + 1, tempRect.bottom - 1)) = 0;
		*((byte *)surface.getBasePtr(tempRect.right - 1, tempRect.bottom - 1)) = 0;

		// Inner frame border
		surface.hLine(tempRect.left + 2, tempRect.top + 1, tempRect.right - 2, R2_GLOBALS._frameEdgeColor);
		surface.hLine(tempRect.left + 2, tempRect.bottom - 1, tempRect.right - 2, R2_GLOBALS._frameEdgeColor);
		surface.vLine(tempRect.left + 1, tempRect.top + 2, tempRect.bottom - 2, R2_GLOBALS._frameEdgeColor);
		surface.vLine(tempRect.right - 1, tempRect.top + 2, tempRect.bottom - 2, R2_GLOBALS._frameEdgeColor);
		*((byte *)surface.getBasePtr(tempRect.left + 2, tempRect.top + 2)) = R2_GLOBALS._frameEdgeColor;
		*((byte *)surface.getBasePtr(tempRect.right - 2, tempRect.top + 2)) = R2_GLOBALS._frameEdgeColor;
		*((byte *)surface.getBasePtr(tempRect.left + 2, tempRect.bottom - 2)) = R2_GLOBALS._frameEdgeColor;
		*((byte *)surface.getBasePtr(tempRect.right - 2, tempRect.bottom - 2)) = R2_GLOBALS._frameEdgeColor;

		gfxManager.unlockSurface();
		gfxManager.getSurface().addDirtyRect(tempRect);

	} else {
		// Fill dialog content with specified background color
		gfxManager.fillRect(tempRect, _colors.background);

		--tempRect.bottom; --tempRect.right;
		gfxManager.fillArea(tempRect.left, tempRect.top, bgColor);
		gfxManager.fillArea(tempRect.left, tempRect.bottom, fgColor);
		gfxManager.fillArea(tempRect.right, tempRect.top, fgColor);
		gfxManager.fillArea(tempRect.right, tempRect.bottom, fgColor);

		tempRect.collapse(-1, -1);
		gfxManager.fillRect2(tempRect.left + 1, tempRect.top, tempRect.width() - 1, 1, bgColor);
		gfxManager.fillRect2(tempRect.left, tempRect.top + 1, 1, tempRect.height() - 1, bgColor);
		gfxManager.fillRect2(tempRect.left + 1, tempRect.bottom, tempRect.width() - 1, 1, fgColor);
		gfxManager.fillRect2(tempRect.right, tempRect.top + 1, 1, tempRect.height() - 1, fgColor);

		gfxManager.fillArea(tempRect.left, tempRect.top, 0);
		gfxManager.fillArea(tempRect.left, tempRect.bottom, 0);
		gfxManager.fillArea(tempRect.right, tempRect.top, 0);
		gfxManager.fillArea(tempRect.right, tempRect.bottom, 0);

		tempRect.collapse(-1, -1);
		gfxManager.fillRect2(tempRect.left + 2, tempRect.top, tempRect.width() - 3, 1, 0);
		gfxManager.fillRect2(tempRect.left, tempRect.top + 2, 1, tempRect.height() - 3, 0);
		gfxManager.fillRect2(tempRect.left + 2, tempRect.bottom, tempRect.width() - 3, 1, 0);
		gfxManager.fillRect2(tempRect.right, tempRect.top + 2, 1, tempRect.height() - 3, 0);
	}

	gfxManager.unlockSurface();
}

/**
 * Handles events when the control has focus
 *
 * @event Event to process
 */
bool GfxElement::focusedEvent(Event &event) {
	Common::Point mousePos = event.mousePos;
	bool highlightFlag = false;

	// HACK: It should use the GfxManager object to figure out the relative
	// position, but for now this seems like the easiest way.
	int xOffset = mousePos.x - g_globals->_events._mousePos.x;
	int yOffset = mousePos.y - g_globals->_events._mousePos.y;

	while (event.eventType != EVENT_BUTTON_UP && !g_vm->shouldQuit()) {
		g_system->delayMillis(10);

		if (_bounds.contains(mousePos)) {
			if (!highlightFlag) {
				// First highlight call to show the highlight
				highlightFlag = true;
				highlight();
			}
		} else if (highlightFlag) {
			// Mouse is outside the element, so remove the highlight
			highlightFlag = false;
			highlight();
		}

		if (g_globals->_events.getEvent(event, EVENT_MOUSE_MOVE | EVENT_BUTTON_UP)) {
			if (event.eventType == EVENT_MOUSE_MOVE) {
				mousePos.x = event.mousePos.x + xOffset;
				mousePos.y = event.mousePos.y + yOffset;
			}
		}
	}

	if (highlightFlag) {
		// Mouse is outside the element, so remove the highlight
		highlight();
	}

	return highlightFlag;
}

/*--------------------------------------------------------------------------*/

GfxImage::GfxImage() : GfxElement() {
	_resNum = 0;
	_rlbNum = 0;
	_cursorNum = 0;
}

void GfxImage::setDetails(int resNum, int rlbNum, int cursorNum) {
	_resNum = resNum;
	_rlbNum = rlbNum;
	_cursorNum = cursorNum;
	setDefaults();
}

void GfxImage::setDefaults() {
	GfxElement::setDefaults();

	// Decode the image
	uint size;
	byte *imgData = g_resourceManager->getSubResource(_resNum, _rlbNum, _cursorNum, &size);
	_surface = surfaceFromRes(imgData);
	DEALLOCATE(imgData);

	// Set up the display bounds
	Rect imgBounds = _surface.getBounds();
	imgBounds.moveTo(_bounds.left, _bounds.top);
	_bounds = imgBounds;
}

void GfxImage::draw() {
	Rect tempRect = _bounds;
	tempRect.translate(g_globals->gfxManager()._topLeft.x, g_globals->gfxManager()._topLeft.y);

	g_globals->gfxManager().copyFrom(_surface, tempRect);
}

/*--------------------------------------------------------------------------*/

GfxMessage::GfxMessage() : GfxElement() {
	_textAlign = ALIGN_LEFT;
	_width = 0;
}

void GfxMessage::set(const Common::String &s, int width, TextAlign textAlign) {
	_message = s;
	_width = width;
	_textAlign = textAlign;

	setDefaults();
}

void GfxMessage::setDefaults() {
	GfxElement::setDefaults();

	GfxFontBackup font;
	GfxManager &gfxManager = g_globals->gfxManager();
	Rect tempRect;

	gfxManager._font.setFontNumber(this->_fontNumber);
	gfxManager.getStringBounds(_message.c_str(), tempRect, _width);

	tempRect.collapse(-1, -1);
	tempRect.moveTo(_bounds.left, _bounds.top);
	_bounds = tempRect;
}

void GfxMessage::draw() {
	GfxFontBackup font;
	GfxManager &gfxManager = g_globals->gfxManager();

	// Set the font and color
	gfxManager.setFillFlag(false);
	gfxManager._font.setFontNumber(_fontNumber);

	gfxManager._font._colors.foreground = this->_color1;
	gfxManager._font._colors2.background = this->_color2;
	gfxManager._font._colors2.foreground = this->_color3;

	// Display the text
	gfxManager._font.writeLines(_message.c_str(), _bounds, _textAlign);
}

/*--------------------------------------------------------------------------*/

void GfxButton::setDefaults() {
	GfxElement::setDefaults();

	GfxFontBackup font;
	GfxManager &gfxManager = g_globals->gfxManager();
	Rect tempRect;

	// Get the string bounds and round up the x end to a multiple of 16
	gfxManager._font.setFontNumber(this->_fontNumber);
	gfxManager._font.getStringBounds(_message.c_str(), tempRect, 240);
	tempRect.right = ((tempRect.right + 15) / 16) * 16;

	// Set the button bounds
	tempRect.collapse(-g_globals->_gfxEdgeAdjust, -g_globals->_gfxEdgeAdjust);
	if (g_vm->getFeatures() & GF_CD)
		--tempRect.top;
	tempRect.moveTo(_bounds.left, _bounds.top);
	_bounds = tempRect;
}

void GfxButton::draw() {
	// Get a lock on the surface and save the active font
	GfxFontBackup font;
	GfxManager &gfxManager = g_globals->gfxManager();
	gfxManager.lockSurface();

	// Draw a basic frame for the button
	drawFrame();

	// Set the font and color
	gfxManager._font.setFontNumber(_fontNumber);

	//
	gfxManager._font._colors.foreground = this->_color1;
	gfxManager._font._colors2.background = this->_color2;
	gfxManager._font._colors2.foreground = this->_color3;

	// Display the button's text
	Rect tempRect(_bounds);
	tempRect.collapse(g_globals->_gfxEdgeAdjust, g_globals->_gfxEdgeAdjust);
	if (g_vm->getFeatures() & GF_CD)
		++tempRect.top;
	gfxManager._font.writeLines(_message.c_str(), tempRect, ALIGN_CENTER);

	gfxManager.unlockSurface();
}

bool GfxButton::process(Event &event) {
	switch (event.eventType) {
	case EVENT_BUTTON_DOWN:
		if (!event.handled) {
			if (_bounds.contains(event.mousePos)) {
				bool result = focusedEvent(event);
				event.handled = true;
				return result;
			}
		}
		break;

	case EVENT_KEYPRESS:
		if (!event.handled && (event.kbd.keycode == _keycode)) {
			// Highlight the button momentarily
			highlight();
			g_system->delayMillis(20);
			highlight();

			event.handled = true;
			return true;
		}

	default:
		break;
	}

	return false;
}

/*--------------------------------------------------------------------------*/

GfxDialog::GfxDialog() {
	_savedArea = NULL;
	_defaultButton = NULL;
}

GfxDialog::~GfxDialog() {
	remove();
}

void GfxDialog::setDefaults() {
	GfxElement::setDefaults();

	// Initialize the embedded graphics manager
	_gfxManager.setDefaults();

	// Figure out a rect needed for all the added elements
	GfxElementList::iterator i;
	Rect tempRect;
	for (i = _elements.begin(); i != _elements.end(); ++i)
		tempRect.extend((*i)->_bounds);

	// Set the dialog boundaries
	_gfxManager._bounds = tempRect;
	tempRect.collapse(-g_globals->_gfxEdgeAdjust * 2, -g_globals->_gfxEdgeAdjust * 2);
	_bounds = tempRect;
}

void GfxDialog::remove() {
	if (_savedArea) {
		// Restore the area the dialog covered
		g_globals->_gfxManagerInstance.copyFrom(*_savedArea, _bounds.left, _bounds.top);

		delete _savedArea;
		_savedArea = NULL;
	}
}

void GfxDialog::draw() {
	Rect tempRect(_bounds);

	// Make a backup copy of the area the dialog will occupy
	_savedArea = surfaceGetArea(g_globals->_gfxManagerInstance.getSurface(), _bounds);

	// Set the palette for use in the dialog
	setPalette();

	_gfxManager.activate();

	// Fill in the contents of the entire dialog
	_gfxManager._bounds = Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
	drawFrame();

	// Reset the dialog's graphics manager to only draw within the dialog boundaries
	tempRect.translate(g_globals->_gfxEdgeAdjust * 2, g_globals->_gfxEdgeAdjust * 2);
	_gfxManager._bounds = tempRect;

	// Draw each element in the dialog in order
	GfxElementList::iterator i;
	for (i = _elements.begin(); i != _elements.end(); ++i) {
		(*i)->draw();
	}

	// If there's a default button, then draw it
	if (_defaultButton) {
		_defaultButton->_flags |= GFXFLAG_THICK_FRAME;
		_defaultButton->draw();
	}

	_gfxManager.deactivate();
}

void GfxDialog::add(GfxElement *element) {
	_elements.push_back(element);
	element->_owner = this;
}

void GfxDialog::addElements(GfxElement *ge, ...) {
	va_list va;
	va_start(va, ge);
	GfxElement *gfxElement = ge;
	while (gfxElement) {
		add(gfxElement);

		gfxElement = va_arg(va, GfxElement *);
	}

	va_end(va);
}

void GfxDialog::setTopLeft(int xp, int yp) {
	_bounds.moveTo(xp - g_globals->_gfxEdgeAdjust * 2, yp - g_globals->_gfxEdgeAdjust * 2);
}

void GfxDialog::setCenter(int xp, int yp) {
	setTopLeft(xp - (_bounds.width() / 2), yp - (_bounds.height() / 2));
}

GfxButton *GfxDialog::execute(GfxButton *defaultButton) {
	_gfxManager.activate();

	if (defaultButton != _defaultButton) {
		if (_defaultButton) {
			_defaultButton->_flags &= ~GFXFLAG_THICK_FRAME;
			_defaultButton->draw();
		}
		_defaultButton = defaultButton;
	}
	if (_defaultButton) {
		_defaultButton->_flags |= GFXFLAG_THICK_FRAME;
		_defaultButton->draw();
	}

	// Event loop
	GfxButton *selectedButton = NULL;

	bool breakFlag = false;
	while (!g_vm->shouldQuit() && !breakFlag) {
		Event event;
		while (g_globals->_events.getEvent(event) && !breakFlag) {
			// Adjust mouse positions to be relative within the dialog
			event.mousePos.x -= _gfxManager._bounds.left;
			event.mousePos.y -= _gfxManager._bounds.top;

			for (GfxElementList::iterator i = _elements.begin(); i != _elements.end(); ++i) {
				if ((*i)->process(event))
					selectedButton = static_cast<GfxButton *>(*i);
			}

			if (selectedButton) {
				breakFlag = true;
				break;
			} else if (!event.handled) {
				if ((event.eventType == EVENT_KEYPRESS) && (event.kbd.keycode == Common::KEYCODE_ESCAPE)) {
					selectedButton = NULL;
					breakFlag = true;
					break;
				} else if ((event.eventType == EVENT_KEYPRESS) && (event.kbd.keycode == Common::KEYCODE_RETURN)) {
					selectedButton = defaultButton;
					breakFlag = true;
					break;
				}
			}
		}

		g_system->delayMillis(10);
		GLOBALS._screenSurface.updateScreen();
	}

	_gfxManager.deactivate();
	if (_defaultButton)
		_defaultButton->_flags &= ~GFXFLAG_THICK_FRAME;

	return selectedButton;
}

void GfxDialog::setPalette() {
	if (g_vm->getGameID() != GType_Ringworld) {
		if (g_vm->getGameID() == GType_BlueForce)
			g_globals->_scenePalette.loadPalette(2);
		g_globals->_scenePalette.setPalette(0, 1);
		g_globals->_scenePalette.setPalette(g_globals->_gfxColors.background, 1);
		g_globals->_scenePalette.setPalette(g_globals->_gfxColors.foreground, 1);
		g_globals->_scenePalette.setPalette(g_globals->_fontColors.background, 1);
		g_globals->_scenePalette.setPalette(g_globals->_fontColors.foreground, 1);
		g_globals->_scenePalette.setEntry(255, 0xff, 0xff, 0xff);
		g_globals->_scenePalette.setPalette(255, 1);
	} else {
		g_globals->_scenePalette.loadPalette(0);
		g_globals->_scenePalette.setPalette(0, 1);
		g_globals->_scenePalette.setPalette(g_globals->_scenePalette._colors.foreground, 1);
		g_globals->_scenePalette.setPalette(g_globals->_fontColors.background, 1);
		g_globals->_scenePalette.setPalette(g_globals->_fontColors.foreground, 1);
		g_globals->_scenePalette.setPalette(255, 1);
	}
}

/*--------------------------------------------------------------------------*/

GfxManager::GfxManager() : _surface(g_globals->_screenSurface), _oldManager(NULL) {
	_font.setOwner(this);
	_font._fillFlag = false;
	_bounds = Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}

GfxManager::GfxManager(GfxSurface &s) : _surface(s), _oldManager(NULL) {
	_font.setOwner(this);
	_font._fillFlag = false;
}

void GfxManager::setDefaults() {
	Rect screenBounds(0, 0, g_system->getWidth(), g_system->getHeight());

	_surface.setBounds(screenBounds);
	_bounds = screenBounds;
	_pane0Rect4 = screenBounds;

	_font._edgeSize = Common::Point(1, 1);
	_font._colors = g_globals->_fontColors;
	_font.setFontNumber(g_globals->_gfxFontNumber);
}

void GfxManager::activate() {
	assert(!contains(g_globals->_gfxManagers, this));
	g_globals->_gfxManagers.push_front(this);
}

void GfxManager::deactivate() {
	// Assert that there will still be another manager, and we're correctly removing our own
	assert((g_globals->_gfxManagers.size() > 1) && (&g_globals->gfxManager() == this));
	g_globals->_gfxManagers.pop_front();
}

int GfxManager::getStringWidth(const char *s, int numChars) {
	return _font.getStringWidth(s, numChars);
}

int GfxManager::getStringWidth(const char *s) {
	return _font.getStringWidth(s);
}

void GfxManager::getStringBounds(const char *s, Rect &bounds, int maxWidth) {
	_font.getStringBounds(s, bounds, maxWidth);
}

void GfxManager::fillArea(int xp, int yp, int color) {
	_surface.setBounds(_bounds);
	Rect tempRect(xp, yp, xp + _font._edgeSize.x, yp + _font._edgeSize.y);
	_surface.fillRect(tempRect, color);
}

void GfxManager::fillRect(const Rect &bounds, int color) {
	_surface.setBounds(_bounds);
	_surface.fillRect(bounds, color);
}

void GfxManager::fillRect2(int xs, int ys, int width, int height, int color) {
	_surface.setBounds(_bounds);
	_surface.fillRect(Rect(xs, ys, xs + width, ys + height), color);
}

/**
 * Sets up the standard palette for dialog displays
 */
void GfxManager::setDialogPalette() {
	// Get the main palette information
	byte palData[256 * 3];
	uint count, start;
	g_resourceManager->getPalette(0, &palData[0], &start, &count);
	g_system->getPaletteManager()->setPalette(&palData[0], start, count);

	// Miscellaneous
	uint32 white = 0xffffffff;
	g_system->getPaletteManager()->setPalette((const byte *)&white, 255, 1);
}

/**
 * Returns the angle of line connecting two points
 */
int GfxManager::getAngle(const Common::Point &p1, const Common::Point &p2) {
	int xDiff = p2.x - p1.x, yDiff = p1.y - p2.y;

	if (!xDiff && !yDiff)
		return -1;
	else if (!xDiff)
		return (p2.y >= p1.y) ? 180 : 0;
	else if (!yDiff)
		return (p2.x >= p1.x) ? 90 : 270;
	else {
		int result = (((xDiff * 100) / ((abs(xDiff) + abs(yDiff))) * 90) / 100);

		if (yDiff < 0)
			result = 180 - result;
		else if (xDiff < 0)
			result += 360;

		return result;
	}
}

void GfxManager::copyFrom(GfxSurface &src, Rect destBounds, Region *priorityRegion) {
	_surface.setBounds(_bounds);

	_surface.copyFrom(src, destBounds, priorityRegion);
}

void GfxManager::copyFrom(GfxSurface &src, int destX, int destY) {
	_surface.setBounds(_bounds);

	_surface.copyFrom(src, destX, destY);
}

void GfxManager::copyFrom(GfxSurface &src, const Rect &srcBounds, const Rect &destBounds) {
	_surface.setBounds(_bounds);

	_surface.copyFrom(src, srcBounds, destBounds);
}

/*--------------------------------------------------------------------------*/


GfxFont::GfxFont() {
	if ((g_vm->getGameID() == GType_Ringworld) && (g_vm->getFeatures() & GF_DEMO))
		_fontNumber = 0;
	else
		_fontNumber = 50;
	_numChars = 0;
	_bpp = 0;
	_fontData = NULL;
	_fillFlag = false;

	_gfxManager = nullptr;
}

GfxFont::~GfxFont() {
	DEALLOCATE(_fontData);
}

/**
 * Sets the current active font number
 *
 * @fontNumber New font number
 */
void GfxFont::setFontNumber(uint32 fontNumber) {
	if ((_fontNumber == fontNumber) && (_fontData))
		return;

	DEALLOCATE(_fontData);

	_fontNumber = fontNumber;

	_fontData = g_resourceManager->getResource(RES_FONT, _fontNumber, 0, true);
	if (!_fontData)
		_fontData = g_resourceManager->getResource(RES_FONT, _fontNumber, 0);

	// Since some TsAGE game versions don't have a valid character count at offset 4, use the offset of the
	// first charactre data to calculate the number of characters in the offset table preceeding it
	_numChars = (READ_LE_UINT32(_fontData + 12) - 12) / 4;
	assert(_numChars <= 256);

	_fontSize.y = READ_LE_UINT16(_fontData + 6);
	_fontSize.x = READ_LE_UINT16(_fontData + 8);
	_bpp = READ_LE_UINT16(_fontData + 10);
}

/**
 * Returns the width of the given specified character
 *
 * @ch Character to return width of
 */
int GfxFont::getCharWidth(char ch) {
	assert(_numChars > 0);
	uint32 charOffset = READ_LE_UINT32(_fontData + 12 + (uint8)ch * 4);
	return _fontData[charOffset] & 0x1f;
}

/**
 * Returns the width of the given string in the current font
 *
 * @s String to return the width of
 * @numChars Number of characters within the string to use
 */
int GfxFont::getStringWidth(const char *s, int numChars) {
	assert(_numChars > 0);
	int width = 0;

	for (; numChars > 0; --numChars, ++s) {
		uint32 charOffset = READ_LE_UINT32(_fontData + 12 + (uint8)*s * 4);
		int charWidth = _fontData[charOffset] & 0x1f;

		width += charWidth;
	}

	return width;
}

/**
 * Returns the width of the given string in the current font
 *
 * @s String to return the width of
 */
int GfxFont::getStringWidth(const char *s) {
	return getStringWidth(s, strlen(s));
}

/**
 * Returns the maximum number of characters for words that will fit into a given width
 *
 * @s Message to be analyzed
 * @maxWidth Maximum allowed width
 */
int GfxFont::getStringFit(const char *&s, int maxWidth) {
	const char *nextWord = NULL;
	const char *sStart = s;
	int numChars = 1;
	char nextChar;

	for (;;) {
		nextChar = *s++;

		if ((nextChar == '\r') || (nextChar == '\0'))
			break;

		// Check if it's a word end
		if (nextChar == ' ') {
			nextWord = s;
		}

		int strWidth = getStringWidth(sStart, numChars);
		if (strWidth > maxWidth) {
			if (nextWord) {
				s = nextWord;
				nextChar = ' ';
			}
			break;
		}

		++numChars;
	}

	int totalChars = s - sStart;
	if (nextChar == '\0')
		--s;
	if ((nextChar == ' ') || (nextChar == '\r') || (nextChar == '\0'))
		--totalChars;

	return totalChars;
}

/**
 * Fills out the passed rect with the dimensions of a given string word-wrapped to a
 * maximum specified width
 *
 * @s Message to be analyzed
 * @bounds Rectangle to put output size into
 * @maxWidth Maximum allowed line width in pixels
 */
void GfxFont::getStringBounds(const char *s, Rect &bounds, int maxWidth) {
	if (maxWidth == 0) {
		// No maximum width, so set bounds for a single line
		bounds.set(0, 0, getStringWidth(s), getHeight());
	} else {
		int numLines = 0;
		int lineWidth = 0;

		// Loop to figure out the number of lines required, and the maximum line width
		while (*s) {
			const char *msg = s;
			int numChars = getStringFit(msg, maxWidth);
			lineWidth = MAX(lineWidth, getStringWidth(s, numChars));

			s = msg;
			++numLines;
		}

		bounds.set(0, 0, lineWidth, numLines * getHeight());
	}
}

/**
 * Writes out a character at the currently set position using the active font
 *
 * @ch Character to display
 */
int GfxFont::writeChar(const char ch) {
	assert((_fontData != NULL) && ((uint8)ch < _numChars));
	uint32 charOffset = READ_LE_UINT32(_fontData + 12 + (uint8)ch * 4);
	int charWidth = _fontData[charOffset] & 0x1f;
	int charHeight = (READ_LE_UINT16(_fontData + charOffset) >> 5) & 0x3f;
	int yOffset = (_fontData[charOffset + 1] >> 3) & 0x1f;
	const uint8 *dataP = &_fontData[charOffset + 2];

	// Lock the surface for access
	Graphics::Surface surfacePtr = _gfxManager->lockSurface();

	Rect charRect;
	charRect.set(0, 0, charWidth, _fontSize.y);
	charRect.translate(_topLeft.x + _position.x, _topLeft.y + _position.y + yOffset);

	if (_fillFlag)
		surfacePtr.fillRect(charRect, _colors.background);

	charRect.bottom = charRect.top + charHeight;

	// Display the character
	int bitCtr = 0;
	uint8 v = 0;
	for (int yp = charRect.top; yp < charRect.bottom; ++yp) {
		byte *destP = (byte *)surfacePtr.getBasePtr(charRect.left, yp);

		for (int xs = 0; xs < charRect.width(); ++xs, ++destP) {
			// Get the next color index to use
			if ((bitCtr % 8) == 0) v = *dataP++;
			int colIndex = 0;
			for (int subCtr = 0; subCtr < _bpp; ++subCtr, ++bitCtr) {
				colIndex = (colIndex << 1) | (v & 0x80 ? 1 : 0);
				v <<= 1;
			}

			switch (colIndex) {
			//case 0: *destP = _colors.background; break;
			case 1: *destP = _colors.foreground; break;
			case 2: *destP = _colors2.background; break;
			case 3: *destP = _colors2.foreground; break;
			}
		}
	}

	// Mark the affected area as dirty
	_gfxManager->getSurface().addDirtyRect(charRect);

	// Move the text writing position
	_position.x += charWidth;

	_gfxManager->unlockSurface();
	return charWidth;
}

/**
 * Writes the specified number of characters from the specified string at the current text position
 *
 * @s String to display
 * @numChars Number of characters to print
 */
void GfxFont::writeString(const char *s, int numChars) {
	// Lock the surface for access
	_gfxManager->lockSurface();

	while ((numChars-- > 0) && (*s != '\0')) {
		writeChar(*s);
		++s;
	}

	// Release the surface lock
	_gfxManager->unlockSurface();
}

/**
 * Writes the the specified string at the current text position
 *
 * @s String to display
 */
void GfxFont::writeString(const char *s) {
	writeString(s, strlen(s));
}

/**
 * Writes a specified string within a given area with support for word wrapping and text alignment types
 *
 * @s String to display
 * @bounds Bounds to display the text within
 * @align Text alignment mode
 */
void GfxFont::writeLines(const char *s, const Rect &bounds, TextAlign align) {
	int lineNum = 0;

	// Lock the surface for access
	_gfxManager->lockSurface();

	while (*s) {
		const char *msgP = s;
		int numChars = getStringFit(msgP, bounds.width());

		_position.y = bounds.top + lineNum * getHeight();

		switch (align) {
		case ALIGN_RIGHT:
			// Right aligned text
			_position.x = bounds.right - getStringWidth(s, numChars);
			writeString(s, numChars);
			break;

		case ALIGN_CENTER:
			// Center aligned text
			_position.x = bounds.left + (bounds.width() / 2) - (getStringWidth(s, numChars) / 2);
			writeString(s, numChars);
			break;

		case ALIGN_JUSTIFIED: {
			// Justified text
			// Get the number of words in the string portion
			int charCtr = 0, numWords = 0;
			while (charCtr < numChars) {
				if (s[charCtr] == ' ')
					++numWords;
				++charCtr;
			}
			// If end of string, count final word
			if (*msgP == '\0')
				++numWords;

			// Display the words of the string
			int spareWidth = bounds.width() - getStringWidth(s, numChars);
			charCtr = 0;
			_position.x = bounds.left;

			while (charCtr < numChars) {
				writeChar(s[charCtr]);
				if ((numWords > 0) && (s[charCtr] == ' ')) {
					int separationWidth = spareWidth / numWords;
					spareWidth -= separationWidth;
					--numWords;
					_position.x += separationWidth;
				}

				++charCtr;
			}
			break;
		}

		case ALIGN_LEFT:
		default:
			// Standard text
			_position.x = bounds.left;
			writeString(s, numChars);
			break;
		}

		// Next line
		s = msgP;
		++lineNum;
	}

	// Release the surface lock
	_gfxManager->unlockSurface();
}

/*--------------------------------------------------------------------------*/

GfxFontBackup::GfxFontBackup() {
	_edgeSize = g_globals->gfxManager()._font._edgeSize;
	_position = g_globals->gfxManager()._font._position;
	_colors = g_globals->gfxManager()._font._colors;
	_fontNumber = g_globals->gfxManager()._font._fontNumber;
}

GfxFontBackup::~GfxFontBackup() {
	g_globals->gfxManager()._font.setFontNumber(_fontNumber);
	g_globals->gfxManager()._font._edgeSize = _edgeSize;
	g_globals->gfxManager()._font._position = _position;
	g_globals->gfxManager()._font._colors = _colors;
}


} // End of namespace TsAGE