File: subtitles.cpp

package info (click to toggle)
residualvm 0.3.1%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 31,292 kB
  • sloc: cpp: 227,029; sh: 7,256; xml: 1,731; perl: 1,067; java: 861; asm: 738; python: 691; ansic: 272; makefile: 139; objc: 81; sed: 22; php: 1
file content (546 lines) | stat: -rw-r--r-- 14,735 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
/* ResidualVM - A 3D game interpreter
 *
 * ResidualVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the AUTHORS
 * 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 "engines/myst3/subtitles.h"
#include "engines/myst3/myst3.h"
#include "engines/myst3/state.h"

#include "common/archive.h"
#include "common/iconv.h"

#include "graphics/fontman.h"
#include "graphics/font.h"
#include "graphics/fonts/ttf.h"

#include "video/bink_decoder.h"

namespace Myst3 {

class FontSubtitles : public Subtitles {
public:
	FontSubtitles(Myst3Engine *vm);
	virtual ~FontSubtitles();

protected:
	void loadResources() override;
	bool loadSubtitles(int32 id) override;
	void drawToTexture(const Phrase *phrase) override;

private:
	void loadCharset(int32 id);
	void createTexture();
	void readPhrases(const DirectorySubEntry *desc);
	static Common::String fakeBidiProcessing(const Common::String &phrase);

	const Graphics::Font *_font;
	Graphics::Surface *_surface;
	float _scale;
	uint8 *_charset;
};

FontSubtitles::FontSubtitles(Myst3Engine *vm) :
	Subtitles(vm),
	_font(0),
	_surface(0),
	_scale(1.0),
	_charset(nullptr) {
}

FontSubtitles::~FontSubtitles() {
	if (_surface) {
		_surface->free();
		delete _surface;
	}

	delete _font;
	delete[] _charset;
}

void FontSubtitles::loadResources() {
	// We draw the subtitles in the adequate resolution so that they are not
	// scaled up. This is the scale factor of the current resolution
	// compared to the original
	_scale = getPosition().width() / (float) getOriginalPosition().width();

#ifdef USE_FREETYPE2
	Common::String ttfFile;
	if (_fontFace == "Arial Narrow") {
		// Use the TTF font provided by the game if TTF support is available
		ttfFile = "arir67w.ttf";
	} else if (_fontFace == "MS Gothic") {
		// The Japanese font has to be supplied by the user
		ttfFile = "msgothic.ttf";
	} else if (_fontFace == "Arial2") {
		// The Hebrew font has to be supplied by the user
		ttfFile = "hebrew.ttf";
	} else {
		error("Unknown subtitles font face '%s'", _fontFace.c_str());
	}

	Common::SeekableReadStream *s = SearchMan.createReadStreamForMember(ttfFile);
	if (s) {
		_font = Graphics::loadTTFFont(*s, _fontSize * _scale);
		delete s;
	} else {
		warning("Unable to load the subtitles font '%s'", ttfFile.c_str());
	}
#endif
}

void FontSubtitles::loadCharset(int32 id) {
	const DirectorySubEntry *fontCharset = _vm->getFileDescription("CHAR", id, 0, DirectorySubEntry::kRawData);

	// Load the font charset if any
	if (fontCharset) {
		Common::MemoryReadStream *data = fontCharset->getData();

		_charset = new uint8[data->size()];

		data->read(_charset, data->size());

		delete data;
	}
}

bool FontSubtitles::loadSubtitles(int32 id) {
	// No game-provided charset for the Japanese version
	if (_fontCharsetCode == 0) {
		loadCharset(1100);
	}

	int32 overridenId = checkOverridenId(id);

	const DirectorySubEntry *desc = loadText(overridenId, overridenId != id);

	if (!desc)
		return false;

	readPhrases(desc);

	if (_vm->getGameLanguage() == Common::HE_ISR) {
		for (uint i = 0; i < _phrases.size(); i++) {
			_phrases[i].string = fakeBidiProcessing(_phrases[i].string);
		}
	}

	return true;
}

void FontSubtitles::readPhrases(const DirectorySubEntry *desc) {
	Common::MemoryReadStream *crypted = desc->getData();

	// Read the frames and associated text offsets
	while (true) {
		Phrase s;
		s.frame = crypted->readUint32LE();
		s.offset = crypted->readUint32LE();

		if (!s.frame)
			break;

		_phrases.push_back(s);
	}

	// Read and decrypt the frames subtitles
	for (uint i = 0; i < _phrases.size(); i++) {
		crypted->seek(_phrases[i].offset);

		uint8 key = 35;
		while (true) {
			uint8 c = crypted->readByte() ^ key++;

			if (c >= 32 && _charset)
				c = _charset[c - 32];

			if (!c)
				break;

			_phrases[i].string += c;
		}
	}

	delete crypted;
}

static bool isPunctuation(char c) {
	return c == '.' || c == ',' || c == '\"'  || c == '!' || c == '?';
}

Common::String FontSubtitles::fakeBidiProcessing(const Common::String &phrase) {
	// The Hebrew subtitles are stored in logical order:
	// .ABC DEF GHI
	// This line should be rendered in visual order as:
	// .IHG FED CBA

	// Notice how the dot is on the left both in logical and visual order. This is
	// because it is in left to right order while the Hebrew characters are in right to
	// left order. Text rendering code needs to apply what is called the BiDirectional
	// algorithm to know which parts of an input string are LTR or RTL and how to render
	// them. This is a quite complicated algorithm. Fortunately the subtitles in Myst III
	// only require very specific BiDi processing. The punctuation signs at the beginning of
	// each line need to be moved to the end so that they are visually to the left once
	// the string is rendered from right to left.
	// This method works around the need to implement proper BiDi processing
	// by exploiting that fact.

	uint punctuationCounter = 0;
	while (punctuationCounter < phrase.size() && isPunctuation(phrase[punctuationCounter])) {
		punctuationCounter++;
	}

	Common::String output = Common::String(phrase.c_str() + punctuationCounter);
	for (uint i = 0; i < punctuationCounter; i++) {
		output += phrase[i];
	}

	// Also reverse the string so that it is in visual order.
	// This is necessary because our text rendering code does not actually support RTL.
	for (int i = 0, j = output.size() - 1; i < j; i++, j--) {
		char c = output[i];
		output.setChar(output[j], i);
		output.setChar(c, j);
	}

	return output;
}

void FontSubtitles::createTexture() {
	// Create a surface to draw the subtitles on
	// Use RGB 565 to allow use of BDF fonts
	if (!_surface) {
		_surface = new Graphics::Surface();
		_surface->create(Renderer::kOriginalWidth * _scale, _surfaceHeight * _scale, Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0));
	}

	if (!_texture) {
		_texture = _vm->_gfx->createTexture(_surface);
	}
}

#ifdef USE_ICONV
/** Return an encoding from a GDI Charset as provided to CreateFont */
static Common::Encoding getEncodingFromCharsetCode(uint32 gdiCharset) {
	static const struct {
		uint32 charset;
		Common::Encoding encoding;
	} codepages[] = {
			{ 128, Common::kEncodingCP932            }, // SHIFTJIS_CHARSET
			{ 177, Common::kEncodingCP1255           }, // HEBREW_CHARSET
			{ 204, Common::kEncodingCP1251           }, // RUSSIAN_CHARSET
			{ 238, Common::kEncodingMacCentralEurope }  // EASTEUROPE_CHARSET
	};

	for (uint i = 0; i < ARRAYSIZE(codepages); i++) {
		if (gdiCharset == codepages[i].charset) {
			return codepages[i].encoding;
		}
	}

	error("Unknown font charset code '%d'", gdiCharset);
}
#endif

