File: LoadScreen.cpp

package info (click to toggle)
spring 88.0%2Bdfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 41,524 kB
  • sloc: cpp: 343,114; ansic: 38,414; python: 12,257; java: 12,203; awk: 5,748; sh: 1,204; xml: 997; perl: 405; objc: 192; makefile: 181; php: 134; sed: 2
file content (440 lines) | stat: -rwxr-xr-x 11,989 bytes parent folder | download
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "System/mmgr.h"
#include <SDL.h>

#include "Rendering/GL/myGL.h"
#include "LoadScreen.h"
#include "Game.h"
#include "GameVersion.h"
#include "GlobalUnsynced.h"
#include "Player.h"
#include "PlayerHandler.h"
#include "Game/UI/MouseHandler.h"
#include "Game/UI/InputReceiver.h"
#include "ExternalAI/SkirmishAIHandler.h"
#include "Map/MapInfo.h"
#include "Rendering/glFont.h"
#include "Rendering/GlobalRendering.h"
#include "Rendering/Textures/Bitmap.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Path/IPathManager.h"
#include "System/Config/ConfigHandler.h"
#include "System/EventHandler.h"
#include "System/Exceptions.h"
#include "System/Sync/FPUCheck.h"
#include "System/Log/ILog.h"
#include "System/NetProtocol.h"
#include "System/FileSystem/FileHandler.h"
#include "System/Platform/Watchdog.h"
#include "System/Sound/ISound.h"
#include "System/Sound/SoundChannels.h"

#if !defined(HEADLESS) && !defined(NO_SOUND)
	#include "System/Sound/EFX.h"
	#include "System/Sound/EFXPresets.h"
#endif

#include <vector>

CONFIG(int, LoadingMT).defaultValue(-1).safemodeValue(0);

CLoadScreen* CLoadScreen::singleton = NULL;

/******************************************************************************/

CLoadScreen::CLoadScreen(const std::string& _mapName, const std::string& _modName, ILoadSaveHandler* _saveFile) :
	mapName(_mapName),
	modName(_modName),
	saveFile(_saveFile),
	netHeartbeatThread(NULL),
	gameLoadThread(NULL),
	mt_loading(true),
	startupTexture(0),
	aspectRatio(1.0f),
	last_draw(0)
{
}

void CLoadScreen::Init()
{
	activeController = this;

	//! hide the cursor until we are ingame
	SDL_ShowCursor(SDL_DISABLE);

	//! When calling this function, mod archives have to be loaded
	//! and gu->myPlayerNum has to be set.
	skirmishAIHandler.LoadPreGame();

#ifdef HEADLESS
	mt_loading = false;
#else
	const int mtCfg = configHandler->GetInt("LoadingMT");
	// user override
	mt_loading = (mtCfg > 0);
	// runtime detect. disable for intel/mesa drivers, they crash at multithreaded OpenGL (date: Nov. 2011)
	mt_loading |= (mtCfg < 0) && !globalRendering->haveMesa && !globalRendering->haveIntel;
#endif

	//! Create a thread during the loading that pings the host/server, so it knows that this client is still alive/loading
	netHeartbeatThread = new boost::thread(boost::bind<void, CNetProtocol, CNetProtocol*>(&CNetProtocol::UpdateLoop, net));

	game = new CGame(mapName, modName, saveFile);

	//FIXME: remove when LuaLoadScreen was added
	{
		const CTeam* team = teamHandler->Team(gu->myTeam);
		assert(team);
		const std::string mapStartPic(mapInfo->GetStringValue("Startpic"));

		if (mapStartPic.empty())
			RandomStartPicture(team->side);
		else
			LoadStartPicture(mapStartPic);

		const std::string mapStartMusic(mapInfo->GetStringValue("Startmusic"));
		if (!mapStartMusic.empty())
			Channels::BGMusic.StreamPlay(mapStartMusic);
	}

	try {
		//! Create the Game Loading Thread
		if (mt_loading)
			gameLoadThread = new COffscreenGLThread( boost::bind(&CGame::LoadGame, game, mapName) );

	} catch (const opengl_error& gle) {
		LOG_L(L_WARNING, "Offscreen GL Context creation failed, "
				"falling back to single-threaded loading. The problem was: %s",
				gle.what());
		mt_loading = false;
	}

	if (!mt_loading) {
		LOG("LoadingScreen: single-threaded");
		game->LoadGame(mapName);
	}
}


