aboutsummaryrefslogtreecommitdiff
path: root/sword2/resman.cpp
blob: d5047ed4d3eef21957b90ddaba0913abff568e57 (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
/* Copyright (C) 1994-2003 Revolution Software Ltd
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Header$
 */

#include "stdafx.h"
#include "bs2/sword2.h"
#include "bs2/driver/driver96.h"
#include "bs2/build_display.h"
#include "bs2/console.h"
#include "bs2/debug.h"
#include "bs2/defs.h"
#include "bs2/function.h"
#include "bs2/header.h"
#include "bs2/interpreter.h"
#include "bs2/logic.h"
#include "bs2/maketext.h"
#include "bs2/memory.h"
#include "bs2/mouse.h"	// for system Set_mouse & Set_luggage routines
#include "bs2/protocol.h"
#include "bs2/resman.h"
#include "bs2/sound.h"	// for Clear_fx_queue() called from cacheNewCluster()
#include "bs2/router.h"

namespace Sword2 {

// ---------------------------------------------------------------------------
// welcome to the easy resource manager - written in simple code for easy
// maintenance
// 
// the resource compiler will create two files
//
//	resource.inf which is a list of ascii cluster file names
//	resource.tab which is a table which tells us which cluster a resource
//      is located in and the number within the cluster
// ---------------------------------------------------------------------------

#define NONE	 0
#define FETCHING 1

#define BUFFERSIZE	4096

ResourceManager	res_man;	//declare the object global

// ---------------------------------------------------------------------------
//
//
//	resman.
//
//
// ---------------------------------------------------------------------------

#define BOTH		0x0		// Cluster is on both CDs
#define CD1		0x1		// Cluster is on CD1 only
#define CD2		0x2		// Cluster is on CD2 only
#define LOCAL_CACHE	0x4		// Cluster is cached on HDD
#define LOCAL_PERM	0x8		// Cluster is on HDD.

#if !defined(__GNUC__)
	#pragma START_PACK_STRUCTS
#endif

struct _cd_inf {
	uint8 clusterName[20];	// Null terminated cluster name.
	uint8 cd;		// Cd cluster is on and whether it is on the local drive or not.
} GCC_PACK;

#if !defined(__GNUC__)
	#pragma END_PACK_STRUCTS
#endif

// FIXME: Should init() / exit() be moved to constructor / destructor instead?

void ResourceManager::init(void) {
	// We read in the resource info which tells us the names of the
	// resource cluster files ultimately, although there might be groups
	// within the clusters at this point it makes no difference. We only
	// wish to know what resource files there are and what is in each

	File file;
	uint32 end;
	mem *temp;
	uint32 pos = 0;
	uint32 j = 0;

	_totalClusters = 0;

	if (!file.open("resource.inf")) {
		error("init cannot *OPEN* resource.inf");
	}

	end = file.size();

	//get some space for the incoming resource file - soon to be trashed
	temp = memory.allocMemory(end, MEM_locked, UID_temp);

	if (file.read(temp->ad, end) != end) {
		file.close();
		error("init cannot *READ* resource.inf");
	}

	file.close();

	// ok, we've loaded in the resource.inf file which contains a list of
	// all the files now extract the filenames
	do {
		// item must have an #0d0a
		while(temp->ad[j] != 13) {
			_resourceFiles[_totalClusters][pos] = temp->ad[j];
			j++;
			pos++;
		}

		// NULL terminate our extracted string
		_resourceFiles[_totalClusters][pos]=0;

		// Reset position in current slot between entries, skip the
		// 0x0a in the source and increase the number of clusters.

		pos = 0;
		j += 2;
		_totalClusters++;

		// TODO: put overload check here
	} while (j != end);	// using this method the Gode generated resource.inf must have #0d0a on the last entry

	// now load in the binary id to res conversion table
	if (!file.open("resource.tab")) {
		error("init cannot *OPEN* resource.tab");
	}

	// find how many resources
	end = file.size();

	_totalResFiles = end / 4;

	// table seems ok so malloc some space
	_resConvTable = (uint16 *) malloc(end);

	for (j = 0; j < end / 2; j++)
		_resConvTable[j] = file.readUint16LE();

	if (file.ioFailed()) {
		file.close();
		error("init cannot *READ* resource.tab");
	}

	file.close();

	if (!file.open("cd.inf")) {
		error("init cannot *OPEN* cd.inf");
	}

	_cd_inf *cdInf = new _cd_inf[_totalClusters];

	for (j = 0; j < _totalClusters; j++) {
		file.read(cdInf[j].clusterName, sizeof(cdInf[j].clusterName));
		cdInf[j].cd = file.readByte();
		
		if (file.ioFailed()) {
			error("init failed to read cd.inf. Insufficient entries?");
		}
	}

	file.close();

	for (j = 0; j < _totalClusters; j++) {
		uint32 i = 0;

		while (scumm_stricmp((char *) cdInf[i].clusterName, _resourceFiles[j]) != 0 && i < _totalClusters)
			i++;

		if (i == _totalClusters) {
			error("init, %s is not in cd.inf", _resourceFiles[j]);
		} else
			_cdTab[j] = cdInf[i].cd;
	}


	debug(5, "%d resources in %d cluster files", _totalResFiles, _totalClusters);
	for (j = 0; j < _totalClusters; j++)
		debug(5, "filename of cluster %d: -%s", j, _resourceFiles[j]);

	// create space for a list of pointers to mem's
	_resList = (mem **) malloc(_totalResFiles * sizeof(mem *));

	_age = (uint32 *) malloc(_totalResFiles * sizeof(uint32));
	_count = (uint16 *) malloc(_totalResFiles * sizeof(uint16));

	for (j = 0; j < _totalResFiles; j++) {
		// age must be 0 if the file is not in memory at all
		_age[j] = 0;
		_count[j] = 0;
	}

	_resTime = 1;	//cannot start at 0
	memory.freeMemory(temp);	//get that memory back

	// FIXME: Is this really needed?

	if (!file.open("revcd1.id")) {
		int index = 0;
/*
		// Scan for CD drives.
		for (char c = 'C'; c <= 'Z'; c++) {
			sprintf(_cdPath, "%c:\\", c);
			if (GetDriveType(_cdPath) == DRIVE_CDROM)
				_cdDrives[index++] = c;
		}
*/
		_cdDrives[index++] = 'C';
		
		if (index == 0) {
			error("init, cannot find CD drive");
		}

		while (index < 24)
			_cdDrives[index++] = 0;
	}
	else
		file.close();
}

void ResourceManager::exit(void) {
	// free up our mallocs
	free(_resList);
	free(_age);
	free(_count);
}

// Quick macro to make swapping in-place easier to write

#define SWAP16(x)	x = SWAP_BYTES_16(x)
#define SWAP32(x)	x = SWAP_BYTES_32(x)

void convertEndian(uint8 *file, uint32 len) {
	int i;
	_standardHeader *hdr = (_standardHeader *)file;
	
	file += sizeof(_standardHeader);

	SWAP32(hdr->compSize);
	SWAP32(hdr->decompSize);

	switch (hdr->fileType) {
	case ANIMATION_FILE: {
		_animHeader *animHead = (_animHeader *)file;

		SWAP16(animHead->noAnimFrames);
		SWAP16(animHead->feetStartX);
		SWAP16(animHead->feetStartY);
		SWAP16(animHead->feetEndX);
		SWAP16(animHead->feetEndY);
		SWAP16(animHead->blend);

		_cdtEntry *cdtEntry = (_cdtEntry *) (file + sizeof(_animHeader));
		for (i = 0; i < animHead->noAnimFrames; i++, cdtEntry++) {
			SWAP16(cdtEntry->x);
			SWAP16(cdtEntry->y);
			SWAP32(cdtEntry->frameOffset);

			_frameHeader *frameHeader = (_frameHeader *) (file + cdtEntry->frameOffset);
			// Quick trick to prevent us from incorrectly applying the endian
			// fixes multiple times. This assumes that frames are less than 1 MB
			// and have height/width less than 4096.
			if ((frameHeader->compSize & 0xFFF00000) ||
				(frameHeader->width & 0xF000) ||
				(frameHeader->height & 0xF000)) {
				SWAP32(frameHeader->compSize);
				SWAP16(frameHeader->width);
				SWAP16(frameHeader->height);
			}
		}
		break;
	}
	case SCREEN_FILE: {
		_multiScreenHeader *mscreenHeader = (_multiScreenHeader *) file;

		SWAP32(mscreenHeader->palette);
		SWAP32(mscreenHeader->bg_parallax[0]);
		SWAP32(mscreenHeader->bg_parallax[1]);
		SWAP32(mscreenHeader->screen);
		SWAP32(mscreenHeader->fg_parallax[0]);
		SWAP32(mscreenHeader->fg_parallax[1]);
		SWAP32(mscreenHeader->layers);
		SWAP32(mscreenHeader->paletteTable);
		SWAP32(mscreenHeader->maskOffset);

		// screenHeader
		_screenHeader *screenHeader = (_screenHeader*) (file + mscreenHeader->screen);

		SWAP16(screenHeader->width);
		SWAP16(screenHeader->height);
		SWAP16(screenHeader->noLayers);

		// layerHeader
		_layerHeader *layerHeader = (_layerHeader *) (file + mscreenHeader->layers);
		for (i = 0; i < screenHeader->noLayers; i++, layerHeader++) {
			SWAP16(layerHeader->x);
			SWAP16(layerHeader->y);
			SWAP16(layerHeader->width);
			SWAP16(layerHeader->height);
			SWAP32(layerHeader->maskSize);
			SWAP32(layerHeader->offset);
		}

		// backgroundParallaxLayer
		_parallax *parallax;
		int offset;
		offset = mscreenHeader->bg_parallax[0];
		if (offset > 0) {
			parallax = (_parallax *) (file + offset);
			SWAP16(parallax->w);
			SWAP16(parallax->h);
		}

		offset = mscreenHeader->bg_parallax[1];
		if (offset > 0) {
			parallax = (_parallax *) (file + offset);
			SWAP16(parallax->w);
			SWAP16(parallax->h);
		}

		// backgroundLayer
		offset = mscreenHeader->screen + sizeof(_screenHeader);
		if (offset > 0) {
			parallax = (_parallax *) (file + offset);
			SWAP16(parallax->w);
			SWAP16(parallax->h);
		}

		// foregroundParallaxLayer
		offset = mscreenHeader->fg_parallax[0];
		if (offset > 0) {
			parallax = (_parallax *) (file + offset);
			SWAP16(parallax->w);
			SWAP16(parallax->h);
		}

		offset = mscreenHeader->fg_parallax[1];
		if (offset > 0) {
			parallax = (_parallax *) (file + offset);
			SWAP16(parallax->w);
			SWAP16(parallax->h);
		}
		break;
	}
	case GAME_OBJECT: {
		_object_hub *objectHub = (_object_hub *)file;

		objectHub->type = (int)SWAP_BYTES_32(objectHub->type);
		SWAP32(objectHub->logic_level);

		for (i = 0; i < TREE_SIZE; i++) {
			SWAP32(objectHub->logic[i]);
			SWAP32(objectHub->script_id[i]);
			SWAP32(objectHub->script_pc[i]);
		}
		break;
	}
	case WALK_GRID_FILE: {
		_walkGridHeader	*walkGridHeader = (_walkGridHeader *)file;

		SWAP32(walkGridHeader->numBars);
		SWAP32(walkGridHeader->numNodes);

		_barData *barData = (_barData *) (file + sizeof(_walkGridHeader));
		for (i = 0; i < walkGridHeader->numBars; i++) {
			SWAP16(barData->x1);
			SWAP16(barData->y1);
			SWAP16(barData->x2);
			SWAP16(barData->y2);
			SWAP16(barData->xmin);
			SWAP16(barData->ymin);
			SWAP16(barData->xmax);
			SWAP16(barData->ymax);
			SWAP16(barData->dx);
			SWAP16(barData->dy);
			SWAP32(barData->co);
			barData++;
		}

		uint16 *node = (uint16 *) (file + sizeof(_walkGridHeader) + walkGridHeader->numBars * sizeof(_barData));
		for (i = 0; i < walkGridHeader->numNodes*2; i++) {
			SWAP16(*node);
			node++;
		}

		break;
	}
	case GLOBAL_VAR_FILE:
		break;
	case PARALLAX_FILE_null:
		break;
	case RUN_LIST: {
		uint32 *list = (uint32 *)file;
		while (*list) {
			SWAP32(*list);
			list++;
		}
		break;
	}
	case TEXT_FILE: {
		_textHeader *textHeader = (_textHeader *)file;
		SWAP32(textHeader->noOfLines);
		break;
	}
	case SCREEN_MANAGER:
		break;
	case MOUSE_FILE:
		break;
	case ICON_FILE:
		break;
	}
}

uint8 *ResourceManager::open(uint32 res) {
	// returns ad of resource. Loads if not in memory
	// retains a count
	// resource can be aged out of memory if count = 0
	// the resource is locked while count != 0 i.e. until a res_close is
	// called

	File	file;
	uint16	parent_res_file;
	uint16	actual_res;
	uint32	pos, len;

	uint32	table_offset;

//#ifdef _SWORD2_DEBUG
	if (res >= _totalResFiles)
		error("open illegal resource %d (there are %d resources 0-%d)", res, _totalResFiles, _totalResFiles - 1);
//#endif

	// is the resource in memory already?
	// if the file is not in memory then age should and MUST be 0
	if (!_age[res]) {
		// fetch the correct file and read in the correct portion
		// if the file cannot fit then we must trash the oldest large
		// enough floating file

		// points to the number of the ascii filename
		parent_res_file = _resConvTable[res * 2];

//#ifdef _SWORD2_DEBUG
		if (parent_res_file == 0xffff)
			error("open tried to open null & void resource number %d", res);
//#endif

		// relative resource within the file
		actual_res = _resConvTable[(res * 2) + 1];

		// first we have to find the file via the _resConvTable

		debug(5, "resOpen %s res %d", _resourceFiles[parent_res_file], res);

		// ** at this point here we start to think about where the
		// ** file is and prompt the user for the right CD to be
		// ** inserted
		// **
		// ** we need to know the position that we're at within the
		// ** game - LINC should write this someplace.

/* these probably aren't necessary - khalek
		if (!(_cdTab[parent_res_file] & LOCAL_CACHE) && !(_cdTab[parent_res_file] & LOCAL_PERM)) {
			// This cluster is on a CD, we need to cache a new one.
			cacheNewCluster(parent_res_file);
		} else if (!(_cdTab[parent_res_file] & LOCAL_PERM)) {
			// Makes sure that the correct CD is in the drive.
			getCd(_cdTab[parent_res_file] & 3);
		}
*/

		// This part of the cluster caching is pretty useful though:
		//
		// If we're loading a cluster that's only available from one
		// of the CDs, remember which one so that we can play the
		// correct music.
		//
		// The code to ask for the correct CD will probably be needed
		// later, too.
		//
		// And there's some music / FX stuff in cacheNewCluster() that
		// might be needed as well.
		//
		// But this will do for now.

		if (!(_cdTab[parent_res_file] & LOCAL_PERM)) {
			_curCd = _cdTab[parent_res_file] & 3;
		}

		// open the cluster file
		if (!file.open(_resourceFiles[parent_res_file]))
			error("open cannot *OPEN* %s", _resourceFiles[parent_res_file]);


		// 1st DWORD of a cluster is an offset to the look-up table
		table_offset = file.readUint32LE();

		debug(5, "table offset = %d", table_offset);

		// 2 dwords per resource
		file.seek(table_offset + actual_res * 8, SEEK_SET);
		// get position of our resource within the cluster file
		pos = file.readUint32LE();
		// read the length
		len = file.readUint32LE();

		// ** get to position in file of our particular resource
		file.seek(pos, SEEK_SET);

		debug(5, "res len %d", len);

		// ok, we know the length so try and allocate the memory
		// if it can't then old files will be ditched until it works
		_resList[res] = memory.allocMemory(len, MEM_locked, res);

		// now load the file
		// hurray, load it in.
		file.read(_resList[res]->ad, len);

		//close the cluster
		file.close();

#ifdef SCUMM_BIG_ENDIAN
		convertEndian((uint8 *) _resList[res]->ad, len);
#endif
	} else {
		debug(5, "RO %d, already open count=%d", res, _count[res]);
	}

	// number of times opened - the file won't move in memory while count
	// is non zero
	_count[res]++;

	// update the accessed time stamp - touch the file in other words
	_age[res] = _resTime;

	// pass the address of the mem & lock the memory too
	// might be locked already (if count > 1)
	memory.lockMemory(_resList[res]);

	return (uint8 *) _resList[res]->ad;
}

uint8 ResourceManager::checkValid(uint32 res) {
	// returns '1' if resource is valid, otherwise returns '0'
	// used in startup.cpp to ignore invalid screen-manager resources

	uint16 parent_res_file;

	// resource number out of range
	if (res >= _totalResFiles)
		return 0;

	// points to the number of the ascii filename
	parent_res_file = _resConvTable[res * 2];

	// null & void resource
	if (parent_res_file == 0xffff)
		return 0;

	// ok
	return 1;
}

void ResourceManager::nextCycle(void) {
	// increment the cycle and calculate actual per-cycle memory useage

#ifdef _SWORD2_DEBUG
	uint32 j;
#endif

#ifdef _SWORD2_DEBUG
	_currentMemoryUsage = 0;

	for (j = 1; j < _totalResFiles; j++) {
		// was accessed last cycle
		if (_age[j] == _resTime)
			_currentMemoryUsage += _resList[j]->size;
	}
#endif

	_resTime++;

	// if you left the game running for a hundred years when this went to 0
	// there'd be a resource left stuck in memory - after another hundred
	// years there'd be another...
	//
	// Mind you, by then the our get_msecs() function will have wrapped
	// around too, probably causing a mess of other problems.

	if (!_resTime)
		_resTime++;
}

uint32 ResourceManager::fetchUsage(void) {
	// returns memory usage previous cycle
	return _currentMemoryUsage;
}

void ResourceManager::close(uint32 res) {
	// decrements the count
	// resource floats when count = 0

//#ifdef _SWORD2_DEBUG
	if (res >= _totalResFiles)
		error("closing illegal resource %d (there are %d resources 0-%d)", res, _totalResFiles, _totalResFiles - 1);

	//closing but isnt open?
	if (!(_count[res]))
		error("close: closing %d but it isn't open", res);
//#endif

	//one less has it open
	_count[res]--;

	//if noone has the file open then unlock and allow to float
	if (!_count[res]) {
		// pass the address of the mem
		memory.floatMemory(_resList[res]);
	}
}

uint32 ResourceManager::fetchLen(uint32 res) {
	// returns the total file length of a resource - i.e. all headers are
	// included too

	File fh;
	uint16 parent_res_file;
	uint16 actual_res;
	uint32 len;
	uint32 table_offset;

	// points to the number of the ascii filename
	parent_res_file = _resConvTable[res * 2];

	// relative resource within the file
	actual_res = _resConvTable[(res * 2) + 1];

	// first we have to find the file via the _resConvTable
	// open the cluster file

	if (!fh.open(_resourceFiles[parent_res_file]))
		error("fetchLen cannot *OPEN* %s", _resourceFiles[parent_res_file]);

	// 1st DWORD of a cluster is an offset to the look-up table
	table_offset = fh.readUint32LE();

	// 2 dwords per resource + skip the position dword
	fh.seek(table_offset + (actual_res * 8) + 4, SEEK_SET);

	// read the length
	len = fh.readUint32LE();
	return len;
}

char *ResourceManager::fetchCluster(uint32 res) {
	// returns a pointer to the ascii name of the cluster file which
	// contains resource res
	return _resourceFiles[_resConvTable[res * 2]];
}

uint32 ResourceManager::fetchAge(uint32 res) {
	// return the age of res
	return _age[res];
}

uint32 ResourceManager::fetchCount(uint32 res) {
	// return the open count of res
	return _count[res];
}

uint32 ResourceManager::helpTheAgedOut(void) {
	// remove from memory the oldest closed resource

	uint32 oldest_res;	// holds id of oldest found so far when we have to chuck stuff out of memory
	uint32 oldest_age;	// age of above during search
	uint32 j;
	uint32 largestResource = 0;

	oldest_age = _resTime;
	oldest_res = 0;

	for (j = 2; j < _totalResFiles; j++) {
		// not held open and older than this one
		if (!_count[j] && _age[j] && _age[j] <= oldest_age) {	
			if (_age[j] == oldest_age && _resList[j]->size > largestResource)	{
				// Kick old resource of oldest age and largest
				// size (Helps the poor defragger).
				oldest_res = j;
				largestResource = _resList[j]->size;
			} else if (_age[j] < oldest_age)	{
				oldest_res = j;
				oldest_age = _age[j];
				largestResource = _resList[j]->size;
			}
		}
	}

	// there was not a file we could release
	// no bytes released - oh dear, lets hope this never happens
	if (!oldest_res)
		return 0;

	debug(5, "removing %d, age %d, size %d", oldest_res, _age[oldest_res], _resList[oldest_res]->size);

	// trash this old resource

	_age[oldest_res] = 0;		// effectively gone from _resList
	memory.freeMemory(_resList[oldest_res]);	// release the memory too

	return _resList[oldest_res]->size;	// return bytes freed
}

void ResourceManager::printConsoleClusters(void) {
	if (_totalClusters) {
		for (uint i = 0; i < _totalClusters; i++)
			Debug_Printf("%s\n", _resourceFiles[i]);
		Debug_Printf("%d resources\n", _totalResFiles);
	} else
		Debug_Printf("Argh! No resources!\n");
}

void ResourceManager::examine(int res) {
	_standardHeader	*file_header;

	if (res < 0 || res >= (int) _totalResFiles)
		Debug_Printf("Illegal resource %d (there are %d resources 0-%d)\n", res, _totalResFiles, _totalResFiles - 1);
	else if (_resConvTable[res * 2] == 0xffff)
		Debug_Printf("%d is a null & void resource number\n", res);
	else {
		//open up the resource and take a look inside!
		file_header = (_standardHeader*) res_man.open(res);

		// Debug_Printf("%d\n", file_header->fileType);
		// Debug_Printf("%s\n", file_header->name);

		//----------------------------------------------------
		// resource types: (taken from header.h)

		// 1:  ANIMATION_FILE
		//      all normal animations & sprites including mega-sets &
		//	font files which are the same format
		// 2:  SCREEN_FILE
		//      each contains background, palette, layer sprites,
		//	parallax layers & shading mask
		// 3:  GAME_OBJECT
		//      each contains object hub + structures + script data
		// 4:  WALK_GRID_FILE
		//      walk-grid data
		// 5:  GLOBAL_VAR_FILE
		//      all the global script variables in one file; "there can
		//	be only one"
		// 6:  PARALLAX_FILE_null
		//      NOT USED
		// 7:  RUN_LIST
		//      each contains a list of object resource ids
		// 8:  TEXT_FILE
		//      each contains all the lines of text for a location or a
		//	character's conversation script
		// 9:  SCREEN_MANAGER
		//      one for each location; this contains special startup
		//	scripts
		// 10: MOUSE_FILE
		//      mouse pointers and luggage icons (sprites in General,
		//	Mouse pointers & Luggage icons)
		// 11: WAV_FILE
		//      NOT USED HERE
		// 12: ICON_FILE
		//      menu icon (sprites in General and Menu icons)
		// 13: PALETTE_FILE
		//      NOT USED HERE
		//----------------------------------------------------

		switch (file_header->fileType) {
		case ANIMATION_FILE:
			Debug_Printf("<anim> %s\n", file_header->name);
			break;
		case SCREEN_FILE:
			Debug_Printf("<layer> %s\n", file_header->name);
			break;
		case GAME_OBJECT:
			Debug_Printf("<game object> %s\n", file_header->name);
			break;
		case WALK_GRID_FILE:
			Debug_Printf("<walk grid> %s\n", file_header->name);
			break;
		case GLOBAL_VAR_FILE:
			Debug_Printf("<global variables> %s\n", file_header->name);
			break;
		case PARALLAX_FILE_null:
			Debug_Printf("<parallax file NOT USED!> %s\n", file_header->name);
			break;
		case RUN_LIST:
			Debug_Printf("<run list> %s\n", file_header->name);
			break;
		case TEXT_FILE:
			Debug_Printf("<text file> %s\n", file_header->name);
			break;
		case SCREEN_MANAGER:
			Debug_Printf("<screen manager> %s\n", file_header->name);
			break;
		case MOUSE_FILE:
			Debug_Printf("<mouse pointer> %s\n", file_header->name);
			break;
		case ICON_FILE:
			Debug_Printf("<menu icon> %s\n", file_header->name);
			break;
		default:
			Debug_Printf("unrecognised fileType %d\n", file_header->fileType);
			break;
		}
		res_man.close(res);
	}
}

void ResourceManager::kill(int res) {
	if (res < 0 || res >= (int) _totalResFiles) {
		Debug_Printf("Illegal resource %d (there are %d resources 0-%d)\n", res, _totalResFiles, _totalResFiles - 1);
		return;
	}

	// if noone has the file open then unlock and allow to float
	if (!_count[res]) {
		if (_age[res]) {
			_age[res] = 0;		// effectively gone from _resList
			memory.freeMemory(_resList[res]);	// release the memory too
			Debug_Printf("Trashed %d\n", res);
		} else
			Debug_Printf("%d not in memory\n", res);
	} else
		Debug_Printf("File is open - cannot remove\n");
}

void ResourceManager::remove(uint32 res) {
	if (_age[res]) {
		_age[res] = 0;			// effectively gone from _resList
		memory.freeMemory(_resList[res]);	// release the memory too
		debug(5, " - Trashing %d", res);
	} else
		debug(5, "remove(%d) not even in memory!", res);
}

void ResourceManager::removeAll(void) {
	// remove all res files from memory - ready for a total restart
	// including player object & global variables resource

	int j;
	uint32 res;

	j = memory._baseMemBlock;

	do {
		if (memory._memList[j].uid < 65536) {	// a resource
			res = memory._memList[j].uid;
			_age[res] = 0;		// effectively gone from _resList
			memory.freeMemory(_resList[res]);	// release the memory too
		}

		j = memory._memList[j].child;
	} while	(j != -1);
}

void ResourceManager::killAll(bool wantInfo) {
	// remove all res files from memory
	// its quicker to search the mem blocs for res files than search
	// resource lists for those in memory

	int j;
	uint32 res;
	uint32 nuked = 0;
  	_standardHeader *header;

	j = memory._baseMemBlock;

	do {
		if (memory._memList[j].uid < 65536) {	// a resource
			res = memory._memList[j].uid;

			// not the global vars which are assumed to be open in
			// memory & not the player object!
			if (res != 1 && res != CUR_PLAYER_ID) {
				header = (_standardHeader *) res_man.open(res);
				res_man.close(res);

				_age[res] = 0;		// effectively gone from _resList
				memory.freeMemory(_resList[res]);	// release the memory too
				nuked++;

				// if this was called from the console,
				if (wantInfo) {
					Debug_Printf("Nuked %5d: %s\n", res, header->name);
					debug(5, " nuked %d: %s", res, header->name);
				}	
			}
		}
		j = memory._memList[j].child;
	} while (j != -1);

	// if this was called from the console
	if (wantInfo) {
		Debug_Printf("Expelled %d resource(s)\n", nuked);
	}
}

//----------------------------------------------------------------------------
// Like killAll but only kills objects (except George & the variable table of
// course) - ie. forcing them to reload & restart their scripts, which
// simulates the effect of a save & restore, thus checking that each object's
// re-entrant logic works correctly, and doesn't cause a statuette to
// disappear forever, or some plaster-filled holes in sand to crash the game &
// get James in trouble again.

void ResourceManager::killAllObjects(bool wantInfo) {
	// remove all object res files from memory, excluding George
	// its quicker to search the mem blocs for res files than search
	// resource lists for those in memory

	int j;
	uint32 res;
	uint32 nuked = 0;
 	_standardHeader *header;

	j = memory._baseMemBlock;

	do {
		if (memory._memList[j].uid < 65536) {	// a resource
			res = memory._memList[j].uid;
			//not the global vars which are assumed to be open in
			// memory & not the player object!
			if (res != 1 && res != CUR_PLAYER_ID) {
				header = (_standardHeader*) res_man.open(res);
				res_man.close(res);

				if (header->fileType == GAME_OBJECT) {
					_age[res] = 0;		// effectively gone from _resList
					memory.freeMemory(_resList[res]);	// release the memory too
   					nuked++;

					// if this was called from the console
					if (wantInfo) {
						Debug_Printf("Nuked %5d: %s\n", res, header->name);
						debug(5, " nuked %d: %s", res, header->name);
					}	
				}
			}
		}
		j = memory._memList[j].child;
	} while (j != -1);

	// if this was called from the console
	if (wantInfo)
		Debug_Printf("Expelled %d object resource(s)\n", nuked);
}

void ResourceManager::cacheNewCluster(uint32 newCluster) {
	// Stop any music from streaming off the CD before we start the
	// cluster-copy!
	//
	// eg. the looping restore-panel music will still be playing if we
	// restored a game to a different cluster on the same CD - and music
	// streaming would interfere with cluster copying, slowing it right
	// down - but if we restored to a different CD the music is stopped
	// in getCd() when it asks for the CD

	g_logic.fnStopMusic(NULL);

	Clear_fx_queue();	// stops all fx & clears the queue (James22july97)
	getCd(_cdTab[newCluster] & 3);

	// Kick out old cached cluster and load the new one.
	uint32 i = 0;
	while (!(_cdTab[i] & LOCAL_CACHE) && i < _totalClusters)
		i++;

	if (i < _totalClusters)	{
		SVM_SetFileAttributes(_resourceFiles[i], FILE_ATTRIBUTE_NORMAL);
		SVM_DeleteFile(_resourceFiles[i]);
		_cdTab[i] &= (0xff - LOCAL_CACHE);
		FILE *file;
		file = fopen("cd.inf", "r+b");

		if (file == NULL) {
			error("init cannot *OPEN* cd.inf");
		}

		_cd_inf cdInf;
		
		do {
			fread(&cdInf, 1, sizeof(_cd_inf), file);
		} while ((scumm_stricmp((char *) cdInf.clusterName, _resourceFiles[i]) != 0) && !feof(file));

		if (feof(file)) {
			error("cacheNewCluster cannot find %s in cd.inf", _resourceFiles[i]);
		}

		fseek(file, -1, SEEK_CUR);
		fwrite(&_cdTab[i], 1, 1, file);
		fclose(file);
	}

	char buf[1024];
	sprintf(buf, "%sClusters\\%s", _cdPath, _resourceFiles[newCluster]);

	g_display->waitForFade();

	if (g_display->getFadeStatus() != RDFADE_BLACK) {
		g_display->fadeDown();
		g_display->waitForFade();
	}

	g_display->clearScene();

	Set_mouse(0);
	Set_luggage(0);

	uint8 *bgfile;
	bgfile = res_man.open(2950);	// open the screen resource
	g_display->initialiseBackgroundLayer(NULL);
	g_display->initialiseBackgroundLayer(NULL);
	g_display->initialiseBackgroundLayer(FetchBackgroundLayer(bgfile));
	g_display->initialiseBackgroundLayer(NULL);
	g_display->initialiseBackgroundLayer(NULL);
	g_display->setPalette(0, 256, FetchPalette(bgfile), RDPAL_FADE);

	g_display->renderParallax(FetchBackgroundLayer(bgfile), 2);
	res_man.close(2950);		// release the screen resource

	// Git rid of read-only status, if it is set.
	SVM_SetFileAttributes(_resourceFiles[newCluster], FILE_ATTRIBUTE_NORMAL);

	File inFile, outFile;
	
	inFile.open(buf);
	outFile.open(_resourceFiles[newCluster], NULL, File::kFileWriteMode);

	if (!inFile.isOpen() || !outFile.isOpen()) {
		error("Cache new cluster could not copy %s to %s", buf, _resourceFiles[newCluster]);
	}

	_spriteInfo textSprite;
	_spriteInfo barSprite;
	mem *text_spr;
	_frameHeader *frame;
	uint8 *loadingBar;
	_cdtEntry *cdt;

	text_spr = fontRenderer.makeTextSprite(FetchTextLine(res_man.open(2283), 8) + 2, 640, 187, g_sword2->_speechFontId);

	frame = (_frameHeader*) text_spr->ad;

	textSprite.x = g_display->_screenWide /2 - frame->width / 2;
	textSprite.y = g_display->_screenDeep /2 - frame->height / 2 - RDMENU_MENUDEEP;
	textSprite.w = frame->width;
	textSprite.h = frame->height;
	textSprite.scale = 0;
	textSprite.scaledWidth	= 0;
	textSprite.scaledHeight	= 0;
	textSprite.type = RDSPR_DISPLAYALIGN | RDSPR_NOCOMPRESSION | RDSPR_TRANS;
	textSprite.blend = 0;
	textSprite.colourTable	= 0;

	res_man.close(2283);

	loadingBar = res_man.open(2951);

	frame = FetchFrameHeader(loadingBar, 0);
	cdt   = FetchCdtEntry(loadingBar, 0);

	barSprite.x = cdt->x;
	barSprite.y = cdt->y;
	barSprite.w = frame->width;
	barSprite.h = frame->height;
	barSprite.scale = 0;
	barSprite.scaledWidth = 0;
	barSprite.scaledHeight = 0;
	barSprite.type = RDSPR_RLE256FAST | RDSPR_TRANS;
	barSprite.blend = 0;
	barSprite.colourTable = 0;

	res_man.close(2951);

	loadingBar = res_man.open(2951);
	frame = FetchFrameHeader(loadingBar, 0);
	barSprite.data = (uint8 *) (frame + 1);
	res_man.close(2951);

	int16 barX = barSprite.x;
	int16 barY = barSprite.y;
	int16 textX = textSprite.x;
	int16 textY = textSprite.y;

	g_display->drawSprite(&barSprite);
	barSprite.x = barX;
	barSprite.y = barY;

	textSprite.data	= text_spr->ad + sizeof(_frameHeader);
	g_display->drawSprite(&textSprite);
	textSprite.x = textX;
	textSprite.y = textY;

	g_display->fadeUp();
	g_display->waitForFade();

	uint32 size = inFile.size();

	char buffer[BUFFERSIZE];
	int stepSize = (size / BUFFERSIZE) / 100;
	uint32  read = 0;
	int step = stepSize;
	int fr = 0;
	uint32 realRead = 0;

	do {
		realRead = inFile.read(buffer, BUFFERSIZE);
		read += realRead;
		if (outFile.write(buffer, realRead) != realRead) {
			error("Cache new cluster could not copy %s to %s", buf, _resourceFiles[newCluster]);
		}

		if (step == stepSize) {
			step = 0;
			// open the screen resource
			bgfile = res_man.open(2950);
			g_display->renderParallax(FetchBackgroundLayer(bgfile), 2);
			// release the screen resource
			res_man.close(2950);
			loadingBar = res_man.open(2951);
			frame = FetchFrameHeader(loadingBar, fr);
			barSprite.data = (uint8 *) (frame + 1);
			res_man.close(2951);
			g_display->drawSprite(&barSprite);
			barSprite.x = barX;
			barSprite.y = barY;

			textSprite.data	= text_spr->ad + sizeof(_frameHeader);
			g_display->drawSprite(&textSprite);
			textSprite.x = textX;
			textSprite.y = textY;

			fr++;
		} else
			step++;

		g_display->updateDisplay();
	} while ((read % BUFFERSIZE) == 0);

	if (read != size) {
		error("Cache new cluster could not copy %s to %s", buf, _resourceFiles[newCluster]);
	}

	inFile.close();
	outFile.close();
	memory.freeMemory(text_spr);

	g_display->clearScene();

	g_display->fadeDown();
	g_display->waitForFade();
	g_display->fadeUp();

	// Git rid of read-only status.
	SVM_SetFileAttributes(_resourceFiles[newCluster], FILE_ATTRIBUTE_NORMAL);

	// Update cd.inf and _cdTab
	_cdTab[newCluster] |= LOCAL_CACHE;

	FILE *file;
	file = fopen("cd.inf", "r+b");

	if (file == NULL) {
		error("init cannot *OPEN* cd.inf");
	}

	_cd_inf cdInf;
	
	do {
		fread(&cdInf, 1, sizeof(_cd_inf), file);
	} while (scumm_stricmp((char *) cdInf.clusterName, _resourceFiles[newCluster]) != 0 && !feof(file));

	if (feof(file)) {
		error("cacheNewCluster cannot find %s in cd.inf", _resourceFiles[newCluster]);
	}

	fseek(file, -1, SEEK_CUR);
	fwrite(&_cdTab[newCluster], 1, 1, file);
	fclose(file);
}

void ResourceManager::getCd(int cd) {
	// TODO support a seperate path for cd data?
	
	bool done = false;
	char sCDName[_MAX_PATH];
	uint32 dwMaxCompLength, dwFSFlags;
	mem *text_spr;
	_frameHeader *frame;
	_spriteInfo spriteInfo;
	int16 oldY;
	int16 oldX;
	FILE *file;
	char name[16];
	int offNetwork = 0;
	int index = 0;
	uint8 *textRes;

	// don't ask for CD's in the playable demo downloaded from our
	// web-site!
	if (g_sword2->_features & GF_DEMO)
		return;

#ifdef _PCGUIDE
	// don't ask for CD in the patch for the demo on "PC Guide" magazine
	return;
#endif

	sprintf(name, "revcd%d.id", cd);
	file = fopen(name, "r");

	if (file == NULL) {
		// Determine what CD is in the drive, and either use it or ask
		// the user to insert the correct CD.
		// Scan all CD drives for our CD as well.
		while(_cdDrives[index] != 0 && index < 24) {
			sprintf(_cdPath, "%c:\\", _cdDrives[index]);

			if (!SVM_GetVolumeInformation(_cdPath, sCDName, _MAX_PATH, NULL, &dwMaxCompLength, &dwFSFlags, NULL, 0))	{
				// Force the following code to ask for the correct CD.
				sCDName[0] = 0;
			}

			_curCd = cd;
		
			if (!scumm_stricmp(sCDName,CD1_LABEL)) {
				if (cd == CD1)
					return;
			} else if (!scumm_stricmp(sCDName,CD2_LABEL)) {
				if (cd == CD2)
					return;
			}

			index++;
		}
	} else {
		// must be running off the network, but still want to see
		// CD-requests to show where they would occur when playing
		// from CD
		debug(5, "RUNNING OFF NETWORK");

		fscanf(file, "%s", _cdPath);
		fclose(file);

		if (_curCd == cd)
			return;
		else
			_curCd = cd;

		// don't show CD-requests if testing anims or text/speech
		if (SYSTEM_TESTING_ANIMS || SYSTEM_TESTING_TEXT)
			return;

		offNetwork = 1;
	}

	// stop any music from playing - so the system no longer needs the
	// current CD - otherwise when we take out the CD, Windows will
	// complain!

	g_logic.fnStopMusic(NULL);

	textRes = res_man.open(2283);
	DisplayMsg(FetchTextLine(textRes, 5 + cd) + 2, 0);
	text_spr = fontRenderer.makeTextSprite(FetchTextLine(textRes, 5 + cd) + 2, 640, 187, g_sword2->_speechFontId);

	frame = (_frameHeader*) text_spr->ad;

	spriteInfo.x = g_display->_screenWide / 2 - frame->width / 2;
	spriteInfo.y = g_display->_screenDeep / 2 - frame->height / 2 - RDMENU_MENUDEEP;
	spriteInfo.w = frame->width;
	spriteInfo.h = frame->height;
	spriteInfo.scale = 0;
	spriteInfo.scaledWidth	= 0;
	spriteInfo.scaledHeight	= 0;
	spriteInfo.type = RDSPR_DISPLAYALIGN | RDSPR_NOCOMPRESSION | RDSPR_TRANS;
	spriteInfo.blend = 0;
	spriteInfo.data = text_spr->ad + sizeof(_frameHeader);
	spriteInfo.colourTable	= 0;
	oldY = spriteInfo.y;
	oldX = spriteInfo.x;

	res_man.close(2283);

	do {
		if (offNetwork == 1)
			done = true;
		else {
			index = 0;
			while (_cdDrives[index] != 0 && !done && index < 24) {
				sprintf(_cdPath, "%c:\\", _cdDrives[index]);

				if (!SVM_GetVolumeInformation(_cdPath, sCDName, _MAX_PATH, NULL, &dwMaxCompLength, &dwFSFlags, NULL, 0)) {
					sCDName[0] = 0;
				}

				if (!scumm_stricmp(sCDName, CD1_LABEL)) {
					if (cd == CD1)
						done = true;
				} else if (!scumm_stricmp(sCDName, CD2_LABEL)) {
					if (cd == CD2)
						done = true;
				}
				index++;
			}
		}
		
		g_display->updateDisplay();

		g_display->clearScene();
		g_display->drawSprite(&spriteInfo);	// Keep the message there even when the user task swaps.
		spriteInfo.y = oldY;		// Drivers change the y co-ordinate, don't know why...
		spriteInfo.x = oldX;
	} while (!done);

	memory.freeMemory(text_spr);
	RemoveMsg();
}

} // End of namespace Sword2