void FontSubtitles::drawToTexture(const Phrase *phrase) {
	const Graphics::Font *font;
	if (_font)
		font = _font;
	else
		font = FontMan.getFontByUsage(Graphics::FontManager::kLocalizedFont);

	if (!font)
		error("No available font");

	if (!_texture || !_surface) {
		createTexture();
	}

	// Draw the new text
	memset(_surface->getPixels(), 0, _surface->pitch * _surface->h);


	if (_fontCharsetCode == 0) {
		font->drawString(_surface, phrase->string, 0, _singleLineTop * _scale, _surface->w, 0xFFFFFFFF, Graphics::kTextAlignCenter);
	} else {
#ifdef USE_ICONV
		Common::Encoding encoding = getEncodingFromCharsetCode(_fontCharsetCode);
		Common::U32String unicode = Common::convertToU32String(encoding, phrase->string);
		font->drawString(_surface, unicode, 0, _singleLineTop * _scale, _surface->w, 0xFFFFFFFF, Graphics::kTextAlignCenter);
#else
		warning("Unable to display charset '%d' subtitles, iconv support is not compiled in.", _fontCharsetCode);
#endif
	}

	// Update the texture
	_texture->update(_surface);
}

class MovieSubtitles : public Subtitles {
public:
	MovieSubtitles(Myst3Engine *vm);
	virtual ~MovieSubtitles();

protected:
	void loadResources() override;
	bool loadSubtitles(int32 id) override;
	void drawToTexture(const Phrase *phrase) override;

private:
	const DirectorySubEntry *loadMovie(int32 id, bool overriden);
	void readPhrases(const DirectorySubEntry *desc);