CLoadScreen::~CLoadScreen()
{
	// at this point, the thread running CGame::LoadGame
	// has finished and deregistered itself from WatchDog
	if (mt_loading && gameLoadThread)
		gameLoadThread->Join();
	delete gameLoadThread; gameLoadThread = NULL;

	if (net)
		net->loading = false;
	if (netHeartbeatThread)
		netHeartbeatThread->join();
	delete netHeartbeatThread; netHeartbeatThread = NULL;

	if (!gu->globalQuit) {
		//! sending your playername to the server indicates that you are finished loading
		const CPlayer* p = playerHandler->Player(gu->myPlayerNum);
		net->Send(CBaseNetProtocol::Get().SendPlayerName(gu->myPlayerNum, p->name));
#ifdef SYNCCHECK
		net->Send(CBaseNetProtocol::Get().SendPathCheckSum(gu->myPlayerNum, pathManager->GetPathCheckSum()));
#endif
		mouse->ShowMouse();

#if !defined(HEADLESS) && !defined(NO_SOUND)
		// sound is initialized at this point,
		// but EFX support is *not* guaranteed
		if (efx != NULL) {
			*(efx->sfxProperties) = *(mapInfo->efxprops);
			efx->CommitEffects();
		}
#endif
		game->SetupRenderingParams();

		activeController = game;
	}

	UnloadStartPicture();

	if (activeController == this)
		activeController = NULL;

	singleton = NULL;
}


/******************************************************************************/

void CLoadScreen::CreateInstance(const std::string& mapName, const std::string& modName, ILoadSaveHandler* saveFile)
{
	assert(singleton == NULL);

	singleton = new CLoadScreen(mapName, modName, saveFile);
	// Init() already requires GetInstance() to work.
	singleton->Init();
	if (!singleton->mt_loading) {
		game->SetupRenderingParams();
		CLoadScreen::DeleteInstance();
	}
}


void CLoadScreen::DeleteInstance()
{
	delete singleton;
	singleton = NULL;
}


/******************************************************************************/

void CLoadScreen::ResizeEvent()
{
	//eventHandler.ViewResize();
}


int CLoadScreen::KeyPressed(unsigned short k, bool isRepeat)
{
	//! try the input receivers
	/*std::deque<CInputReceiver*>& inputReceivers = GetInputReceivers();
	std::deque<CInputReceiver*>::iterator ri;
	for (ri = inputReceivers.begin(); ri != inputReceivers.end(); ++ri) {
		CInputReceiver* recv = *ri;
		if (recv && recv->KeyPressed(k, isRepeat)) {
			return 0;
		}
	}*/

	return 0;
}


int CLoadScreen::KeyReleased(unsigned short k)
{
	//! try the input receivers
	/*std::deque<CInputReceiver*>& inputReceivers = GetInputReceivers();
	std::deque<CInputReceiver*>::iterator ri;
	for (ri = inputReceivers.begin(); ri != inputReceivers.end(); ++ri) {
		CInputReceiver* recv = *ri;
		if (recv && recv->KeyReleased(k)) {
			return 0;
		}
	}*/

	return 0;
}


bool CLoadScreen::Update()
{
	{
		//! cause of `curLoadMessage`
		boost::recursive_mutex::scoped_lock lck(mutex);
		//! Stuff that needs to be done regularly while loading.
		good_fpu_control_registers(curLoadMessage.c_str());
	}

	if (game->finishedLoading) {
		CLoadScreen::DeleteInstance();
	}

	return true;
}


bool CLoadScreen::Draw()
{
	//! Limit the Frames Per Second to not lock a singlethreaded CPU from loading the game
	if (mt_loading) {
		spring_time now = spring_gettime();
		unsigned diff_ms = spring_tomsecs(now - last_draw);
		static unsigned min_frame_time = 40; //! 40ms = 25FPS
		if (diff_ms < min_frame_time) {
			spring_time nap = spring_msecs(min_frame_time - diff_ms);
			spring_sleep(nap);
		}
		last_draw = now;
	}

	//! cause of `curLoadMessage`
	boost::recursive_mutex::scoped_lock lck(mutex);

	ClearScreen();

	float xDiv = 0.0f;
	float yDiv = 0.0f;
	const float ratioComp = globalRendering->aspectRatio / aspectRatio;
	if (fabs(ratioComp - 1.0f) < 0.01f) { //! ~= 1
		//! show Load-Screen full screen
		//! nothing to do
	} else if (ratioComp > 1.0f) {
		//! show Load-Screen on part of the screens X-Axis only
		xDiv = (1.0f - (1.0f / ratioComp)) * 0.5f;
	} else {
		//! show Load-Screen on part of the screens Y-Axis only
		yDiv = (1.0f - ratioComp) * 0.5f;
	}

	//! Draw loading screen & print load msg.
	if (startupTexture) {
		glBindTexture(GL_TEXTURE_2D,startupTexture);
		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f); glVertex2f(0.0f + xDiv, 0.0f + yDiv);
			glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f + xDiv, 1.0f - yDiv);
			glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0f - xDiv, 1.0f - yDiv);
			glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0f - xDiv, 0.0f + yDiv);
		glEnd();
	}

	font->Begin();
		font->SetTextColor(0.5f,0.5f,0.5f,0.9f);
		font->glPrint(0.1f,0.9f,   globalRendering->viewSizeY / 35.0f, FONT_NORM,
			oldLoadMessages);

		font->SetTextColor(0.9f,0.9f,0.9f,0.9f);
		float posy = font->GetTextNumLines(oldLoadMessages) * font->GetLineHeight() * globalRendering->viewSizeY / 35.0f;
		font->glPrint(0.1f,0.9f - posy * globalRendering->pixelY,   globalRendering->viewSizeY / 35.0f, FONT_NORM,
			curLoadMessage);


		font->SetOutlineColor(0.0f,0.0f,0.0f,0.65f);
		font->SetTextColor(1.0f,1.0f,1.0f,1.0f);
