1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * Additional copyright for this file:
8  * Copyright (C) 1995 Presto Studios, Inc.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14 
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19 
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23  *
24  */
25 
26 #include "common/scummsys.h"
27 #include "common/config-manager.h"
28 #include "common/error.h"
29 #include "common/events.h"
30 #include "common/fs.h"
31 #include "common/savefile.h"
32 #include "common/system.h"
33 #include "common/textconsole.h"
34 #include "common/translation.h"
35 #include "common/winexe_ne.h"
36 #include "common/winexe_pe.h"
37 #include "engines/util.h"
38 #include "graphics/wincursor.h"
39 #include "gui/message.h"
40 
41 #include "buried/buried.h"
42 #include "buried/console.h"
43 #include "buried/frame_window.h"
44 #include "buried/graphics.h"
45 #include "buried/message.h"
46 #include "buried/resources.h"
47 #include "buried/sound.h"
48 #include "buried/video_window.h"
49 #include "buried/window.h"
50 
51 namespace Buried {
52 
BuriedEngine(OSystem * syst,const ADGameDescription * gameDesc)53 BuriedEngine::BuriedEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst), _gameDescription(gameDesc) {
54 	_gfx = nullptr;
55 	_mainEXE = nullptr;
56 	_library = nullptr;
57 	_sound = nullptr;
58 	_timerSeed = 0;
59 	_mainWindow = nullptr;
60 	_focusedWindow = nullptr;
61 	_captureWindow = nullptr;
62 	_pauseStartTime = 0;
63 	_yielding = false;
64 
65 	const Common::FSNode gameDataDir(ConfMan.get("path"));
66 	SearchMan.addSubDirectoryMatching(gameDataDir, "WIN31/MANUAL", 0, 2); // v1.05 era
67 	SearchMan.addSubDirectoryMatching(gameDataDir, "WIN95/MANUAL", 0, 2); // v1.10 era (Trilogy release)
68 
69 	// GOG.com release, plainly extracted files
70 	SearchMan.addSubDirectoryMatching(gameDataDir, "data1", 0, 3);
71 	SearchMan.addSubDirectoryMatching(gameDataDir, "data2", 0, 3);
72 	SearchMan.addSubDirectoryMatching(gameDataDir, "data3", 0, 3);
73 }
74 
~BuriedEngine()75 BuriedEngine::~BuriedEngine() {
76 	delete _mainWindow;
77 	delete _gfx;
78 	delete _mainEXE;
79 	delete _library;
80 	delete _sound;
81 
82 	// The queue should be empty since all windows destroy their messages
83 }
84 
run()85 Common::Error BuriedEngine::run() {
86 	setDebugger(new BuriedConsole(this));
87 
88 	if (isTrueColor()) {
89 		initGraphics(640, 480, 0);
90 
91 		if (_system->getScreenFormat().bytesPerPixel == 1)
92 			return Common::kUnsupportedColorMode;
93 	} else {
94 		initGraphics(640, 480);
95 	}
96 
97 	if (isWin95()) {
98 		_mainEXE = new Common::PEResources();
99 		_library = new Common::PEResources();
100 	} else {
101 		_mainEXE = new Common::NEResources();
102 
103 		// Demo only uses the main EXE
104 		if (!isDemo())
105 			_library = new Common::NEResources();
106 	}
107 
108 	if (isCompressed()) {
109 		if (!_mainEXE->loadFromCompressedEXE(getEXEName()))
110 			error("Failed to load main EXE '%s'", getEXEName().c_str());
111 
112 		if (_library && !_library->loadFromCompressedEXE(getLibraryName()))
113 			error("Failed to load library DLL '%s'", getLibraryName().c_str());
114 	} else {
115 		if (!_mainEXE->loadFromEXE(getEXEName()))
116 			error("Failed to load main EXE '%s'", getEXEName().c_str());
117 
118 		if (_library && !_library->loadFromEXE(getLibraryName()))
119 			error("Failed to load library DLL '%s'", getLibraryName().c_str());
120 	}
121 
122 	syncSoundSettings();
123 
124 	_gfx = new GraphicsManager(this);
125 	_sound = new SoundManager(this);
126 	_mainWindow = new FrameWindow(this);
127 	_mainWindow->showWindow(Window::kWindowShow);
128 
129 	if (isDemo()) {
130 		((FrameWindow *)_mainWindow)->showTitleSequence();
131 		((FrameWindow *)_mainWindow)->showMainMenu();
132 	} else {
133 		bool doIntro = true;
134 
135 		if (ConfMan.hasKey("save_slot")) {
136 			uint32 gameToLoad = ConfMan.getInt("save_slot");
137 			doIntro = (loadGameState(gameToLoad).getCode() != Common::kNoError);
138 
139 			// If the trial version tries to load a game without a time
140 			// zone that's part of the trial version, force the intro.
141 			if (isTrial() && !((FrameWindow *)_mainWindow)->getMainChildWindow())
142 				doIntro = true;
143 		}
144 
145 		// Play the intro only if we're starting from scratch
146 		if (doIntro)
147 			((FrameWindow *)_mainWindow)->showClosingScreen();
148 	}
149 
150 	while (!shouldQuit()) {
151 		updateVideos();
152 
153 		pollForEvents();
154 
155 		sendAllMessages();
156 
157 		_gfx->updateScreen();
158 		_system->delayMillis(10);
159 	}
160 
161 	return Common::kNoError;
162 }
163 
getString(uint32 stringID)164 Common::String BuriedEngine::getString(uint32 stringID) {
165 	bool continueReading = true;
166 	Common::String result;
167 
168 	while (continueReading) {
169 		Common::String string = _mainEXE->loadString(stringID);
170 
171 		if (string.empty())
172 			return "";
173 
174 		if (string[0] == '!') {
175 			string.deleteChar(0);
176 			stringID++;
177 		} else {
178 			continueReading = false;
179 		}
180 
181 		result += string;
182 	}
183 
184 	// Change any \r to \n
185 	for (uint32 i = 0; i < result.size(); i++)
186 		if (result[i] == '\r')
187 			result.setChar('\n', i);
188 
189 	return result;
190 }
191 
getFilePath(uint32 stringID)192 Common::String BuriedEngine::getFilePath(uint32 stringID) {
193 	Common::String path = getString(stringID);
194 	Common::String output;
195 
196 	if (path.empty())
197 		return output;
198 
199 	uint i = 0;
200 
201 	// The non-demo paths have CD info followed by a backslash.
202 	// We ignore this.
203 	// In the demo, we remove the "BITDATA" prefix because the
204 	// binaries are in the same directory.
205 	if (isDemo())
206 		i += 8;
207 	else
208 		i += 2;
209 
210 	for (; i < path.size(); i++) {
211 		if (path[i] == '\\')
212 			output += '/';
213 		else
214 			output += path[i];
215 	}
216 
217 	return output;
218 }
219 
getCursorGroup(uint32 cursorGroupID)220 Graphics::WinCursorGroup *BuriedEngine::getCursorGroup(uint32 cursorGroupID) {
221 	return Graphics::WinCursorGroup::createCursorGroup(_mainEXE, cursorGroupID);
222 }
223 
getBitmapStream(uint32 bitmapID)224 Common::SeekableReadStream *BuriedEngine::getBitmapStream(uint32 bitmapID) {
225 	// The demo's bitmaps are in the main EXE
226 	if (isDemo())
227 		return _mainEXE->getResource(Common::kWinBitmap, bitmapID);
228 
229 	// The rest in the database library
230 	return _library->getResource(Common::kWinBitmap, bitmapID);
231 }
232 
getNavData(uint32 resourceID)233 Common::SeekableReadStream *BuriedEngine::getNavData(uint32 resourceID) {
234 	return _mainEXE->getResource(Common::String("NAVDATA"), resourceID);
235 }
236 
getSndData(uint32 resourceID)237 Common::SeekableReadStream *BuriedEngine::getSndData(uint32 resourceID) {
238 	return _mainEXE->getResource(Common::String("SNDDATA"), resourceID);
239 }
240 
getAnimData(uint32 resourceID)241 Common::SeekableReadStream *BuriedEngine::getAnimData(uint32 resourceID) {
242 	return _mainEXE->getResource(Common::String("ANIMDATA"), resourceID);
243 }
244 
getAIData(uint32 resourceID)245 Common::SeekableReadStream *BuriedEngine::getAIData(uint32 resourceID) {
246 	return _mainEXE->getResource(Common::String("AIDATA"), resourceID);
247 }
248 
getItemData(uint32 resourceID)249 Common::SeekableReadStream *BuriedEngine::getItemData(uint32 resourceID) {
250 	return _mainEXE->getResource(Common::String("ITEMDATA"), resourceID);
251 }
252 
getBookData(uint32 resourceID)253 Common::SeekableReadStream *BuriedEngine::getBookData(uint32 resourceID) {
254 	return _mainEXE->getResource(Common::String("BOOKDATA"), resourceID);
255 }
256 
getFileBCData(uint32 resourceID)257 Common::SeekableReadStream *BuriedEngine::getFileBCData(uint32 resourceID) {
258 	return _mainEXE->getResource(Common::String("FILEBCDATA"), resourceID);
259 }
260 
getINNData(uint32 resourceID)261 Common::SeekableReadStream *BuriedEngine::getINNData(uint32 resourceID) {
262 	return _mainEXE->getResource(Common::String("INNDATA"), resourceID);
263 }
264 
createTimer(Window * window,uint period)265 uint BuriedEngine::createTimer(Window *window, uint period) {
266 	uint timer = ++_timerSeed;
267 
268 	Timer timerInfo;
269 	timerInfo.owner = window;
270 	timerInfo.period = period;
271 	timerInfo.nextTrigger = _system->getMillis() + period;
272 
273 	_timers[timer] = timerInfo;
274 	return timer;
275 }
276 
killTimer(uint timer)277 bool BuriedEngine::killTimer(uint timer) {
278 	TimerMap::iterator it = _timers.find(timer);
279 
280 	if (it == _timers.end())
281 		return false;
282 
283 	_timers.erase(it);
284 	return true;
285 }
286 
removeAllTimers(Window * window)287 void BuriedEngine::removeAllTimers(Window *window) {
288 	for (TimerMap::iterator it = _timers.begin(); it != _timers.end(); ++it) {
289 		if (it->_value.owner == window)
290 			_timers.erase(it);
291 	}
292 }
293 
addVideo(VideoWindow * window)294 void BuriedEngine::addVideo(VideoWindow *window) {
295 	_videos.push_back(window);
296 }
297 
removeVideo(VideoWindow * window)298 void BuriedEngine::removeVideo(VideoWindow *window) {
299 	_videos.remove(window);
300 }
301 
updateVideos()302 void BuriedEngine::updateVideos() {
303 	for (VideoList::iterator it = _videos.begin(); it != _videos.end(); ++it)
304 		(*it)->updateVideo();
305 }
306 
postMessageToWindow(Window * dest,Message * message)307 void BuriedEngine::postMessageToWindow(Window *dest, Message *message) {
308 	MessageInfo msg;
309 	msg.dest = dest;
310 	msg.message = message;
311 	_messageQueue.push_back(msg);
312 }
313 
sendAllMessages()314 void BuriedEngine::sendAllMessages() {
315 	while (!shouldQuit() && !_messageQueue.empty()) {
316 		MessageInfo msg = _messageQueue.front();
317 		_messageQueue.pop_front();
318 
319 		msg.dest->sendMessage(msg.message);
320 		// Control of the pointer is passed to the destination
321 	}
322 
323 	// Generate a timer messages while they exist and there are no messages
324 	// in the queue.
325 	while (!shouldQuit() && _messageQueue.empty()) {
326 		// Generate a timer message
327 		bool ranTimer = false;
328 
329 		for (TimerMap::iterator it = _timers.begin(); it != _timers.end(); ++it) {
330 			uint32 time = g_system->getMillis();
331 
332 			if (time >= it->_value.nextTrigger) {
333 				// Adjust the trigger to be what the next one would be, after
334 				// all the current triggers would be called.
335 				uint32 triggerCount = (time - it->_value.nextTrigger + it->_value.period) / it->_value.period;
336 				it->_value.nextTrigger += triggerCount * it->_value.period;
337 				it->_value.owner->sendMessage(new TimerMessage(it->_key));
338 				ranTimer = true;
339 				break;
340 			}
341 		}
342 
343 		// If no timers were run, there's nothing to keep looking for
344 		if (!ranTimer)
345 			break;
346 	}
347 }
348 
removeMessages(Window * window,int messageBegin,int messageEnd)349 void BuriedEngine::removeMessages(Window *window, int messageBegin, int messageEnd) {
350 	for (MessageQueue::iterator it = _messageQueue.begin(); it != _messageQueue.end();) {
351 		if (it->dest == window && it->message->getMessageType() >= messageBegin && it->message->getMessageType() <= messageEnd) {
352 			delete it->message;
353 			it = _messageQueue.erase(it);
354 		} else {
355 			++it;
356 		}
357 	}
358 }
359 
removeKeyboardMessages(Window * window)360 void BuriedEngine::removeKeyboardMessages(Window *window) {
361 	removeMessages(window, kMessageTypeKeyBegin, kMessageTypeKeyEnd);
362 }
363 
removeMouseMessages(Window * window)364 void BuriedEngine::removeMouseMessages(Window *window) {
365 	removeMessages(window, kMessageTypeMouseBegin, kMessageTypeMouseEnd);
366 }
367 
removeAllMessages(Window * window)368 void BuriedEngine::removeAllMessages(Window *window) {
369 	for (MessageQueue::iterator it = _messageQueue.begin(); it != _messageQueue.end();) {
370 		if (it->dest == window) {
371 			delete it->message;
372 			it = _messageQueue.erase(it);
373 		} else {
374 			++it;
375 		}
376 	}
377 }
378 
hasMessage(Window * window,int messageBegin,int messageEnd) const379 bool BuriedEngine::hasMessage(Window *window, int messageBegin, int messageEnd) const {
380 	// Implementation note: This doesn't currently handle timers, but would on real Windows.
381 	// Buried doesn't check for timer messages being present, so it's skipped.
382 
383 	for (MessageQueue::const_iterator it = _messageQueue.begin(); it != _messageQueue.end(); ++it)
384 		if ((!window || it->dest == window) && it->message->getMessageType() >= messageBegin && it->message->getMessageType() <= messageEnd)
385 			return true;
386 
387 	return false;
388 }
389 
yield()390 void BuriedEngine::yield() {
391 	// A cut down version of the Win16 yield function. Win32 handles this
392 	// asynchronously, which we don't want. Only needed for internal event loops.
393 
394 	// Mark us that we're yielding so we can't save or load in a synchronous sequence
395 	_yielding = true;
396 
397 	updateVideos();
398 
399 	pollForEvents();
400 
401 	// We don't send messages any messages from here. Otherwise, this is the same
402 	// as our main loop.
403 
404 	_gfx->updateScreen();
405 	_system->delayMillis(10);
406 
407 	_yielding = false;
408 }
409 
pollForEvents()410 void BuriedEngine::pollForEvents() {
411 	// TODO: Key flags
412 	// TODO: Mouse flags
413 
414 	Common::Event event;
415 	while (_eventMan->pollEvent(event)) {
416 		switch (event.type) {
417 		case Common::EVENT_MOUSEMOVE: {
418 			_gfx->markMouseMoved();
419 			Window *window = _captureWindow ? _captureWindow : _mainWindow->childWindowAtPoint(event.mouse);
420 			window->postMessage(new MouseMoveMessage(window->convertPointToLocal(event.mouse), 0));
421 			window->postMessage(new SetCursorMessage(kMessageTypeMouseMove));
422 			break;
423 		}
424 		case Common::EVENT_KEYUP:
425 			if (_focusedWindow)
426 				_focusedWindow->postMessage(new KeyUpMessage(event.kbd, 0));
427 			break;
428 		case Common::EVENT_KEYDOWN:
429 			if (_focusedWindow)
430 				_focusedWindow->postMessage(new KeyDownMessage(event.kbd, 0));
431 			break;
432 		case Common::EVENT_LBUTTONDOWN: {
433 			Window *window = _captureWindow ? _captureWindow : _mainWindow->childWindowAtPoint(event.mouse);
434 			window->postMessage(new LButtonDownMessage(window->convertPointToLocal(event.mouse), 0));
435 			break;
436 		}
437 		case Common::EVENT_LBUTTONUP: {
438 			Window *window = _captureWindow ? _captureWindow : _mainWindow->childWindowAtPoint(event.mouse);
439 			window->postMessage(new LButtonUpMessage(window->convertPointToLocal(event.mouse), 0));
440 			break;
441 		}
442 		case Common::EVENT_MBUTTONUP: {
443 			Window *window = _captureWindow ? _captureWindow : _mainWindow->childWindowAtPoint(event.mouse);
444 			window->postMessage(new MButtonUpMessage(window->convertPointToLocal(event.mouse), 0));
445 			break;
446 		}
447 		case Common::EVENT_RBUTTONDOWN: {
448 			Window *window = _captureWindow ? _captureWindow : _mainWindow->childWindowAtPoint(event.mouse);
449 			window->postMessage(new RButtonDownMessage(window->convertPointToLocal(event.mouse), 0));
450 			break;
451 		}
452 		case Common::EVENT_RBUTTONUP: {
453 			Window *window = _captureWindow ? _captureWindow : _mainWindow->childWindowAtPoint(event.mouse);
454 			window->postMessage(new RButtonUpMessage(window->convertPointToLocal(event.mouse), 0));
455 			break;
456 		}
457 		default:
458 			break;
459 		}
460 	}
461 }
462 
getTransitionSpeed()463 int BuriedEngine::getTransitionSpeed() {
464 	assert(_mainWindow);
465 	return ((FrameWindow *)_mainWindow)->getTransitionSpeed();
466 }
467 
setTransitionSpeed(int newSpeed)468 void BuriedEngine::setTransitionSpeed(int newSpeed) {
469 	assert(_mainWindow);
470 	((FrameWindow *)_mainWindow)->setTransitionSpeed(newSpeed);
471 }
472 
getVersion()473 uint32 BuriedEngine::getVersion() {
474 	if (isWin95()) {
475 		// Not really needed, it should only be 1.1
476 		return MAKEVERSION(1, 1, 0, 0);
477 	}
478 
479 	Common::WinResources::VersionInfo *versionInfo = _mainEXE->getVersionResource(1);
480 	uint32 result = MAKEVERSION(versionInfo->fileVersion[0], versionInfo->fileVersion[1], versionInfo->fileVersion[2], versionInfo->fileVersion[3]);
481 	delete versionInfo;
482 
483 	return result;
484 }
485 
getFilePath(int timeZone,int environment,int fileOffset)486 Common::String BuriedEngine::getFilePath(int timeZone, int environment, int fileOffset) {
487 	return getFilePath(computeFileNameResourceID(timeZone, environment, fileOffset));
488 }
489 
computeNavDBResourceID(int timeZone,int environment)490 uint32 BuriedEngine::computeNavDBResourceID(int timeZone, int environment) {
491 	return RESID_NAVDB_BASE + RESOFFSET_NAVDB_TIMEZONE * timeZone + environment;
492 }
493 
computeAnimDBResourceID(int timeZone,int environment)494 uint32 BuriedEngine::computeAnimDBResourceID(int timeZone, int environment) {
495 	return RESID_ANIMDB_BASE + RESOFFSET_ANIMDB_TIMEZONE * timeZone + environment;
496 }
497 
computeAIDBResourceID(int timeZone,int environment)498 uint32 BuriedEngine::computeAIDBResourceID(int timeZone, int environment) {
499 	return RESID_AI_DB_BASE + RESOFFSET_AI_DB_TIMEZONE * timeZone + environment;
500 }
501 
computeFileNameResourceID(int timeZone,int environment,int fileOffset)502 uint32 BuriedEngine::computeFileNameResourceID(int timeZone, int environment, int fileOffset) {
503 	return RESID_FILENAMES_BASE + RESOFFSET_FILENAME_TIMEZONE * timeZone + RESOFFSET_FILENAME_ENVIRON * environment + fileOffset;
504 }
505 
pauseEngineIntern(bool pause)506 void BuriedEngine::pauseEngineIntern(bool pause) {
507 	if (pause) {
508 		_sound->pause(true);
509 
510 		for (VideoList::iterator it = _videos.begin(); it != _videos.end(); ++it)
511 			(*it)->pauseVideo();
512 
513 		_pauseStartTime = g_system->getMillis();
514 	} else {
515 		_sound->pause(false);
516 
517 		for (VideoList::iterator it = _videos.begin(); it != _videos.end(); ++it)
518 			(*it)->resumeVideo();
519 
520 		uint32 timeDiff = g_system->getMillis() - _pauseStartTime;
521 
522 		for (TimerMap::iterator it = _timers.begin(); it != _timers.end(); ++it)
523 			it->_value.nextTrigger += timeDiff;
524 	}
525 }
526 
runQuitDialog()527 bool BuriedEngine::runQuitDialog() {
528 	// TODO: Would be nice to load the text out of the EXE for this
529 	// v1.04+: IDS_APP_MESSAGE_QUIT_TEXT (9024)
530 	GUI::MessageDialog dialog(_("Are you sure you want to quit?"), _("Yes"), _("No"));
531 	return dialog.runModal() == GUI::kMessageOK;
532 }
533 
isControlDown() const534 bool BuriedEngine::isControlDown() const {
535 	return _mainWindow && ((FrameWindow *)_mainWindow)->_controlDown;
536 }
537 
538 } // End of namespace Buried
539