	Video::BinkDecoder _bink;
};

MovieSubtitles::MovieSubtitles(Myst3Engine *vm) :
		Subtitles(vm) {
}

MovieSubtitles::~MovieSubtitles() {
}

void MovieSubtitles::readPhrases(const DirectorySubEntry *desc) {
	Common::MemoryReadStream *frames = desc->getData();

	// Read the frames
	uint index = 0;
	while (true) {
		Phrase s;
		s.frame = frames->readUint32LE();
		s.offset = index;

		if (!s.frame)
			break;

		_phrases.push_back(s);
		index++;
	}

	delete frames;
}

const DirectorySubEntry *MovieSubtitles::loadMovie(int32 id, bool overriden) {
	const DirectorySubEntry *desc;
	if (overriden) {
		desc = _vm->getFileDescription("IMGR", 200000 + id, 0, DirectorySubEntry::kMovie);
	} else {
		desc = _vm->getFileDescription("", 200000 + id, 0, DirectorySubEntry::kMovie);
	}
	return desc;
}

bool MovieSubtitles::loadSubtitles(int32 id) {
	int32 overridenId = checkOverridenId(id);

	const DirectorySubEntry *phrases = loadText(overridenId, overridenId != id);
	const DirectorySubEntry *movie = loadMovie(overridenId, overridenId != id);

	if (!phrases || !movie)
		return false;

	readPhrases(phrases);

	// Load the movie
	Common::MemoryReadStream *movieStream = movie->getData();
	_bink.setDefaultHighColorFormat(Texture::getRGBAPixelFormat());
	_bink.loadStream(movieStream);
	_bink.start();

	return true;
}

void MovieSubtitles::loadResources() {
}

void MovieSubtitles::drawToTexture(const Phrase *phrase) {
	_bink.seekToFrame(phrase->offset);
	const Graphics::Surface *surface = _bink.decodeNextFrame();

	if (!_texture) {
		_texture = _vm->_gfx->createTexture(surface);
	} else {
		_texture->update(surface);
	}
}

Subtitles::Subtitles(Myst3Engine *vm) :
		Window(),
		_vm(vm),
		_texture(0),
		_frame(-1) {
	_scaled = !_vm->isWideScreenModEnabled();
}

Subtitles::~Subtitles() {
	freeTexture();
}

void Subtitles::loadFontSettings(int32 id) {
	// Load font settings
	const DirectorySubEntry *fontNums = _vm->getFileDescription("NUMB", id, 0, DirectorySubEntry::kNumMetadata);

	if (!fontNums)
		error("Unable to load font settings values");

	_fontSize = fontNums->getMiscData(0);
	_fontBold = fontNums->getMiscData(1);
	_surfaceHeight = fontNums->getMiscData(2);
	_singleLineTop = fontNums->getMiscData(3);
	_line1Top = fontNums->getMiscData(4);
	_line2Top = fontNums->getMiscData(5);
	_surfaceTop = fontNums->getMiscData(6);
	_fontCharsetCode = fontNums->getMiscData(7);

	if (_fontCharsetCode > 0) {
		_fontCharsetCode = 128; // The Japanese subtitles are encoded in CP 932 / Shift JIS
	}

	if (_vm->getGameLanguage() == Common::HE_ISR) {
		// The Hebrew subtitles are encoded in CP 1255, but the game data does not specify the appropriate encoding
		_fontCharsetCode = 177;
	}

	if (_fontCharsetCode < 0) {
		_fontCharsetCode = -_fontCharsetCode; // Negative values are GDI charset codes
	}

	const DirectorySubEntry *fontText = _vm->getFileDescription("TEXT", id, 0, DirectorySubEntry::kTextMetadata);

	if (!fontText)
		error("Unable to load font face");

	_fontFace = fontText->getTextData(0);
}

