File: assets.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (1326 lines) | stat: -rw-r--r-- 40,742 bytes parent folder | download | duplicates (2)
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
/* 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include "graphics/managed_surface.h"
#include "graphics/surface.h"

#include "audio/audiostream.h"

#include "common/endian.h"
#include "common/memstream.h"

#include "image/codecs/codec.h"

#include "mtropolis/assets.h"
#include "mtropolis/asset_factory.h"

namespace MTropolis {

AssetHooks::~AssetHooks() {
}

void AssetHooks::onLoaded(Asset *asset, const Common::String &name) {
}

Asset::Asset() : _assetID(0) {
}

Asset::~Asset() {
}

uint32 Asset::getAssetID() const {
	return _assetID;
}

bool ColorTableAsset::load(AssetLoaderContext &context, const Data::ColorTableAsset &data) {
	_assetID = data.assetID;
	for (int i = 0; i < 256; i++) {
		if (!_colors[i].load(data.colors[i]))
			return false;
	}

	return true;
}

AssetType ColorTableAsset::getAssetType() const {
	return kAssetTypeColorTable;
}

const ColorRGB8 *ColorTableAsset::getColors() const {
	return _colors;
}

CachedAudio::CachedAudio() {
}

bool CachedAudio::loadFromStream(const AudioMetadata &metadata, Common::ReadStream *stream, size_t size) {
	_data.resize(size);
	if (size > 0) {
		stream->read(&_data[0], size);
		if (stream->err())
			return false;

		if (metadata.encoding == AudioMetadata::kEncodingUncompressed && metadata.bitsPerSample == 16) {
			int16 *samples = reinterpret_cast<int16 *>(&_data[0]);
			size_t numSamples = _data.size() / 2;

			if (metadata.isBigEndian) {
				for (size_t i = 0; i < numSamples; i++)
					samples[i] = FROM_BE_16(samples[i]);
			} else {
				for (size_t i = 0; i < numSamples; i++)
					samples[i] = FROM_LE_16(samples[i]);
			}
		}

		return true;
	}
	return true;
}

const void *CachedAudio::getData() const {
	if (_data.size() == 0)
		return nullptr;
	return &_data[0];
}

size_t CachedAudio::getSize() const {
	return _data.size();
}

size_t CachedAudio::getNumSamples(const AudioMetadata &metadata) const {
	switch (metadata.encoding) {
	case AudioMetadata::kEncodingMace6:
		return _data.size() * 6 / metadata.channels;
	case AudioMetadata::kEncodingMace3:
		return _data.size() * 3 / metadata.channels;
	case AudioMetadata::kEncodingUncompressed:
		return _data.size() / (metadata.channels * metadata.bitsPerSample / 8);
	default:
		return 0;
	}
}

MToonMetadata::FrameDef::FrameDef() : dataOffset(0), compressedSize(0), decompressedSize(0), decompressedBytesPerRow(0), isKeyFrame(false) {
}

bool MToonMetadata::FrameDef::load(AssetLoaderContext &context, const Data::MToonAsset::FrameDef &data) {
	compressedSize = data.compressedSize;
	dataOffset = data.dataOffset;
	decompressedBytesPerRow = data.decompressedBytesPerRow;
	decompressedSize = data.decompressedSize;
	isKeyFrame = (data.keyframeFlag != 0);
	if (!data.rect1.toScummVMRect(rect))
		return false;

	return true;
}

MToonMetadata::FrameRangeDef::FrameRangeDef() : startFrame(0), endFrame(0) {
}

MToonMetadata::MToonMetadata() : imageFormat(kImageFormatWindows), bitsPerPixel(0), codecID(0), encodingFlags(0) {
}

CachedMToon::RleFrame::RleFrame() : version(0), width(0), height(0), isKeyframe(0) {
}

CachedMToon::CachedMToon() : _isRLETemporalCompressed(false), _hackFlags(0) {
}

bool CachedMToon::loadFromStream(const Common::SharedPtr<MToonMetadata> &metadata, Common::ReadStream *stream, size_t size, uint hackFlags) {
	_metadata = metadata;
	_hackFlags = hackFlags;

	Common::Array<uint8> data;
	data.resize(size);
	if (size > 0) {
		stream->read(&data[0], size);
		if (stream->err())
			return false;
	}

	if (metadata->codecID == kMToonRLECodecID) {
		loadRLEFrames(data);

		uint16 fullWidth = metadata->rect.width();
		uint16 fullHeight = metadata->rect.height();

		bool haveAnyTemporalFrames = false;
		bool haveDifferentDimensions = false;
		_isRLETemporalCompressed = false;

		for (size_t i = 0; i < metadata->frames.size(); i++) {
			if (!_rleData[i].isKeyframe)
				haveAnyTemporalFrames = true;

			if (_rleData[i].width != fullWidth || _rleData[i].height != fullHeight) {
				haveDifferentDimensions = true;
				break;
			}
		}

		if (haveAnyTemporalFrames && !haveDifferentDimensions)
			_isRLETemporalCompressed = true;
	}

	if (!_isRLETemporalCompressed)
		decompressFrames(data);

	return true;
}

void CachedMToon::decompressFrames(const Common::Array<uint8> &data) {
	size_t numFrames = _metadata->frames.size();

	_decompressedFrames.resize(numFrames);
	_optimizedFrames.resize(numFrames);

	for (size_t i = 0; i < numFrames; i++) {
		if (_metadata->codecID == kMToonRLECodecID) {
			decompressRLEFrame(i);
		} else if (_metadata->codecID == 0) {
			loadUncompressedFrame(data, i);
		} else {
			decompressQuickTimeFrame(data, i);
		}
	}

	_rleData.clear();
}

template<class TNumber, uint32 TLiteralMask, uint32 TTransparentRowSkipMask>
bool CachedMToon::decompressMToonRLE(const RleFrame &frame, const Common::Array<TNumber> &coefsArray, Graphics::ManagedSurface &surface, bool isBottomUp, bool isKeyFrame, uint hackFlags) {
	assert(sizeof(TNumber) == surface.format.bytesPerPixel);

	size_t w = surface.w;
	size_t h = surface.h;

	size_t size = coefsArray.size();
	if (size == 0) {
		if (isKeyFrame) {
			TNumber fillColor = 0;
			if (surface.format.bytesPerPixel > 1)
				fillColor = surface.format.RGBToColor(0, 0, 0);

			for (size_t y = 0; y < h; y++) {
				TNumber *rowData = static_cast<TNumber *>(surface.getBasePtr(0, y));
				for (size_t x = 0; x < w; x++)
					rowData[x] = fillColor;
			}
		}
		return true;
	}

	const TNumber *coefs = &coefsArray[0];

	size_t x = 0;
	size_t y = 0;

	if (w != frame.width || h != frame.height)
		return false;

	TNumber *rowData = static_cast<TNumber *>(surface.getBasePtr(0, isBottomUp ? (h - 1) : 0));

	for (;;) {
		if (size == 0)
			return false;
		const TNumber rleCode = coefs[0];
		coefs++;
		size--;

		size_t remainingInRow = w - x;

		if (rleCode == 0) {
			if (size == 0)
				return false;
			const TNumber transparentCountCode = coefs[0];
			coefs++;
			size--;

			if (transparentCountCode & TTransparentRowSkipMask) {
				// Vertical skip
				uint32 skipAmount = transparentCountCode - TTransparentRowSkipMask;

				y += skipAmount;
				x = 0;
				if (y < h) {
					rowData = static_cast<TNumber *>(surface.getBasePtr(0, isBottomUp ? (h - 1 - y) : y));
					continue;
				} else {
					break;
				}
			} else {
				// Horizontal skip
				const size_t horizontalSkip = transparentCountCode;
				if (horizontalSkip > remainingInRow)
					return false;
				x += horizontalSkip;
			}
		} else if (rleCode & TLiteralMask) {
			// Literals
			const size_t numLiterals = (rleCode - TLiteralMask);
			if (numLiterals > size || numLiterals > remainingInRow)
				return false;
			memcpy(rowData + x, coefs, sizeof(TNumber) * numLiterals);
			coefs += numLiterals;
			size -= numLiterals;
			x += numLiterals;
		} else {
			// Run
			const size_t numCopies = rleCode;
			if (numCopies > remainingInRow || size == 0)
				return false;
			const TNumber repeatedValue = coefs[0];
			for (size_t i = 0; i < numCopies; i++)
				rowData[x + i] = repeatedValue;
			coefs++;
			size--;
			x += numCopies;

			if (size >= 2) {
				// Handle some strange cases in MTI that appear to be caused by some kind of mToon
				// encoder RLE flush problem: Numerous mToons have a 0-length RLE run after a max-length
				// run.  In most cases, the repeated value is 0, which has no effect, but in some cases
				// this causes decode problems because the value is non-zero and gets decoded as a skip.
				//
				// In particular, it causes problems with the MPZ-1000 Hispaniola TV, the shoe and pants
				// pull-outs in the chest in the first area, and the target animations in the Hispaniola
				// cannon minigame.
				if (numCopies == (TLiteralMask - 1) && coefs[0] == 0 && coefs[1] == repeatedValue) {
					coefs += 2;
					size -= 2;
				}
			}
		}

		if (x == w) {
			y++;
			x = 0;
			if (y < h) {
				rowData = static_cast<TNumber *>(surface.getBasePtr(0, isBottomUp ? (h - 1 - y) : y));
				continue;
			} else {
				break;
			}
		}
	}

	return true;
}

template<class TDest, class TSrc>
void CachedMToon::checkedMemCpy(Common::Array<TDest> &dest, size_t destIndex, const Common::Array<TSrc> &src, size_t srcIndex, size_t sizeBytes) {
	if (sizeBytes == 0)
		return;

	size_t destSize = dest.size() * sizeof(TDest);
	size_t srcSize = src.size() * sizeof(TSrc);

	if (destIndex > dest.size() || srcIndex > src.size())
		error("Out-of-range data copy offset while loading mToon");

	size_t srcPos = srcIndex * sizeof(TSrc);
	size_t destPos = destIndex * sizeof(TDest);

	size_t srcAvail = srcSize - srcPos;
	size_t destAvail = destSize - destPos;

	if (srcAvail < sizeBytes || destAvail < sizeBytes)
		error("Out-of-range data copy end while loading mToon");

	memcpy(&dest[destIndex], &src[srcIndex], sizeBytes);
}

void CachedMToon::decompressRLEFrameToImage(size_t frameIndex, Graphics::ManagedSurface &surface) {
	assert(surface.format == _rleOptimizedFormat);

	bool isBottomUp = (_metadata->imageFormat == MToonMetadata::kImageFormatWindows);

	bool isKeyFrame = _metadata->frames[frameIndex].isKeyFrame;

	bool decompressedOK = false;
	if (_rleOptimizedFormat.bytesPerPixel == 4) {
		decompressedOK = decompressMToonRLE<uint32, 0x80000000u, 0x80000000u>(_rleData[frameIndex], _rleData[frameIndex].data32, surface, isBottomUp, isKeyFrame, _hackFlags);
	} else if (_rleOptimizedFormat.bytesPerPixel == 2) {
		decompressedOK = decompressMToonRLE<uint16, 0x8000u, 0x8000u>(_rleData[frameIndex], _rleData[frameIndex].data16, surface, isBottomUp, isKeyFrame, _hackFlags);
	} else if (_rleOptimizedFormat.bytesPerPixel == 1) {
		decompressedOK = decompressMToonRLE<uint8, 0x80u, 0x80u>(_rleData[frameIndex], _rleData[frameIndex].data8, surface, isBottomUp, isKeyFrame, _hackFlags);
	} else
		error("Unknown mToon encoding");

	if (!decompressedOK)
		warning("mToon RLE frame decompression failed");
}

void CachedMToon::loadRLEFrames(const Common::Array<uint8> &data) {
	size_t numFrames = _metadata->frames.size();
	uint16 bpp = _metadata->bitsPerPixel;

	_rleData.resize(numFrames);

	for (size_t i = 0; i < numFrames; i++) {
		const MToonMetadata::FrameDef &frameDef = _metadata->frames[i];

		RleFrame &rleFrame = _rleData[i];

		size_t baseOffset = frameDef.dataOffset;

		if (frameDef.compressedSize == 0) {
			rleFrame.isKeyframe = (i == 0);	// ???
			continue;
		}

		if (frameDef.compressedSize < 20)
			error("Invalid compressed data size");

		uint32 headerInts[5];
		for (size_t hi = 0; hi < 5; hi++) {
			uint32 unpacked = 0;
			for (size_t b = 0; b < 4; b++)
				unpacked = (unpacked << 8) + data[baseOffset + hi * 4 + b];
			headerInts[hi] = unpacked;
		}

		rleFrame.isKeyframe = (headerInts[0] == kMToonRLEKeyframePrefix);
		if (headerInts[1] == 0x01000001) {
			if (bpp != 8)
				error("Unknown mToon encoding");
		} else if (headerInts[1] == 0x01000002) {
			if (bpp != 16)
				error("Unknown mToon encoding");
		} else
			error("Unknown mToon encoding");

		rleFrame.version = headerInts[1];
		rleFrame.width = headerInts[2];
		rleFrame.height = headerInts[3];

		uint32 frameDataSize = headerInts[4];

		if (frameDataSize > 0) {
			// frameDataSize is sometimes set to frameDef.compressedSize but sometimes contains garbage,
			// so we need to ignore it and derive size from the frameDef instead.
			if (bpp == 8) {
				rleFrame.data8.resize(frameDef.compressedSize - 20);
				checkedMemCpy(rleFrame.data8, 0, data, baseOffset + 20, frameDef.compressedSize - 20);
			} else if (bpp == 16) {
				uint32 numDWords = (frameDef.compressedSize - 20) / 2;
				rleFrame.data16.resize(numDWords);
				checkedMemCpy(rleFrame.data16, 0, data, baseOffset + 20, static_cast<size_t>(numDWords) * 2u);

				uint16 *i16 = &rleFrame.data16[0];
				if (_metadata->imageFormat == MToonMetadata::kImageFormatWindows) {
					for (size_t swapIndex = 0; swapIndex < numDWords; swapIndex++)
						i16[swapIndex] = FROM_LE_16(i16[swapIndex]);
				} else if (_metadata->imageFormat == MToonMetadata::kImageFormatMac) {
					for (size_t swapIndex = 0; swapIndex < numDWords; swapIndex++)
						i16[swapIndex] = FROM_BE_16(i16[swapIndex]);
				}
			} else
				error("Unknown mToon encoding");
		}
	}

	if (bpp == 8)
		_rleInternalFormat = Graphics::PixelFormat::createFormatCLUT8();
	else if (bpp == 16)
		_rleInternalFormat = Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 15);
	else
		error("Unknown mToon encoding");

	_rleOptimizedFormat = _rleInternalFormat;
}

void CachedMToon::decompressRLEFrame(size_t frameIndex) {
	Common::SharedPtr<Graphics::ManagedSurface> surface(new Graphics::ManagedSurface());

	RleFrame &frame = _rleData[frameIndex];

	surface->create(frame.width, frame.height, _rleInternalFormat);

	decompressRLEFrameToImage(frameIndex, *surface);

	this->_decompressedFrames[frameIndex] = surface;
}

void CachedMToon::loadUncompressedFrame(const Common::Array<uint8> &data, size_t frameIndex) {
	const MToonMetadata::FrameDef &frameDef = _metadata->frames[frameIndex];
	uint16 stride = frameDef.decompressedBytesPerRow;

	uint16 bpp = _metadata->bitsPerPixel;

	Common::SharedPtr<Graphics::ManagedSurface> surface(new Graphics::ManagedSurface());
	Graphics::PixelFormat pixFmt;

	if (bpp == 1 || bpp == 2 || bpp == 4 || bpp == 8)
		pixFmt = Graphics::PixelFormat::createFormatCLUT8();
	else if (bpp == 16)
		pixFmt = Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 15);
	else if (bpp == 32)
		pixFmt = Graphics::PixelFormat(4, 8, 8, 8, 0, 0, 8, 16, 24);
	else
		error("Unknown mToon encoding");

	size_t w = frameDef.rect.width();
	size_t h = frameDef.rect.height();

	surface->create(w, h, pixFmt);

	for (size_t row = 0; row < h; row++) {
		const uint8 *inData = &data[frameDef.dataOffset + row * stride];
		void *outDataUntyped = nullptr;

		if (_metadata->imageFormat == MToonMetadata::kImageFormatWindows)
			outDataUntyped = surface->getBasePtr(0, h - 1 - row);
		else if (_metadata->imageFormat == MToonMetadata::kImageFormatMac)
			outDataUntyped = surface->getBasePtr(0, row);
		else
			error("Unimplemented mToon uncompressed image layout");

		if (bpp == 1) {
			for (size_t col = 0; col < w; col++)
				static_cast<uint8 *>(outDataUntyped)[col] = (inData[col / 8] >> (7 - (col % 8))) & 1;
		} else if (bpp == 2) {
			for (size_t col = 0; col < w; col++)
				static_cast<uint8 *>(outDataUntyped)[col] = (inData[col / 4] >> (6 - (col % 4) * 2)) & 3;
		} else if (bpp == 4) {
			for (size_t col = 0; col < w; col++)
				static_cast<uint8 *>(outDataUntyped)[col] = (inData[col / 2] >> (4 - (col % 2) * 4)) & 15;
		} else if (bpp == 8) {
			for (size_t col = 0; col < w; col++)
				static_cast<uint8 *>(outDataUntyped)[col] = inData[col];
		} else if (bpp == 16) {
			if (_metadata->imageFormat == MToonMetadata::kImageFormatMac) {
				for (size_t col = 0; col < w; col++)
					static_cast<uint16 *>(outDataUntyped)[col] = (inData[col * 2] << 8) | (inData[col * 2 + 1]);
			} else if (_metadata->imageFormat == MToonMetadata::kImageFormatWindows) {
				for (size_t col = 0; col < w; col++)
					static_cast<uint16 *>(outDataUntyped)[col] = (inData[col * 2 + 1] << 8) | (inData[col * 2]);
			}
		} else if (bpp == 32) {
			if (_metadata->imageFormat == MToonMetadata::kImageFormatMac) {
				for (size_t col = 0; col < w; col++)
					static_cast<uint32 *>(outDataUntyped)[col] = (0xff000000 | (inData[col * 4 + 1]) | (inData[col * 4 + 2] << 8) | (inData[col * 4 + 3] << 16));
			} else if (_metadata->imageFormat == MToonMetadata::kImageFormatWindows) {
				for (size_t col = 0; col < w; col++)
					static_cast<uint32 *>(outDataUntyped)[col] = (0xff000000 | (inData[col * 4 + 2]) | (inData[col * 4 + 1] << 8) | (inData[col * 4 + 0] << 16));
			}
		}
	}

	_decompressedFrames[frameIndex] = surface;
}

void CachedMToon::decompressQuickTimeFrame(const Common::Array<uint8> &data, size_t frameIndex) {
	const MToonMetadata::FrameDef &frameDef = _metadata->frames[frameIndex];

	// We used to validate that these match the sample desc, but that actually breaks in Obsidian
	// on the Bureau Immediate Action clock puzzle, because the frames have different sizes and
	// the codec data encodes the size of the last frame.
	uint16 w = frameDef.rect.width();
	uint16 h = frameDef.rect.height();
	uint16 bpp = READ_BE_UINT16(&_metadata->codecData[82]);

	Image::Codec *codec = Image::createQuickTimeCodec(_metadata->codecID, w, h, bpp);
	if (!codec) {
		error("Unknown QuickTime codec for mToon frame");
	}

	if (frameDef.dataOffset > data.size())
		error("Invalid framedef offset");

	if (frameDef.compressedSize > data.size())
		error("Invalid compressed size");

	if (frameDef.compressedSize - data.size() < frameDef.dataOffset)
		error("Not enough available bytes for compressed data");

	Common::MemoryReadStream stream(&data[frameDef.dataOffset], frameDef.compressedSize);

	const Graphics::Surface *surface = codec->decodeFrame(stream);
	if (!surface) {
		error("mToon QuickTime frame failed to decompress");
	}

	// Clone the decompressed frame
	Graphics::ManagedSurface *surfaceCopy = new Graphics::ManagedSurface();
	surfaceCopy->copyFrom(*surface);
	_decompressedFrames[frameIndex].reset(surfaceCopy);
}

template<class TSrcNumber, uint32 TSrcLiteralMask, uint32 TSrcTransparentSkipMask, class TDestNumber, uint32 TDestLiteralMask, uint32 TDestTransparentSkipMask>
void CachedMToon::rleReformat(RleFrame &frame, const Common::Array<TSrcNumber> &srcData, const Graphics::PixelFormat &srcFormatRef, Common::Array<TDestNumber> &destData, const Graphics::PixelFormat &destFormatRef, uint hackFlags) {
	const Graphics::PixelFormat srcFormat = srcFormatRef;
	const Graphics::PixelFormat destFormat = destFormatRef;

	size_t offset = 0;
	destData.resize(srcData.size());

	while (offset < srcData.size()) {
		uint32 rleCodeOffset = offset;
		const uint32 rleCode = srcData[rleCodeOffset];
		if (rleCode == 0) {
			destData[offset] = 0;
			offset++;

			uint32 numTransparentCode = srcData[offset];
			if (numTransparentCode & TSrcTransparentSkipMask)
				destData[offset] = (numTransparentCode - TSrcTransparentSkipMask) + TDestTransparentSkipMask;
			else
				destData[offset] = numTransparentCode;
			offset++;
		} else if (rleCode & TSrcLiteralMask) {
			uint32 numLiterals = rleCode - TSrcLiteralMask;

			destData[offset] = numLiterals + TDestLiteralMask;
			offset++;

			while (numLiterals) {
				uint8 a, r, g, b;
				srcFormat.colorToARGB(srcData[offset], a, r, g, b);
				destData[offset] = destFormat.ARGBToColor(a, r, g, b);
				offset++;
				numLiterals--;
			}
		} else {
			destData[offset] = rleCode;
			offset++;

			uint8 a, r, g, b;
			srcFormat.colorToARGB(srcData[offset], a, r, g, b);
			destData[offset] = destFormat.ARGBToColor(a, r, g, b);
			offset++;
		}
	}
}

void CachedMToon::optimize(Runtime *runtime) {
	Graphics::PixelFormat renderFmt = runtime->getRenderPixelFormat();
	if (_isRLETemporalCompressed)
		optimizeRLE(renderFmt);
	else
		optimizeNonTemporal(renderFmt);
}

void CachedMToon::optimizeNonTemporal(const Graphics::PixelFormat &targetFormatRef) {
	const Graphics::PixelFormat targetFormat = targetFormatRef;

	_optimizedFrames.resize(_decompressedFrames.size());

	for (size_t i = 0; i < _decompressedFrames.size(); i++) {
		Common::SharedPtr<Graphics::ManagedSurface> srcSurface = _decompressedFrames[i];
		Common::SharedPtr<Graphics::ManagedSurface> &optimizedSurfRef = _optimizedFrames[i];

		// FIXME: Aggregate these checks and merge into a single format field
		if (optimizedSurfRef == nullptr || optimizedSurfRef->format != targetFormat) {
			if (targetFormat.bytesPerPixel > 1 && srcSurface->format.bytesPerPixel > 1) {
				if (targetFormat.bytesPerPixel == srcSurface->format.bytesPerPixel) {
					srcSurface->convertToInPlace(targetFormat);
					optimizedSurfRef = srcSurface;
				} else {
					optimizedSurfRef.reset();

					Graphics::ManagedSurface *newSurface = new Graphics::ManagedSurface();
					newSurface->convertFrom(*srcSurface, targetFormat);
					optimizedSurfRef.reset(newSurface);
				}
			} else {
				optimizedSurfRef = srcSurface;
			}
		}
	}
}

void CachedMToon::optimizeRLE(const Graphics::PixelFormat &targetFormatRef) {
	const Graphics::PixelFormat targetFormat = targetFormatRef;

	if (targetFormat == _rleOptimizedFormat)
		return;

	if (_rleInternalFormat.bytesPerPixel != 2 && _rleInternalFormat.bytesPerPixel != 4)
		return;	// Can't optimize

	size_t numFrames = _metadata->frames.size();
	for (size_t i = 0; i < numFrames; i++) {
		if (_rleInternalFormat.bytesPerPixel == 2) {
			if (targetFormat.bytesPerPixel == 4)
				rleReformat<uint16, 0x8000u, 0x8000u, uint32, 0x80000000u, 0x80000000u>(_rleData[i], _rleData[i].data16, _rleInternalFormat, _rleData[i].data32, targetFormat, _hackFlags);
			else if (targetFormat.bytesPerPixel == 2)
				rleReformat<uint16, 0x8000u, 0x8000u, uint16, 0x8000u, 0x8000u>(_rleData[i], _rleData[i].data16, _rleInternalFormat, _rleData[i].data16, targetFormat, _hackFlags);
		} else if (_rleInternalFormat.bytesPerPixel == 4) {
			if (targetFormat.bytesPerPixel == 4)
				rleReformat<uint32, 0x80000000u, 0x80000000u, uint32, 0x80000000u, 0x80000000u>(_rleData[i], _rleData[i].data32, _rleInternalFormat, _rleData[i].data32, targetFormat, _hackFlags);
			else if (targetFormat.bytesPerPixel == 2)
				rleReformat<uint32, 0x80000000u, 0x80000000u, uint16, 0x8000u, 0x8000u>(_rleData[i], _rleData[i].data32, _rleInternalFormat, _rleData[i].data16, targetFormat, _hackFlags);
		}
	}

	if (_rleInternalFormat.bytesPerPixel == targetFormat.bytesPerPixel)
		_rleInternalFormat = targetFormat;

	_rleOptimizedFormat = targetFormat;
}

void CachedMToon::getOrRenderFrame(uint32 prevFrame, uint32 targetFrame, Common::SharedPtr<Graphics::ManagedSurface> &surface) const {
	if (!_isRLETemporalCompressed) {
		surface = _optimizedFrames[targetFrame];
	} else if (_metadata->codecID == kMToonRLECodecID) {
		uint32 firstFrameToRender = 0;
		uint32 backStopFrame = 0;

		if (surface && surface->format != _rleOptimizedFormat)
			surface.reset();

		if (surface != nullptr) {
			if (prevFrame == targetFrame)
				return;
			if (prevFrame < targetFrame)
				backStopFrame = prevFrame + 1;
		}

		firstFrameToRender = targetFrame;
		while (firstFrameToRender > backStopFrame) {
			if (_metadata->frames[firstFrameToRender].isKeyFrame)
				break;
			firstFrameToRender--;
		}

		if (!surface || surface->format != _rleOptimizedFormat) {
			surface.reset(new Graphics::ManagedSurface());
			surface->create(_metadata->rect.width(), _metadata->rect.height(), _rleOptimizedFormat);
		}

		bool isBottomUp = (_metadata->imageFormat == MToonMetadata::kImageFormatWindows);

		for (size_t i = firstFrameToRender; i <= targetFrame; i++) {
			bool isKeyFrame = _metadata->frames[i].isKeyFrame;

			if (_rleOptimizedFormat.bytesPerPixel == 1)
				decompressMToonRLE<uint8, 0x80u, 0x80u>(_rleData[i], _rleData[i].data8, *surface, isBottomUp, isKeyFrame, _hackFlags);
			else if (_rleOptimizedFormat.bytesPerPixel == 2)
				decompressMToonRLE<uint16, 0x8000u, 0x8000u>(_rleData[i], _rleData[i].data16, *surface, isBottomUp, isKeyFrame, _hackFlags);
			else if (_rleOptimizedFormat.bytesPerPixel == 4)
				decompressMToonRLE<uint32, 0x80000000u, 0x80000000u>(_rleData[i], _rleData[i].data32, *surface, isBottomUp, isKeyFrame, _hackFlags);
		}
	}
}

const Common::SharedPtr<MToonMetadata>& CachedMToon::getMetadata() const {
	return _metadata;
}

AudioMetadata::AudioMetadata() : encoding(kEncodingUncompressed), durationMSec(0),
	sampleRate(0), channels(0), bitsPerSample(0), isBigEndian(false) {
}

bool AudioAsset::load(AssetLoaderContext &context, const Data::AudioAsset &data) {
	_assetID = data.assetID;

	_metadata.reset(new AudioMetadata());
	_metadata->sampleRate = data.sampleRate1;
	_metadata->bitsPerSample = data.bitsPerSample;

	_streamIndex = context.streamIndex;

	switch (data.encoding1) {
	case 0:
		_metadata->encoding = AudioMetadata::kEncodingUncompressed;
		break;
	case 3:
		_metadata->encoding = AudioMetadata::kEncodingMace3;
		break;
	case 4:
		_metadata->encoding = AudioMetadata::kEncodingMace6;
		break;
	default:
		return false;
	}

	_metadata->channels = data.channels;
	// Hours Minutes Seconds Hundredths -> msec
	// Maximum is 0x37a4f52e so this fits in 30 bits
	_metadata->durationMSec = ((((data.codedDuration[0] * 60u) + data.codedDuration[1]) * 60u + data.codedDuration[2]) * 100u + data.codedDuration[3]) * 10u;
	_filePosition = data.filePosition;
	_size = data.size;
	_metadata->cuePoints.resize(data.cuePoints.size());
	_metadata->isBigEndian = data.isBigEndian;

	for (size_t i = 0; i < data.cuePoints.size(); i++) {
		_metadata->cuePoints[i].cuePointID = data.cuePoints[i].cuePointID;
		_metadata->cuePoints[i].position = data.cuePoints[i].position;
	}

	return true;
}

AssetType AudioAsset::getAssetType() const {
	return kAssetTypeAudio;
}

size_t AudioAsset::getStreamIndex() const {
	return _streamIndex;
}

const Common::SharedPtr<AudioMetadata> &AudioAsset::getMetadata() const {
	return _metadata;
}


const Common::SharedPtr<CachedAudio> &AudioAsset::loadAndCacheAudio(Runtime *runtime) {
	if (_audioCache)
		return _audioCache;

	size_t streamIndex = getStreamIndex();
	int segmentIndex = runtime->getProject()->getSegmentForStreamIndex(streamIndex);
	runtime->getProject()->openSegmentStream(segmentIndex);
	Common::SeekableReadStream *stream = runtime->getProject()->getStreamForSegment(segmentIndex);

	if (!stream || !stream->seek(_filePosition)) {
		warning("Audio asset failed to load, couldn't seek to position");
		return _audioCache;
	}

	Common::SharedPtr<CachedAudio> audio(new CachedAudio());
	if (!audio->loadFromStream(*_metadata, stream, _size)) {
		warning("Audio asset failed to load, couldn't read data");
		return _audioCache;
	}

	_audioCache.reset();
	_audioCache = audio;

	return _audioCache;
}

bool MovieAsset::load(AssetLoaderContext &context, const Data::MovieAsset &data) {
	_assetID = data.assetID;
	_moovAtomPos = data.moovAtomPos;
	_movieDataPos = data.movieDataPos;
	_movieDataSize = data.movieDataSize;
	_extFileName = data.extFileName;
	_streamIndex = context.streamIndex;

	return true;
}

AssetType MovieAsset::getAssetType() const {
	return kAssetTypeMovie;
}

uint32 MovieAsset::getMovieDataPos() const {
	return _movieDataPos;
}

uint32 MovieAsset::getMoovAtomPos() const {
	return _moovAtomPos;
}

uint32 MovieAsset::getMovieDataSize() const {
	return _movieDataSize;
}


const Common::String &MovieAsset::getExtFileName() const {
	return _extFileName;
}

size_t MovieAsset::getStreamIndex() const {
	return _streamIndex;
}

void MovieAsset::addDamagedFrame(int frame) {
	_damagedFrames.push_back(frame);
}

bool AVIMovieAsset::load(AssetLoaderContext &context, const Data::AVIMovieAsset &data) {
	_assetID = data.assetID;
	_extFileName = data.extFileName;

	return true;
}

AssetType AVIMovieAsset::getAssetType() const {
	return kAssetTypeAVIMovie;
}

const Common::String &AVIMovieAsset::getExtFileName() const {
	return _extFileName;
}

const Common::Array<int> &MovieAsset::getDamagedFrames() const {
	return _damagedFrames;
}


CachedImage::CachedImage() : _colorDepth(kColorDepthModeInvalid) {
}

void CachedImage::resetSurface(ColorDepthMode colorDepth, const Common::SharedPtr<Graphics::ManagedSurface> &surface) {
	_optimizedSurface.reset();

	_colorDepth = colorDepth;
	_surface = surface;
}

ColorDepthMode CachedImage::getOriginalColorDepth() const {
	return _colorDepth;
}

const Common::SharedPtr<Graphics::ManagedSurface> &CachedImage::optimize(Runtime *runtime) {
	ColorDepthMode renderDepth = runtime->getRealColorDepth();
	const Graphics::PixelFormat &renderFmt = runtime->getRenderPixelFormat();

	if (renderDepth != _colorDepth) {
		if (!_optimizedSurface) {
			size_t w = _surface->w;
			size_t h = _surface->h;

			if (renderDepth == kColorDepthMode16Bit && _colorDepth == kColorDepthMode32Bit) {
				_optimizedSurface.reset(new Graphics::ManagedSurface());
				_optimizedSurface->create(w, h, renderFmt);
				Render::convert32To16(*_optimizedSurface, *_surface);
			} else if (renderDepth == kColorDepthMode32Bit && _colorDepth == kColorDepthMode16Bit) {
				_optimizedSurface.reset(new Graphics::ManagedSurface());
				_optimizedSurface->create(w, h, renderFmt);
				Render::convert16To32(*_optimizedSurface, *_surface);
			} else {
				return _surface; // Can't optimize
			}
		}

		return _optimizedSurface;
	}

	return _surface;	// Already optimal
}

ImageAsset::ImageAsset() : _colorDepth(kColorDepthMode8Bit), _filePosition(0), _size(0), _streamIndex(0), _imageFormat(kImageFormatWindows) {
}

ImageAsset::~ImageAsset() {
}

bool ImageAsset::load(AssetLoaderContext &context, const Data::ImageAsset &data) {
	_assetID = data.assetID;
	if (!data.rect1.toScummVMRect(_rect))
		return false;
	_filePosition = data.filePosition;
	_size = data.size;
	_streamIndex = context.streamIndex;

	switch (data.bitsPerPixel) {
	case 1:
		_colorDepth = kColorDepthMode1Bit;
		break;
	case 2:
		_colorDepth = kColorDepthMode2Bit;
		break;
	case 4:
		_colorDepth = kColorDepthMode4Bit;
		break;
	case 8:
		_colorDepth = kColorDepthMode8Bit;
		break;
	case 16:
		_colorDepth = kColorDepthMode16Bit;
		break;
	case 32:
		_colorDepth = kColorDepthMode32Bit;
		break;
	default:
		return false;
	}

	if (data.haveMacPart)
		_imageFormat = kImageFormatMac;
	else if (data.haveWinPart)
		_imageFormat = kImageFormatWindows;
	else
		return false;

	return true;
}

AssetType ImageAsset::getAssetType() const {
	return kAssetTypeImage;
}

const Common::Rect &ImageAsset::getRect() const {
	return _rect;
}

ColorDepthMode ImageAsset::getColorDepth() const {
	return _colorDepth;
}

uint32 ImageAsset::getFilePosition() const {
	return _filePosition;
}

uint32 ImageAsset::getSize() const {
	return _size;
}

size_t ImageAsset::getStreamIndex() const {
	return _streamIndex;
}

ImageAsset::ImageFormat ImageAsset::getImageFormat() const {
	return _imageFormat;
}

const Common::SharedPtr<CachedImage> &ImageAsset::loadAndCacheImage(Runtime *runtime) {
	if (_imageCache)
		return _imageCache;

	size_t streamIndex = getStreamIndex();
	int segmentIndex = runtime->getProject()->getSegmentForStreamIndex(streamIndex);
	runtime->getProject()->openSegmentStream(segmentIndex);
	Common::SeekableReadStream *stream = runtime->getProject()->getStreamForSegment(segmentIndex);

	if (!stream || !stream->seek(getFilePosition())) {
		warning("Image element failed to load");
		return _imageCache;
	}

	size_t bytesPerRow = 0;

	Common::Rect imageRect = getRect();
	int width = imageRect.right - imageRect.left;
	int height = imageRect.bottom - imageRect.top;

	if (width <= 0 || height < 0) {
		warning("Image asset has invalid size");
		return _imageCache;
	}

	Graphics::PixelFormat pixelFmt;
	switch (getColorDepth()) {
	case kColorDepthMode1Bit:
		bytesPerRow = (width + 31) / 32 * 4;
		pixelFmt = Graphics::PixelFormat::createFormatCLUT8();
		break;
	case kColorDepthMode2Bit:
		bytesPerRow = (width + 15) / 16 * 4;
		pixelFmt = Graphics::PixelFormat::createFormatCLUT8();
		break;
	case kColorDepthMode4Bit:
		bytesPerRow = (width + 7) / 8 * 4;
		pixelFmt = Graphics::PixelFormat::createFormatCLUT8();
		break;
	case kColorDepthMode8Bit:
		bytesPerRow = (width + 3) / 4 * 4;
		pixelFmt = Graphics::PixelFormat::createFormatCLUT8();
		break;
	case kColorDepthMode16Bit:
		bytesPerRow = (width * 2 + 3) / 4 * 4;
		pixelFmt = Graphics::createPixelFormat<1555>();
		break;
	case kColorDepthMode32Bit:
		bytesPerRow = width * 4;
		pixelFmt = Graphics::createPixelFormat<8888>();
		break;
	default:
		warning("Image asset has an unrecognizable pixel format");
		return _imageCache;
	}

	Common::Array<uint8> rowBuffer;
	rowBuffer.resize(bytesPerRow);

	ImageAsset::ImageFormat imageFormat = getImageFormat();
	bool bottomUp = (imageFormat == ImageAsset::kImageFormatWindows);
	bool isBigEndian = (imageFormat == ImageAsset::kImageFormatMac);

	Common::SharedPtr<Graphics::ManagedSurface> imageSurface;
	imageSurface.reset(new Graphics::ManagedSurface());
	imageSurface->create(width, height, pixelFmt);

	for (int inRow = 0; inRow < height; inRow++) {
		int outRow = bottomUp ? (height - 1 - inRow) : inRow;

		stream->read(&rowBuffer[0], bytesPerRow);
		const uint8 *inRowBytes = &rowBuffer[0];

		void *outBase = imageSurface->getBasePtr(0, outRow);

		switch (getColorDepth()) {
		case kColorDepthMode1Bit: {
				for (int x = 0; x < width; x++) {
					int bit = (inRowBytes[x / 8] >> (7 - (x % 8))) & 1;
					static_cast<uint8 *>(outBase)[x] = bit;
				}
			} break;
		case kColorDepthMode2Bit: {
				for (int x = 0; x < width; x++) {
					int bit = (inRowBytes[x / 4] >> (3 - (x % 4))) & 3;
					static_cast<uint8 *>(outBase)[x] = bit;
				}
			} break;
		case kColorDepthMode4Bit: {
				for (int x = 0; x < width; x++) {
					int bit = (inRowBytes[x / 2] >> (1 - (x % 2))) & 15;
					static_cast<uint8 *>(outBase)[x] = bit;
				}
			} break;
		case kColorDepthMode8Bit:
			memcpy(outBase, inRowBytes, width);
			break;
		case kColorDepthMode16Bit: {
				if (isBigEndian) {
					for (int x = 0; x < width; x++) {
						uint16 packedPixel = inRowBytes[x * 2 + 1] + (inRowBytes[x * 2 + 0] << 8);
						int r = ((packedPixel >> 10) & 0x1f);
						int g = ((packedPixel >> 5) & 0x1f);
						int b = (packedPixel & 0x1f);

						uint16 repacked = (1 << pixelFmt.aShift) | (r << pixelFmt.rShift) | (g << pixelFmt.gShift) | (b << pixelFmt.bShift);
						static_cast<uint16 *>(outBase)[x] = repacked;
					}
				} else {
					for (int x = 0; x < width; x++) {
						uint16 packedPixel = inRowBytes[x * 2 + 0] + (inRowBytes[x * 2 + 1] << 8);
						int r = ((packedPixel >> 10) & 0x1f);
						int g = ((packedPixel >> 5) & 0x1f);
						int b = (packedPixel & 0x1f);

						uint16 repacked = (1 << pixelFmt.aShift) | (r << pixelFmt.rShift) | (g << pixelFmt.gShift) | (b << pixelFmt.bShift);
						static_cast<uint16 *>(outBase)[x] = repacked;
					}
				}
			} break;
		case kColorDepthMode32Bit: {
				if (imageFormat == ImageAsset::kImageFormatMac) {
					for (int x = 0; x < width; x++) {
						uint8 r = inRowBytes[x * 4 + 1];
						uint8 g = inRowBytes[x * 4 + 2];
						uint8 b = inRowBytes[x * 4 + 3];
						uint32 repacked = (255 << pixelFmt.aShift) | (r << pixelFmt.rShift) | (g << pixelFmt.gShift) | (b << pixelFmt.bShift);
						static_cast<uint32 *>(outBase)[x] = repacked;
					}
				} else if (imageFormat == ImageAsset::kImageFormatWindows) {
					for (int x = 0; x < width; x++) {
						uint8 r = inRowBytes[x * 4 + 2];
						uint8 g = inRowBytes[x * 4 + 1];
						uint8 b = inRowBytes[x * 4 + 0];
						uint32 repacked = (255 << pixelFmt.aShift) | (r << pixelFmt.rShift) | (g << pixelFmt.gShift) | (b << pixelFmt.bShift);
						static_cast<uint32 *>(outBase)[x] = repacked;
					}
				}
			} break;
		default:
			break;
		}
	}

	_imageCache.reset(new CachedImage());
	_imageCache->resetSurface(getColorDepth(), imageSurface);

	return _imageCache;
}

bool MToonAsset::load(AssetLoaderContext &context, const Data::MToonAsset &data) {
	_streamIndex = context.streamIndex;
	_assetID = data.assetID;

	_metadata.reset(new MToonMetadata());

	if (data.haveMacPart)
		_metadata->imageFormat = MToonMetadata::kImageFormatMac;
	else if (data.haveWinPart)
		_metadata->imageFormat = MToonMetadata::kImageFormatWindows;
	else
		return false;

	_frameDataPosition = data.frameDataPosition;
	_sizeOfFrameData = data.sizeOfFrameData;

	if (!data.registrationPoint.toScummVMPoint(_metadata->registrationPoint))
		return false;

	if (!data.rect.toScummVMRect(_metadata->rect))
		return false;

	_metadata->bitsPerPixel = data.bitsPerPixel;
	_metadata->codecID = data.codecID;
	_metadata->encodingFlags = data.encodingFlags;

	_metadata->frames.resize(data.frames.size());
	for (size_t i = 0; i < data.frames.size(); i++) {
		if (!_metadata->frames[i].load(context, data.frames[i]))
			return false;
	}

	_metadata->frameRanges.resize(data.frameRangesPart.frameRanges.size());
	for (size_t i = 0; i < data.frameRangesPart.frameRanges.size(); i++) {
		if (!_metadata->frameRanges[i].load(context, data.frameRangesPart.frameRanges[i]))
			return false;
	}

	_metadata->codecData = data.codecData;

	return true;
}

MToonAsset::MToonAsset() : _frameDataPosition(0), _sizeOfFrameData(0), _streamIndex(0){
}

AssetType MToonAsset::getAssetType() const {
	return kAssetTypeMToon;
}

const Common::SharedPtr<CachedMToon> &MToonAsset::loadAndCacheMToon(Runtime *runtime, uint hackFlags) {
	if (_cachedMToon)
		return _cachedMToon;

	Common::SharedPtr<CachedMToon> cachedMToon(new CachedMToon());

	size_t streamIndex = _streamIndex;
	int segmentIndex = runtime->getProject()->getSegmentForStreamIndex(streamIndex);
	runtime->getProject()->openSegmentStream(segmentIndex);
	Common::SeekableReadStream *stream = runtime->getProject()->getStreamForSegment(segmentIndex);

	if (!stream || !stream->seek(_frameDataPosition)) {
		warning("Couldn't seek stream to mToon data");
		return _cachedMToon;
	}

	if (!cachedMToon->loadFromStream(_metadata, stream, _sizeOfFrameData, hackFlags)) {
		warning("mToon data failed to load");
		return _cachedMToon;
	}

	_cachedMToon = cachedMToon;

	return _cachedMToon;
}

bool MToonMetadata::FrameRangeDef::load(AssetLoaderContext &context, const Data::MToonAsset::FrameRangeDef &data) {
	name = data.name;
	startFrame = data.startFrame;
	endFrame = data.endFrame;

	return true;
}

TextAsset::TextAsset() : _alignment(kTextAlignmentLeft), _isBitmap(false) {
}

bool TextAsset::load(AssetLoaderContext &context, const Data::TextAsset &data) {
	_assetID = data.assetID;

	_isBitmap = ((data.isBitmap & 1) != 0);

	// Bitmaps may contain garbled alignment
	switch (data.alignment) {
	case Data::kTextAlignmentCodeLeft:
		_alignment = kTextAlignmentLeft;
		break;
	case Data::kTextAlignmentCodeRight:
		_alignment = kTextAlignmentRight;
		break;
	case Data::kTextAlignmentCodeCenter:
		_alignment = kTextAlignmentCenter;
		break;
	default:
		if (_isBitmap)
			_alignment = kTextAlignmentLeft;
		else
			return false;
		break;
	};

	if (_isBitmap) {
		if (!data.bitmapRect.toScummVMRect(_bitmapRect))
			return false;

		_bitmapData.reset(new Graphics::ManagedSurface());

		uint16 width = _bitmapRect.width();
		uint16 height = _bitmapRect.height();

		uint16 pitch = (data.pitchBigEndian[0] << 8) + data.pitchBigEndian[1];

		if (static_cast<uint32>(pitch * height) != data.bitmapSize) {
			// Pitch is normally aligned to 4 bytes, so if this fails, maybe compute it that way?
			warning("Pre-rendered text bitmap pitch didn't compute to bitmap size correctly, maybe it's wrong?");
			return false;
		}

		if (pitch * 8 < width) {
			warning("Pre-rendered text pitch is too small");
			return false;
		}

		_bitmapData->create(width, height, Graphics::PixelFormat::createFormatCLUT8());

		for (int row = 0; row < height; row++) {
			int outRowY = row;
			if (data.isBottomUp)
				outRowY = height - 1 - row;

			uint8 *outRow = static_cast<uint8 *>(_bitmapData->getBasePtr(0, outRowY));
			const uint8 *inRow = &data.bitmapData[row * pitch];
			for (int col = 0; col < width; col++) {
				int bit = ((inRow[col / 8] >> (7 - (col & 7))) & 1);
				outRow[col] = bit;
			}
		}
	} else {
		_bitmapRect = Common::Rect(0, 0, 0, 0);

		_stringData = data.text;

		for (size_t i = 0; i < data.macFormattingSpans.size(); i++) {
			const Data::TextAsset::MacFormattingSpan &inSpan = data.macFormattingSpans[i];
			MacFormattingSpan fmtSpan;
			fmtSpan.formatting = MacFontFormatting(inSpan.fontID, inSpan.fontFlags, inSpan.size);
			fmtSpan.spanStart = inSpan.spanStart;

			_macFormattingSpans.push_back(fmtSpan);
		}
	}

	return true;
}

AssetType TextAsset::getAssetType() const {
	return kAssetTypeText;
}

bool TextAsset::isBitmap() const {
	return _isBitmap;
}

const Common::SharedPtr<Graphics::ManagedSurface>& TextAsset::getBitmapSurface() const {
	return _bitmapData;
}

const Common::String& TextAsset::getString() const {
	return _stringData;
}

const Common::Array<MacFormattingSpan> &TextAsset::getMacFormattingSpans() const {
	return _macFormattingSpans;
}

} // End of namespace MTropolis