1 // ==============================================================
2 //	This file is part of Glest (www.glest.org)
3 //
4 //	Copyright (C) 2001-2008 Martiño Figueroa
5 //
6 //	You can redistribute this code and/or modify it under
7 //	the terms of the GNU General Public License as published
8 //	by the Free Software Foundation; either version 2 of the
9 //	License, or (at your option) any later version
10 // ==============================================================
11 
12 #include "program.h"
13 
14 #include "sound.h"
15 #include "renderer.h"
16 #include "config.h"
17 #include "game.h"
18 #include "main_menu.h"
19 #include "intro.h"
20 #include "world.h"
21 #include "main.h"
22 #include "sound_renderer.h"
23 #include "logger.h"
24 #include "profiler.h"
25 #include "core_data.h"
26 #include "metrics.h"
27 #include "network_manager.h"
28 #include "menu_state_custom_game.h"
29 #include "menu_state_join_game.h"
30 #include "menu_state_scenario.h"
31 #include "leak_dumper.h"
32 
33 using namespace Shared::Util;
34 using namespace Shared::Graphics;
35 using namespace Shared::Graphics::Gl;
36 
37 // =====================================================
38 // 	class Program
39 // =====================================================
40 
41 namespace Glest{ namespace Game{
42 
43 const int Program::maxTimes= 10;
44 Program *Program::singleton = NULL;
45 const int SOUND_THREAD_UPDATE_MILLISECONDS = 25;
46 
47 bool Program::wantShutdownApplicationAfterGame = false;
48 const char *ProgramState::MAIN_PROGRAM_RENDER_KEY = "MEGAGLEST.RENDER";
49 
50 // =====================================================
51 // 	class Program::CrashProgramState
52 // =====================================================
53 
ProgramState(Program * program)54 ProgramState::ProgramState(Program *program) {
55 	this->program= program;
56 	this->forceMouseRender = false;
57 	this->mouseX = 0;
58 	this->mouseY = 0;
59 	this->mouse2dAnim = 0;
60 	this->fps= 0;
61 	this->lastFps= 0;
62 	this->startX=0;
63 	this->startY=0;
64 }
65 
restoreToStartXY()66 void ProgramState::restoreToStartXY() {
67 	SDL_WarpMouseInWindow(this->program->getWindow()->getSDLWindow(), startX, startY);
68 }
69 
incrementFps()70 void ProgramState::incrementFps() {
71 	fps++;
72 }
73 
tick()74 void ProgramState::tick() {
75 	lastFps= fps;
76 	fps= 0;
77 }
78 
canRender(bool sleepIfCannotRender)79 bool ProgramState::canRender(bool sleepIfCannotRender) {
80 	int maxFPSCap = Config::getInstance().getInt("RenderFPSCap","500");
81 	int sleepMillis = Config::getInstance().getInt("RenderFPSCapSleepMillis","1");
82 	//Renderer &renderer= Renderer::getInstance();
83 	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) {
84 		maxFPSCap = Config::getInstance().getInt("RenderFPSCapHeadless","250");
85 		sleepMillis = Config::getInstance().getInt("RenderFPSCapHeadlessSleepMillis","1");
86 	}
87 
88 	if(lastFps > maxFPSCap) {
89 		if(sleepIfCannotRender == true) {
90 			sleep(sleepMillis);
91 			//if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sleeping because lastFps = %d, maxFPSCap = %d sleepMillis = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,lastFps,maxFPSCap,sleepMillis);
92 		}
93 		return false;
94 	}
95 	return true;
96 }
97 
render()98 void ProgramState::render() {
99 	Renderer &renderer= Renderer::getInstance();
100 
101 	canRender();
102 	incrementFps();
103 
104 	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) {
105 		renderer.clearBuffers();
106 		renderer.reset2d();
107 		renderer.renderMessageBox(program->getMsgBox());
108 		renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim);
109 		renderer.swapBuffers();
110 	}
111 }
112 
update()113 void ProgramState::update() {
114 	mouse2dAnim = (mouse2dAnim +1) % Renderer::maxMouse2dAnim;
115 }
116 
mouseMove(int x,int y,const MouseState * mouseState)117 void ProgramState::mouseMove(int x, int y, const MouseState *mouseState) {
118 	mouseX = x;
119 	mouseY = y;
120 	program->getMsgBox()->mouseMove(x, y);
121 }
122 
ShowMessageProgramState(Program * program,const char * msg)123 Program::ShowMessageProgramState::ShowMessageProgramState(Program *program, const char *msg) :
124 		ProgramState(program) {
125     userWantsExit = false;
126 	msgBox.registerGraphicComponent("ShowMessageProgramState", "msgBox");
127 	msgBox.init("Ok");
128 
129 	if(msg) {
130 		fprintf(stderr, "%s\n", msg);
131 		msgBox.setText(msg);
132 	}
133 	else {
134 		msgBox.setText("Mega-Glest has crashed.");
135 	}
136 
137 	mouse2dAnim = mouseY = mouseX = 0;
138 	this->msg = (msg ? msg : "");
139 }
140 
render()141 void Program::ShowMessageProgramState::render() {
142 	Renderer &renderer= Renderer::getInstance();
143 	renderer.clearBuffers();
144 	renderer.reset2d();
145 	renderer.renderMessageBox(&msgBox);
146 	renderer.renderMouse2d(mouseX, mouseY, mouse2dAnim);
147 	renderer.swapBuffers();
148 }
149 
mouseDownLeft(int x,int y)150 void Program::ShowMessageProgramState::mouseDownLeft(int x, int y) {
151 	int button= 0;
152 	if(msgBox.mouseClick(x,y,button)) {
153 		program->exit();
154 		userWantsExit = true;
155 	}
156 }
157 
keyPress(SDL_KeyboardEvent c)158 void Program::ShowMessageProgramState::keyPress(SDL_KeyboardEvent c) {
159 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] c = [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,c.keysym.sym);
160 
161     // if user pressed return we exit
162 	//if(c == 13) {
163 	if(isKeyPressed(SDLK_RETURN,c) == true) {
164 		program->exit();
165 		userWantsExit = true;
166 	}
167 }
168 
mouseMove(int x,int y,const MouseState & mouseState)169 void Program::ShowMessageProgramState::mouseMove(int x, int y, const MouseState &mouseState) {
170 	mouseX = x;
171 	mouseY = y;
172 	msgBox.mouseMove(x, y);
173 }
174 
update()175 void Program::ShowMessageProgramState::update() {
176 	mouse2dAnim = (mouse2dAnim +1) % Renderer::maxMouse2dAnim;
177 }
178 
179 // ===================== PUBLIC ========================
180 
181 bool Program::rendererInitOk = false;
182 bool Program::tryingRendererInit = false;
183 
Program()184 Program::Program() : msgBox("Program", "msgBox") {
185 	//this->masterserverMode = false;
186 	this->window = NULL;
187 	this->shutdownApplicationEnabled = false;
188 	this->skipRenderFrameCount = 0;
189 	this->messageBoxIsSystemError = false;
190 	this->programStateOldSystemError = NULL;
191 	this->programState= NULL;
192 	this->singleton = this;
193 	this->soundThreadManager = NULL;
194 
195 	//mesage box
196 	Lang &lang= Lang::getInstance();
197 	//msgBox.registerGraphicComponent("Program", "msgBox");
198 	msgBox.init(lang.getString("Ok"));
199 	msgBox.setEnabled(false);
200 }
201 
202 //bool Program::isMasterserverMode() const {
203 //	return this->masterserverMode;
204 //}
205 
initNormal(WindowGl * window)206 void Program::initNormal(WindowGl *window){
207 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
208 	Config &config = Config::getInstance();
209 	init(window);
210 
211 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
212 
213 	setState(new Intro(this));
214 	showCursor(config.getBool("No2DMouseRendering","false"));
215 
216 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
217 }
218 
initSavedGame(WindowGl * window,bool masterserverMode,string saveGameFile)219 void Program::initSavedGame(WindowGl *window,bool masterserverMode, string saveGameFile) {
220 	init(window);
221 	MainMenu *mainMenu= new MainMenu(this);
222 	setState(mainMenu);
223 
224 	if(saveGameFile == "") {
225 		Config &config = Config::getInstance();
226 		saveGameFile = config.getString("LastSavedGame","");
227 		if(saveGameFile == "") {
228 			saveGameFile = GameConstants::saveGameFileDefault;
229 			if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") {
230 				saveGameFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + saveGameFile;
231 			}
232 			else {
233 				string userData = Config::getInstance().getString("UserData_Root","");
234 				if(userData != "") {
235 					endPathWithSlash(userData);
236 				}
237 				saveGameFile = userData + saveGameFile;
238 			}
239 		}
240 	}
241 
242 	//if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Loading game from [%s]\n",saveGameFile.c_str());
243 	printf("Loading saved game from [%s]\n",saveGameFile.c_str());
244 
245 	Game::loadGame(saveGameFile,this,masterserverMode);
246 }
247 
initServer(WindowGl * window,bool autostart,bool openNetworkSlots,bool masterserverMode)248 void Program::initServer(WindowGl *window, bool autostart,bool openNetworkSlots,
249 		bool masterserverMode) {
250 	//this->masterserverMode = masterserverMode;
251 	init(window);
252 	MainMenu *mainMenu= new MainMenu(this);
253 	setState(mainMenu);
254 	mainMenu->setState(new MenuStateCustomGame(this, mainMenu, openNetworkSlots, pNewGame, autostart, NULL, masterserverMode));
255 }
256 
initServer(WindowGl * window,GameSettings * settings)257 void Program::initServer(WindowGl *window, GameSettings *settings) {
258 	init(window);
259 	MainMenu *mainMenu= new MainMenu(this);
260 	setState(mainMenu);
261 	mainMenu->setState(new MenuStateCustomGame(this, mainMenu, false, pNewGame, true, settings));
262 }
263 
initClient(WindowGl * window,const Ip & serverIp,int portNumber)264 void Program::initClient(WindowGl *window, const Ip &serverIp, int portNumber) {
265 	init(window);
266 	MainMenu *mainMenu= new MainMenu(this);
267 	setState(mainMenu);
268 	mainMenu->setState(new MenuStateJoinGame(this, mainMenu, true, serverIp,portNumber));
269 }
270 
initClientAutoFindHost(WindowGl * window)271 void Program::initClientAutoFindHost(WindowGl *window) {
272 	init(window);
273 	MainMenu *mainMenu= new MainMenu(this);
274 	setState(mainMenu);
275 	bool autoFindHost = true;
276 	mainMenu->setState(new MenuStateJoinGame(this, mainMenu, &autoFindHost));
277 
278 }
279 
initScenario(WindowGl * window,string autoloadScenarioName)280 void Program::initScenario(WindowGl *window, string autoloadScenarioName) {
281 	init(window);
282 	MainMenu *mainMenu= new MainMenu(this);
283 	setState(mainMenu);
284 	mainMenu->setState(new MenuStateScenario(this, mainMenu, false,
285 			Config::getInstance().getPathListForType(ptScenarios),autoloadScenarioName));
286 }
287 
~Program()288 Program::~Program(){
289 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
290 	delete programState;
291 	programState = NULL;
292 
293 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
294 
295 	Renderer::getInstance().end();
296 	CoreData &coreData= CoreData::getInstance();
297     coreData.cleanup();
298 
299 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
300 
301 	//restore video mode
302 	restoreDisplaySettings();
303 	singleton = NULL;
304 
305 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
306 
307 	if(soundThreadManager != NULL) {
308 		BaseThread::shutdownAndWait(soundThreadManager);
309 		delete soundThreadManager;
310 		soundThreadManager = NULL;
311 	}
312 
313 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
314 }
315 
restoreStateFromSystemError()316 void Program::restoreStateFromSystemError() {
317 	messageBoxIsSystemError = false;
318 	if(this->programStateOldSystemError == NULL) {
319 		setState(new Intro(this));
320 	}
321 	else {
322 		setState(this->programStateOldSystemError);
323 	}
324 }
325 
textInput(std::string text)326 bool Program::textInput(std::string text) {
327 	if(msgBox.getEnabled()) {
328 		return false;
329 	}
330 	//delegate event
331 	return programState->textInput(text);
332 }
333 
sdlKeyDown(SDL_KeyboardEvent key)334 bool Program::sdlKeyDown(SDL_KeyboardEvent key) {
335 	//delegate event
336 	return programState->sdlKeyDown(key);
337 }
338 
keyDown(SDL_KeyboardEvent key)339 void Program::keyDown(SDL_KeyboardEvent key) {
340 	if(msgBox.getEnabled()) {
341 		//SDL_keysym keystate = Window::getKeystate();
342 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
343 
344 		//if(key == vkEscape  || key == SDLK_ESCAPE ||
345 		//	((key == vkReturn || key == SDLK_RETURN || key == SDLK_KP_ENTER) && !(keystate.mod & (KMOD_LALT | KMOD_RALT)))) {
346 		if(isKeyPressed(SDLK_ESCAPE,key) == true ||	((isKeyPressed(SDLK_RETURN,key) == true) && !(key.keysym.mod & (KMOD_LALT | KMOD_RALT)))) {
347 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
348 
349 			//printf("---> keystate [%d]\n",keystate);
350 			msgBox.setEnabled(false);
351 			if(messageBoxIsSystemError == true) {
352 				restoreStateFromSystemError();
353 			}
354 		}
355 	}
356 	//delegate event
357 	programState->keyDown(key);
358 }
359 
keyUp(SDL_KeyboardEvent key)360 void Program::keyUp(SDL_KeyboardEvent key) {
361 	programState->keyUp(key);
362 }
363 
keyPress(SDL_KeyboardEvent c)364 void Program::keyPress(SDL_KeyboardEvent c) {
365 	programState->keyPress(c);
366 }
367 
mouseDownLeft(int x,int y)368 void Program::mouseDownLeft(int x, int y) {
369 	if(msgBox.getEnabled()) {
370 		int button= 0;
371 		if(msgBox.mouseClick(x, y, button)) {
372 			//if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
373 			//close message box
374 			msgBox.setEnabled(false);
375 			if(messageBoxIsSystemError == true) {
376 				restoreStateFromSystemError();
377 			}
378 		}
379 	}
380 }
381 
eventMouseMove(int x,int y,const MouseState * ms)382 void Program::eventMouseMove(int x, int y, const MouseState *ms) {
383 	if (msgBox.getEnabled()) {
384 		msgBox.mouseMove(x, y);
385 	}
386 }
387 
simpleTask(BaseThread * callingThread,void * userdata)388 void Program::simpleTask(BaseThread *callingThread,void *userdata) {
389 	loopWorker();
390 }
391 
loop()392 void Program::loop() {
393 	loopWorker();
394 }
395 
loopWorker()396 void Program::loopWorker() {
397 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ================================= MAIN LOOP START ================================= \n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
398 
399 	//Renderer &renderer= Renderer::getInstance();
400 	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && window) {
401 		MainWindow *mainWindow = dynamic_cast<MainWindow *>(window);
402 		if(mainWindow) {
403 			//mainWindow->render();
404 			if(mainWindow->getTriggerLanguageToggle()) {
405 				mainWindow->toggleLanguage(mainWindow->getTriggerLanguage());
406 			}
407 		}
408 	}
409 
410 	Chrono chronoPerformanceCounts;
411 
412 	bool showPerfStats = Config::getInstance().getBool("ShowPerfStats","false");
413 	Chrono chronoPerf;
414 	char perfBuf[8096]="";
415 	std::vector<string> perfList;
416 	if(showPerfStats) chronoPerf.start();
417 
418 	Chrono chronoLoop;
419 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chronoLoop.start();
420 
421 	Chrono chrono;
422 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start();
423 
424 	//render
425     assert(programState != NULL);
426 
427     if(this->programState->quitTriggered() == true) {
428     	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
429 
430     	Stats endStats = this->programState->quitAndToggleState();
431 
432     	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
433 
434     	Game::exitGameState(this, endStats);
435 
436     	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
437 
438     	return;
439     }
440     ProgramState *prevState = this->programState;
441 
442 	if(showPerfStats) {
443 		sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis());
444 		perfList.push_back(perfBuf);
445 	}
446 
447     assert(programState != NULL);
448 
449     chronoPerformanceCounts.start();
450 
451     programState->render();
452 
453     programState->addPerformanceCount(ProgramState::MAIN_PROGRAM_RENDER_KEY,chronoPerformanceCounts.getMillis());
454 
455 	if(showPerfStats) {
456 		sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis());
457 		perfList.push_back(perfBuf);
458 	}
459 
460     if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP RENDERING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
461     if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
462 
463 	//update camera
464     if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start();
465 
466     chronoPerformanceCounts.start();
467 
468     while(updateCameraTimer.isTime()) {
469 		programState->updateCamera();
470 	}
471 
472     programState->addPerformanceCount("programState->updateCamera()",chronoPerformanceCounts.getMillis());
473 
474 	if(showPerfStats) {
475 		sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis());
476 		perfList.push_back(perfBuf);
477 	}
478 
479 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP CAMERA UPDATING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
480 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
481 
482 	//update world
483 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start();
484 	int updateCount = 0;
485 	while(prevState == this->programState && updateTimer.isTime()) {
486 		Chrono chronoUpdateLoop;
487 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chronoUpdateLoop.start();
488 		if(showPerfStats) {
489 			sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount);
490 			perfList.push_back(perfBuf);
491 		}
492 
493 		GraphicComponent::update();
494 		programState->update();
495 
496 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] programState->update took msecs: %lld, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoUpdateLoop.getMillis(),updateCount);
497 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) chronoUpdateLoop.start();
498 
499 		if(showPerfStats) {
500 			sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount);
501 			perfList.push_back(perfBuf);
502 		}
503 
504 		if(prevState == this->programState) {
505 			chronoPerformanceCounts.start();
506 
507 			if(soundThreadManager == NULL || soundThreadManager->isThreadExecutionLagging()) {
508 				if(soundThreadManager != NULL) {
509 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] ERROR / WARNING soundThreadManager->isThreadExecutionLagging is TRUE\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
510 					SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s %d] ERROR / WARNING soundThreadManager->isThreadExecutionLagging is TRUE\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
511 				}
512 				SoundRenderer::getInstance().update();
513 				if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] SoundRenderer::getInstance().update() took msecs: %lld, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoUpdateLoop.getMillis(),updateCount);
514 				if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) chronoUpdateLoop.start();
515 			}
516 
517 			programState->addPerformanceCount("SoundRenderer::getInstance().update()",chronoPerformanceCounts.getMillis());
518 
519 			if(showPerfStats) {
520 				sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount);
521 				perfList.push_back(perfBuf);
522 			}
523 
524 			chronoPerformanceCounts.start();
525 
526 			NetworkManager::getInstance().update();
527 
528 			programState->addPerformanceCount("NetworkManager::getInstance().update()",chronoPerformanceCounts.getMillis());
529 
530 			if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] NetworkManager::getInstance().update() took msecs: %lld, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoUpdateLoop.getMillis(),updateCount);
531 			if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chronoUpdateLoop.getMillis() > 0) chronoUpdateLoop.start();
532 
533 			if(showPerfStats) {
534 				sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER " updateCount: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis(),updateCount);
535 				perfList.push_back(perfBuf);
536 			}
537 
538 		}
539 		updateCount++;
540 	}
541 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d AFTER programState->update took msecs: %lld ==============> MAIN LOOP BODY LOGIC, updateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),updateCount);
542 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
543 
544 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
545 
546 	if(showPerfStats) {
547 		sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis());
548 		perfList.push_back(perfBuf);
549 	}
550 
551 	if(prevState == this->programState) {
552 		//fps timer
553 		chronoPerformanceCounts.start();
554 
555 		chrono.start();
556 		while(fpsTimer.isTime()) {
557 			programState->tick();
558 		}
559 
560 		programState->addPerformanceCount("programState->tick()",chronoPerformanceCounts.getMillis());
561 
562 		if(showPerfStats) {
563 			sprintf(perfBuf,"In [%s::%s] Line: %d took msecs: " MG_I64_SPECIFIER "\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoPerf.getMillis());
564 			perfList.push_back(perfBuf);
565 		}
566 
567 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP TICKING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
568 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
569 
570 		//if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d programState->render took msecs: %lld ==============> MAIN LOOP TICKING\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
571 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
572 
573 	}
574 
575 	if(showPerfStats && chronoPerf.getMillis() >= 100) {
576 		for(unsigned int x = 0; x < perfList.size(); ++x) {
577 			printf("%s",perfList[x].c_str());
578 		}
579 	}
580 
581 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ------------------------------- MAIN LOOP END, stats: loop took msecs: %lld -------------------------------\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chronoLoop.getMillis());
582 }
583 
resize(SizeState sizeState)584 void Program::resize(SizeState sizeState){
585 
586 	switch(sizeState){
587 	case ssMinimized:
588 		//restoreVideoMode();
589 		break;
590 	case ssMaximized:
591 	case ssRestored:
592 		//setDisplaySettings();
593 		//renderer.reloadResources();
594 		break;
595 	}
596 }
597 
598 // ==================== misc ====================
599 
renderProgramMsgBox()600 void Program::renderProgramMsgBox() {
601 	Renderer &renderer= Renderer::getInstance();
602 	if(msgBox.getEnabled()) {
603 		renderer.renderMessageBox(&msgBox);
604 	}
605 
606 	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false && window) {
607 		MainWindow *mainWindow = dynamic_cast<MainWindow *>(window);
608 		if(mainWindow) {
609 			mainWindow->render();
610 		}
611 	}
612 
613 }
614 
setState(ProgramState * programStateNew,bool cleanupOldState)615 void Program::setState(ProgramState *programStateNew, bool cleanupOldState) {
616 	try {
617 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
618 
619 		this->programStateOldSystemError = this->programState;
620 		bool msgBoxEnabled = msgBox.getEnabled();
621 
622 		if(dynamic_cast<Game *>(programStateNew) != NULL) {
623 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
624 
625 			int X = 0;
626 			int Y = 0;
627 			SDL_GetMouseState(&X,&Y);
628 			programStateNew->setStartXY(X,Y);
629 			Logger::getInstance().setProgress(0);
630 			Logger::getInstance().setState("");
631 
632 
633 			SDL_PumpEvents();
634 
635 			showCursor(true);
636 			SDL_PumpEvents();
637 			sleep(0);
638 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
639 		}
640 
641 		if(cleanupOldState == true) {
642 			if(this->programState != programStateNew) {
643 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
644 
645 				this->programStateOldSystemError = NULL;
646 				delete this->programState;
647 
648 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
649 
650 				this->programState = NULL;
651 
652 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
653 			}
654 		}
655 
656 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
657 
658 		//mesage box
659 		Lang &lang= Lang::getInstance();
660 		msgBox.init(lang.getString("Ok"));
661 		msgBox.setEnabled(msgBoxEnabled);
662 
663 		fpsTimer.init(1, maxTimes);
664 		updateTimer.init(GameConstants::updateFps, maxTimes);
665 		updateCameraTimer.init(GameConstants::cameraFps, maxTimes);
666 
667 		this->programState= programStateNew;
668 		assert(programStateNew != NULL);
669 		if(programStateNew == NULL) {
670 			throw megaglest_runtime_error("programStateNew == NULL");
671 		}
672 		programStateNew->load();
673 
674 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
675 
676 		programStateNew->init();
677 
678 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
679 
680 		updateTimer.reset();
681 		updateCameraTimer.reset();
682 		fpsTimer.reset();
683 
684 		Config &config = Config::getInstance();
685 		if(dynamic_cast<Intro *>(programStateNew) != NULL && msgBoxEnabled == true) {
686 			showCursor(true);
687 		} else {
688 			showCursor(config.getBool("No2DMouseRendering","false"));
689 		}
690 
691 		this->programStateOldSystemError = NULL;
692 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
693 	}
694 	catch(megaglest_runtime_error& e) {
695 		//printf("3333333 ex.wantStackTrace() = %d\n",e.wantStackTrace());
696 		char szBuf[8096]="";
697 		snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
698 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
699 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf);
700 		//abort();
701 		//printf("44444444a ex.wantStackTrace() = %d\n",e.wantStackTrace());
702 
703 		messageBoxIsSystemError = true;
704 		string errorMsg = e.what();
705 
706 		if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) {
707 			if(dynamic_cast<Game *>(programStateNew) != NULL) {
708 				try {
709 					Game *game = dynamic_cast<Game *>(programStateNew);
710 					Renderer &renderer= Renderer::getInstance();
711 					game->setQuitPendingIndicator();// by this the world is no more updated
712 					renderer.initGame(game,game->getGameCameraPtr());
713 				}
714 				catch(megaglest_runtime_error& ex2) {
715 					errorMsg += "\n" + string(ex2.what());
716 				}
717 			}
718 		}
719 
720 		//printf("44444444b ex.wantStackTrace() = %d\n",e.wantStackTrace());
721 		this->showMessage(errorMsg.c_str());
722 		//setState(new Intro(this));
723 	}
724 	catch(const exception &e){
725 		char szBuf[8096]="";
726 		snprintf(szBuf,8096,"In [%s::%s Line: %d]\nError [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
727 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
728 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,szBuf);
729 		//abort();
730 
731 		messageBoxIsSystemError = true;
732 
733 		if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false) {
734 			if(dynamic_cast<Game *>(programStateNew) != NULL) {
735 				Game *game = dynamic_cast<Game *>(programStateNew);
736 				Renderer &renderer= Renderer::getInstance();
737 				renderer.initGame(game,game->getGameCameraPtr());
738 			}
739 		}
740 
741 		this->showMessage(e.what());
742 		//setState(new Intro(this));
743 	}
744 }
745 
exit()746 void Program::exit() {
747 	window->destroy();
748 }
749 
750 // ==================== PRIVATE ====================
751 
initResolution()752 void Program::initResolution() {
753 	const Metrics &metrics = Metrics::getInstance();
754 	if(window->getScreenWidth() != metrics.getScreenW() ||
755 		window->getScreenHeight() != metrics.getScreenH()) {
756 
757 		int oldW = metrics.getScreenW();
758 		int oldH = metrics.getScreenH();
759 
760 		Config &config= Config::getInstance();
761 		config.setInt("ScreenWidth",window->getScreenWidth(),true);
762 		config.setInt("ScreenHeight",window->getScreenHeight(),true);
763 
764 		metrics.reload(window->getScreenWidth(), window->getScreenHeight());
765 		printf("MainWindow forced change of resolution to desktop values (%d x %d) instead of (%d x %d)\n",metrics.getScreenW(), metrics.getScreenH(),oldW,oldH);
766 	}
767 }
768 
init(WindowGl * window,bool initSound,bool toggleFullScreen)769 void Program::init(WindowGl *window, bool initSound, bool toggleFullScreen){
770 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
771 
772 	this->window= window;
773 	Config &config= Config::getInstance();
774 
775 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
776 
777     //set video mode
778 	if(toggleFullScreen == false) {
779 		setDisplaySettings();
780 	}
781 
782 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
783 
784 	//window
785 	//window->setText("MegaGlest");
786 	window->setStyle(config.getBool("Windowed")? wsWindowedFixed: wsFullscreen);
787 	window->setPos(0, 0);
788 	window->setSize(config.getInt("ScreenWidth"), config.getInt("ScreenHeight"));
789 	window->create();
790 
791 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
792 
793 	//timers
794 	fpsTimer.init(1, maxTimes);
795 	updateTimer.init(GameConstants::updateFps, maxTimes);
796 	updateCameraTimer.init(GameConstants::cameraFps, maxTimes);
797 
798 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
799 
800     //log start
801 	Logger &logger= Logger::getInstance();
802 	string logFile = "glest.log";
803     if(getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) != "") {
804         logFile = getGameReadWritePath(GameConstants::path_logs_CacheLookupKey) + logFile;
805     }
806     else {
807         string userData = config.getString("UserData_Root","");
808         if(userData != "") {
809         	endPathWithSlash(userData);
810         }
811 
812         logFile = userData + logFile;
813     }
814 	logger.setFile(logFile);
815 	logger.clear();
816 
817 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
818 
819 	//lang
820 	//Lang &lang= Lang::getInstance();
821 	Lang::getInstance();
822 
823 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
824 
825 	//render
826 	Renderer &renderer= Renderer::getInstance();
827 
828 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
829 
830 	window->initGl(config.getInt("ColorBits"),
831 			       config.getInt("DepthBits"),
832 			       config.getInt("StencilBits"),
833 			       config.getBool("HardwareAcceleration","false"),
834 			       config.getBool("FullScreenAntiAliasing","false"),
835 			       config.getFloat("GammaValue","0.0"));
836 	window->setText(config.getString("WindowTitle","MegaGlest"));
837 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
838 
839 	window->makeCurrentGl();
840 	initResolution();
841 
842 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
843 
844 	//coreData, needs renderer, but must load before renderer init
845 	CoreData &coreData= CoreData::getInstance();
846     coreData.load();
847 
848     if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
849 
850 	//init renderer (load global textures)
851     tryingRendererInit = true;
852 	renderer.init();
853 	tryingRendererInit = false;
854 	rendererInitOk = true;
855 
856 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
857 
858 	//sound
859 	if(initSound == true && toggleFullScreen == false) {
860         SoundRenderer &soundRenderer= SoundRenderer::getInstance();
861         bool initOk = soundRenderer.init(window);
862 
863         if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] initOk = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,initOk);
864 
865         // Test sound system failed
866         //initOk = false;
867         // END
868 
869         if(initOk == false) {
870         	string sError = "Sound System could not be initialized!";
871         	this->showMessage(sError.c_str());
872         }
873 
874 		// Run sound streaming in a background thread if enabled
875         if(SoundRenderer::getInstance().runningThreaded() == true) {
876 			if(BaseThread::shutdownAndWait(soundThreadManager) == true) {
877 				delete soundThreadManager;
878 			}
879 			static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__);
880 			soundThreadManager = new SimpleTaskThread(&SoundRenderer::getInstance(),0,SOUND_THREAD_UPDATE_MILLISECONDS);
881 			soundThreadManager->setUniqueID(mutexOwnerId);
882 			soundThreadManager->start();
883 		}
884 	}
885 
886 	NetworkInterface::setAllowGameDataSynchCheck(Config::getInstance().getBool("AllowGameDataSynchCheck","false"));
887 	NetworkInterface::setAllowDownloadDataSynch(Config::getInstance().getBool("AllowDownloadDataSynch","false"));
888 
889 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
890 }
891 
reloadUI()892 void Program::reloadUI() {
893 	if(programState) {
894 		programState->reloadUI();
895 	}
896 }
897 
setDisplaySettings()898 void Program::setDisplaySettings(){
899 
900 	Config &config= Config::getInstance();
901 
902 	if(!config.getBool("Windowed")) {
903 
904 		//int freq= config.getInt("RefreshFrequency");
905 		int colorBits= config.getInt("ColorBits");
906 		int screenWidth= config.getInt("ScreenWidth");
907 		int screenHeight= config.getInt("ScreenHeight");
908 
909         if(config.getBool("AutoMaxFullScreen","false") == true) {
910             getFullscreenVideoInfo(colorBits,screenWidth,screenHeight,!config.getBool("Windowed"));
911             config.setInt("ColorBits",colorBits);
912             config.setInt("ScreenWidth",screenWidth);
913             config.setInt("ScreenHeight",screenHeight);
914         }
915 	}
916 	changeVideoModeFullScreen(!config.getBool("Windowed"));
917 }
918 
restoreDisplaySettings()919 void Program::restoreDisplaySettings(){
920 	Config &config= Config::getInstance();
921 
922 	if(!config.getBool("Windowed")){
923 		restoreVideoMode(this->getWindow()->getSDLWindow());
924 	}
925 }
926 
isMessageShowing()927 bool Program::isMessageShowing() {
928     return msgBox.getEnabled();
929 }
930 
showMessage(const char * msg)931 void Program::showMessage(const char *msg) {
932 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s %d] msg [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,msg);
933 
934 	msgBox.setText(msg);
935 	msgBox.setEnabled(true);
936 
937 	if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) {
938 		printf("Message:\n%s\n",msg);
939 
940 		if(messageBoxIsSystemError == true) {
941 			messageBoxIsSystemError = false;
942 			//setState(new Intro(this));
943 			initServer(window,false,true,true);
944 		}
945 	}
946 }
947 
stopSoundSystem()948 void Program::stopSoundSystem() {
949 	if(soundThreadManager != NULL) {
950 		BaseThread::shutdownAndWait(soundThreadManager);
951 		delete soundThreadManager;
952 		soundThreadManager = NULL;
953 	}
954 }
955 
startSoundSystem()956 void Program::startSoundSystem() {
957 	stopSoundSystem();
958 	if(SoundRenderer::getInstance().runningThreaded() == true) {
959 		static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__);
960 		soundThreadManager = new SimpleTaskThread(&SoundRenderer::getInstance(),0,SOUND_THREAD_UPDATE_MILLISECONDS);
961 		soundThreadManager->setUniqueID(mutexOwnerId);
962 		soundThreadManager->start();
963 	}
964 }
965 
resetSoundSystem()966 void Program::resetSoundSystem() {
967 	startSoundSystem();
968 }
969 
reInitGl()970 void Program::reInitGl() {
971 	if(window != NULL) {
972 		Config &config= Config::getInstance();
973 		window->initGl(config.getInt("ColorBits"),
974 				       config.getInt("DepthBits"),
975 				       config.getInt("StencilBits"),
976 				       config.getBool("HardwareAcceleration","false"),
977 				       config.getBool("FullScreenAntiAliasing","false"),
978 				       config.getFloat("GammaValue","0.0"));
979 		window->setText(config.getString("WindowTitle","MegaGlest"));
980 		initResolution();
981 	}
982 }
983 
consoleAddLine(string line)984 void Program::consoleAddLine(string line) {
985 	if(programState != NULL) {
986 		programState->consoleAddLine(line);
987 	}
988 }
989 
getSoundThreadManager(bool takeOwnership)990 SimpleTaskThread * Program::getSoundThreadManager(bool takeOwnership) {
991 	SimpleTaskThread *result = soundThreadManager;
992 	if(takeOwnership) {
993 		soundThreadManager = NULL;
994 	}
995 	return result;
996 }
997 
998 }}//end namespace
999