#ifdef USE_GML
		font->glFormat(0.5f,0.06f, globalRendering->viewSizeY / 35.0f, FONT_OUTLINE | FONT_CENTER | FONT_NORM,
			"Spring %s (%d threads)", SpringVersion::GetFull().c_str(), GML::ThreadCount());
#else
		font->glFormat(0.5f,0.06f, globalRendering->viewSizeY / 35.0f, FONT_OUTLINE | FONT_CENTER | FONT_NORM,
			"Spring %s", SpringVersion::GetFull().c_str());
#endif
		font->glFormat(0.5f,0.02f, globalRendering->viewSizeY / 50.0f, FONT_OUTLINE | FONT_CENTER | FONT_NORM,
			"This program is distributed under the GNU General Public License, see license.html for more info");
	font->End();

	if (!mt_loading)
		SDL_GL_SwapBuffers();

	return true;
}


/******************************************************************************/
/******************************************************************************/

void CLoadScreen::SetLoadMessage(const std::string& text, bool replace_lastline)
{
	Watchdog::ClearTimer(WDT_LOAD);

	boost::recursive_mutex::scoped_lock lck(mutex);

	if (!replace_lastline) {
		if (oldLoadMessages.empty()) {
			oldLoadMessages = curLoadMessage;
		} else {
			oldLoadMessages += "\n" + curLoadMessage;
		}
	}
	curLoadMessage = text;

	LOG("%s", text.c_str());
	LOG_CLEANUP();

	//! Check the FPU state (needed for synced computations),
	//! some external libraries which get linked during loading might reset those.
	//! Here it is done for the loading thread, for the mainthread it is done in CLoadScreen::Update()
	good_fpu_control_registers(curLoadMessage.c_str());

	if (!mt_loading)
		Draw();
}


/******************************************************************************/

static void AppendStringVec(vector<string>& dst, const vector<string>& src)
{
	for (int i = 0; i < (int)src.size(); i++) {
		dst.push_back(src[i]);
	}
}


static string SelectPicture(const std::string& dir, const std::string& prefix)
{
	std::vector<string> pics;

	AppendStringVec(pics, CFileHandler::FindFiles(dir, prefix + "*"));

	//! add 'allside_' pictures if we don't have a prefix
	if (!prefix.empty()) {
		AppendStringVec(pics, CFileHandler::FindFiles(dir, "allside_*"));
	}

	if (pics.empty()) {
		return "";
	}

	return pics[gu->usRandInt() % pics.size()];
}


void CLoadScreen::RandomStartPicture(const std::string& sidePref)
{
	if (startupTexture)
		return;

	const std::string picDir = "bitmaps/loadpictures/";

	std::string name = "";
	if (!sidePref.empty()) {
		name = SelectPicture(picDir, sidePref + "_");
	}
	if (name.empty()) {
		name = SelectPicture(picDir, "");
	}
	if (name.empty() || (name.rfind(".db") == name.size() - 3)) {
		return; // no valid pictures
	}
	LoadStartPicture(name);
}


void CLoadScreen::LoadStartPicture(const std::string& name)
{
	CBitmap bm;
	if (!bm.Load(name)) {
		throw content_error("Could not load startpicture from file " + name);
	}

	aspectRatio = (float)bm.xsize / bm.ysize;

	if ((bm.xsize > globalRendering->viewSizeX) || (bm.ysize > globalRendering->viewSizeY)) {
		float newX = globalRendering->viewSizeX;
		float newY = globalRendering->viewSizeY;

		// Make smaller but preserve aspect ratio.
		// The resulting resolution will make it fill one axis of the
		// screen, and be smaller or equal to the screen on the other axis.
		const float ratioComp = globalRendering->aspectRatio / aspectRatio;
		if (ratioComp > 1.0f) {
			newX = newX / ratioComp;
		} else {
			newY = newY * ratioComp;
		}

		bm = bm.CreateRescaled((int) newX, (int) newY);
	}

	startupTexture = bm.CreateTexture(false);
}


void CLoadScreen::UnloadStartPicture()
{
	if (startupTexture) {
		glDeleteTextures(1, &startupTexture);
	}
	startupTexture = 0;
}


/******************************************************************************/