int32 Subtitles::checkOverridenId(int32 id) {
	// Subtitles may be overridden using a variable
	if (_vm->_state->getMovieOverrideSubtitles()) {
		id = _vm->_state->getMovieOverrideSubtitles();
		_vm->_state->setMovieOverrideSubtitles(0);
	}
	return id;
}

const DirectorySubEntry *Subtitles::loadText(int32 id, bool overriden) {
	const DirectorySubEntry *desc;
	if (overriden) {
		desc = _vm->getFileDescription("IMGR", 100000 + id, 0, DirectorySubEntry::kText);
	} else {
		desc = _vm->getFileDescription("", 100000 + id, 0, DirectorySubEntry::kText);
	}
	return desc;
}

void Subtitles::setFrame(int32 frame) {
	const Phrase *phrase = nullptr;

	for (uint i = 0; i < _phrases.size(); i++) {
		if (_phrases[i].frame > frame)
			break;

		phrase = &_phrases[i];
	}

	if (!phrase) {
		freeTexture();
		return;
	}

	if (phrase->frame == _frame) {
		return;
	}

	_frame = phrase->frame;

	drawToTexture(phrase);
}

void Subtitles::drawOverlay() {
	if (!_texture) return;

	Common::Rect screen = _vm->_gfx->viewport();
	Common::Rect bottomBorder = Common::Rect(Renderer::kOriginalWidth, _surfaceHeight);
	bottomBorder.translate(0, _surfaceTop);

	if (_vm->isWideScreenModEnabled()) {
		// Draw a black background to cover the main game frame
		_vm->_gfx->drawRect2D(Common::Rect(screen.width(), Renderer::kBottomBorderHeight), 0xFF000000);

		// Center the subtitles in the screen
		bottomBorder.translate((screen.width() - Renderer::kOriginalWidth) / 2, 0);
	}

	Common::Rect textureRect = Common::Rect(_texture->width, _texture->height);

	_vm->_gfx->drawTexturedRect2D(bottomBorder, textureRect, _texture);
}

Subtitles *Subtitles::create(Myst3Engine *vm, uint32 id) {
	Subtitles *s;

	if (vm->getPlatform() == Common::kPlatformXbox) {
		s = new MovieSubtitles(vm);
	} else {
		s = new FontSubtitles(vm);
	}

	s->loadFontSettings(1100);

	if (!s->loadSubtitles(id)) {
		delete s;
		return 0;
	}

	s->loadResources();

	return s;
}

void Subtitles::freeTexture() {
	if (_texture) {
		_vm->_gfx->freeTexture(_texture);
		_texture = nullptr;
	}
}

Common::Rect Subtitles::getPosition() const {
	Common::Rect screen = _vm->_gfx->viewport();

	Common::Rect frame;

	if (_vm->isWideScreenModEnabled()) {
		frame = Common::Rect(screen.width(), Renderer::kBottomBorderHeight);
		frame.translate(0, screen.height() - frame.height());
	} else {
		frame = Common::Rect(screen.width(), screen.height() * Renderer::kBottomBorderHeight / Renderer::kOriginalHeight);
		frame.translate(screen.left, screen.top + screen.height() * (Renderer::kTopBorderHeight + Renderer::kFrameHeight) / Renderer::kOriginalHeight);
	}

	return frame;
}

Common::Rect Subtitles::getOriginalPosition() const {
	Common::Rect originalPosition = Common::Rect(Renderer::kOriginalWidth, Renderer::kBottomBorderHeight);
	originalPosition.translate(0, Renderer::kTopBorderHeight + Renderer::kFrameHeight);
	return originalPosition;
}

} // End of namespace Myst3