1 //	This file is part of Glest (www.glest.org)
2 //
3 //	Copyright (C) 2001-2005 Martiño Figueroa
4 //
5 //	You can redistribute this code and/or modify it under
6 //	the terms of the GNU General Public License as published
7 //	by the Free Software Foundation; either version 2 of the
8 //	License, or (at your option) any later version
9 // ==============================================================
10 #include "menu_state_custom_game.h"
11 
12 #include "renderer.h"
13 #include "sound_renderer.h"
14 #include "core_data.h"
15 #include "config.h"
16 #include "menu_state_new_game.h"
17 #include "menu_state_masterserver.h"
18 #include "menu_state_join_game.h"
19 #include "metrics.h"
20 #include "network_manager.h"
21 #include "network_message.h"
22 #include "client_interface.h"
23 #include "conversion.h"
24 #include "socket.h"
25 #include "game.h"
26 #include "util.h"
27 #include <algorithm>
28 #include <time.h>
29 #include <curl/curl.h>
30 #include "cache_manager.h"
31 #include <iterator>
32 #include "map_preview.h"
33 #include "gen_uuid.h"
34 #include "leak_dumper.h"
35 
36 namespace Glest{ namespace Game{
37 
38 using namespace ::Shared::Util;
39 
40 const int MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS  = 15;
41 const int MASTERSERVER_BROADCAST_PUBLISH_SECONDS   			= 6;
42 const int BROADCAST_MAP_DELAY_SECONDS 						= 5;
43 const int BROADCAST_SETTINGS_SECONDS  						= 4;
44 static const char *SAVED_GAME_FILENAME 				= "lastCustomGameSettings.mgg";
45 static const char *DEFAULT_GAME_FILENAME 			= "data/defaultGameSetup.mgg";
46 static const char *DEFAULT_NETWORKGAME_FILENAME 	= "data/defaultNetworkGameSetup.mgg";
47 
48 const int mapPreviewTexture_X = 5;
49 const int mapPreviewTexture_Y = 185;
50 const int mapPreviewTexture_W = 150;
51 const int mapPreviewTexture_H = 150;
52 
53 struct FormatString {
operator ()Glest::Game::FormatString54 	void operator()(string &s) {
55 		s = formatString(s);
56 	}
57 };
58 
59 // =====================================================
60 // 	class MenuStateCustomGame
61 // =====================================================
62 enum THREAD_NOTIFIER_TYPE {
63 	tnt_MASTERSERVER = 1,
64 	tnt_CLIENTS = 2
65 };
66 
MenuStateCustomGame(Program * program,MainMenu * mainMenu,bool openNetworkSlots,ParentMenuState parentMenuState,bool autostart,GameSettings * settings,bool masterserverMode,string autoloadScenarioName)67 MenuStateCustomGame::MenuStateCustomGame(Program *program, MainMenu *mainMenu,
68 		bool openNetworkSlots,ParentMenuState parentMenuState, bool autostart,
69 		GameSettings *settings, bool masterserverMode,
70 		string autoloadScenarioName) :
71 		MenuState(program, mainMenu, "new-game") {
72 	try {
73 
74 	this->headlessServerMode = masterserverMode;
75 	if(this->headlessServerMode == true) {
76 		printf("Waiting for players to join and start a game...\n");
77 	}
78 
79 	this->gameUUID = getUUIDAsString();
80 
81 	this->zoomedMap=false;
82 	this->render_mapPreviewTexture_X = mapPreviewTexture_X;
83 	this->render_mapPreviewTexture_Y = mapPreviewTexture_Y;
84 	this->render_mapPreviewTexture_W = mapPreviewTexture_W;
85 	this->render_mapPreviewTexture_H = mapPreviewTexture_H;
86 
87 	this->lastMasterServerSettingsUpdateCount = 0;
88 	this->masterserverModeMinimalResources = true;
89 	this->parentMenuState=parentMenuState;
90 	this->factionVideo = NULL;
91 	factionVideoSwitchedOffVolume=false;
92 
93 	//printf("this->masterserverMode = %d [%d]\n",this->masterserverMode,masterserverMode);
94 
95 	forceWaitForShutdown = true;
96 	this->autostart = autostart;
97 	this->autoStartSettings = settings;
98 
99 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] autostart = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,autostart);
100 
101 	containerName = "CustomGame";
102 	activeInputLabel=NULL;
103 	showGeneralError = false;
104 	generalErrorToShow = "---";
105 	currentFactionLogo = "";
106 	factionTexture=NULL;
107 	currentTechName_factionPreview="";
108 	currentFactionName_factionPreview="";
109 	mapPreviewTexture=NULL;
110 	hasCheckedForUPNP = false;
111 	needToPublishDelayed=false;
112 	mapPublishingDelayTimer=time(NULL);
113 	headlessHasConnectedPlayer=false;
114 
115     lastCheckedCRCTilesetName					= "";
116     lastCheckedCRCTechtreeName					= "";
117     lastCheckedCRCMapName						= "";
118 
119     last_Forced_CheckedCRCTilesetName			= "";
120     last_Forced_CheckedCRCTechtreeName			= "";
121     last_Forced_CheckedCRCMapName				= "";
122 
123     lastCheckedCRCTilesetValue					= 0;
124     lastCheckedCRCTechtreeValue					= 0;
125     lastCheckedCRCMapValue						= 0;
126 
127 	publishToMasterserverThread = NULL;
128 	publishToClientsThread = NULL;
129 
130 	Lang &lang= Lang::getInstance();
131 	NetworkManager &networkManager= NetworkManager::getInstance();
132     Config &config = Config::getInstance();
133     defaultPlayerName = config.getString("NetPlayerName",Socket::getHostName().c_str());
134     enableFactionTexturePreview = config.getBool("FactionPreview","true");
135     enableMapPreview = config.getBool("MapPreview","true");
136 
137     showFullConsole=false;
138 
139 	enableScenarioTexturePreview = Config::getInstance().getBool("EnableScenarioTexturePreview","true");
140 	scenarioLogoTexture=NULL;
141 	previewLoadDelayTimer=time(NULL);
142 	needToLoadTextures=true;
143 	this->autoloadScenarioName = autoloadScenarioName;
144 	this->dirList = Config::getInstance().getPathListForType(ptScenarios);
145 
146     mainMessageBox.registerGraphicComponent(containerName,"mainMessageBox");
147 	mainMessageBox.init(lang.getString("Ok"),500,300);
148 	mainMessageBox.setEnabled(false);
149 	mainMessageBoxState=0;
150 
151 	//initialize network interface
152 	NetworkManager::getInstance().end();
153 
154 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
155 
156 	serverInitError = false;
157 	try {
158 		networkManager.init(nrServer,openNetworkSlots);
159 	}
160 	catch(const std::exception &ex) {
161 		serverInitError = true;
162 		char szBuf[8096]="";
163 		snprintf(szBuf,8096,"In [%s::%s %d]\nNetwork init error:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
164 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
165 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
166 
167 		showGeneralError=true;
168 		generalErrorToShow = szBuf;
169 	}
170 
171 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
172 
173 	needToSetChangedGameSettings = false;
174 	needToRepublishToMasterserver = false;
175 	needToBroadcastServerSettings = false;
176 	lastGameSettingsreceivedCount = -1;
177 	showMasterserverError = false;
178 	tMasterserverErrorElapsed = 0;
179 	masterServererErrorToShow = "---";
180 	lastSetChangedGameSettings  = 0;
181 	lastMasterserverPublishing 	= 0;
182 	lastNetworkPing				= 0;
183 	soundConnectionCount=0;
184 
185 	techTree.reset(new TechTree(config.getPathListForType(ptTechs)));
186 
187 	int labelOffset=23;
188 	int setupPos=605;
189 	int mapHeadPos=330;
190 	int mapPos=mapHeadPos-labelOffset;
191 	int aHeadPos=240;
192 	int aPos=aHeadPos-labelOffset;
193 	int networkHeadPos=700;
194 	int networkPos=networkHeadPos-labelOffset;
195 	int xoffset=10;
196 
197 	//create
198 	int buttonx=165;
199 	int buttony=180;
200 
201     // player status
202 	listBoxPlayerStatus.registerGraphicComponent(containerName,"listBoxPlayerStatus");
203 	listBoxPlayerStatus.init(buttonx, buttony, 165);
204 	vector<string> playerStatuses;
205 	playerStatuses.push_back(lang.getString("PlayerStatusSetup"));
206 	playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack"));
207 	playerStatuses.push_back(lang.getString("PlayerStatusReady"));
208 	listBoxPlayerStatus.setItems(playerStatuses);
209 	listBoxPlayerStatus.setSelectedItemIndex(2,true);
210 	listBoxPlayerStatus.setTextColor(Vec3f(0.0f,1.0f,0.0f));
211 	listBoxPlayerStatus.setLighted(false);
212 	listBoxPlayerStatus.setVisible(true);
213 	buttonx+=180;
214 
215 	buttonReturn.registerGraphicComponent(containerName,"buttonReturn");
216 	buttonReturn.init(buttonx, buttony, 125);
217 	buttonx+=132;
218 
219 	buttonRestoreLastSettings.registerGraphicComponent(containerName,"buttonRestoreLastSettings");
220 	buttonRestoreLastSettings.init(buttonx, buttony, 240);
221 	buttonx+=247;
222 
223 	buttonPlayNow.registerGraphicComponent(containerName,"buttonPlayNow");
224 	buttonPlayNow.init(buttonx, buttony, 125);
225 
226 	labelLocalGameVersion.registerGraphicComponent(containerName,"labelLocalGameVersion");
227 	labelLocalGameVersion.init(10, networkHeadPos+labelOffset);
228 
229 	labelLocalIP.registerGraphicComponent(containerName,"labelLocalIP");
230 	labelLocalIP.init(360, networkHeadPos+labelOffset);
231 
232 	string ipText = "none";
233 	std::vector<std::string> ipList = Socket::getLocalIPAddressList();
234 	if(ipList.empty() == false) {
235 		ipText = "";
236 		for(int idx = 0; idx < (int)ipList.size(); idx++) {
237 			string ip = ipList[idx];
238 			if(ipText != "") {
239 				ipText += ", ";
240 			}
241 			ipText += ip;
242 		}
243 	}
244 	string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str());
245 	string externalPort=config.getString("PortExternal", serverPort.c_str());
246 	labelLocalIP.setText(lang.getString("LanIP") + ipText + "  ( "+serverPort+" / "+externalPort+" )");
247 	ServerSocket::setExternalPort(strToInt(externalPort));
248 
249 	if(EndsWith(glestVersionString, "-dev") == false){
250 		labelLocalGameVersion.setText(glestVersionString);
251 	}
252 	else {
253 		//labelLocalGameVersion.setText(glestVersionString + " [" + getCompileDateTime() + ", " + getGITRevisionString() + "]");
254 		labelLocalGameVersion.setText(glestVersionString + " [" + getGITRevisionString() + "]");
255 	}
256 
257 	xoffset=65;
258 	// MapFilter
259 	labelMapFilter.registerGraphicComponent(containerName,"labelMapFilter");
260 	labelMapFilter.init(xoffset+325, mapHeadPos);
261 	labelMapFilter.setText(lang.getString("MapFilter"));
262 
263 	listBoxMapFilter.registerGraphicComponent(containerName,"listBoxMapFilter");
264 	listBoxMapFilter.init(xoffset+325, mapPos, 80);
265 	listBoxMapFilter.pushBackItem("-");
266 	for(int i=1; i<GameConstants::maxPlayers+1; ++i){
267 		listBoxMapFilter.pushBackItem(intToStr(i));
268 	}
269 	listBoxMapFilter.setSelectedItemIndex(0);
270 
271 	// Map
272 	labelMap.registerGraphicComponent(containerName,"labelMap");
273 	labelMap.init(xoffset+100, mapHeadPos);
274 	labelMap.setText(lang.getString("Map"));
275 
276 	//map listBox
277 	listBoxMap.registerGraphicComponent(containerName,"listBoxMap");
278 	listBoxMap.init(xoffset+100, mapPos, 220);
279 	// put them all in a set, to weed out duplicates (gbm & mgm with same name)
280 	// will also ensure they are alphabetically listed (rather than how the OS provides them)
281 	int initialMapSelection = setupMapList("");
282     listBoxMap.setItems(formattedPlayerSortedMaps[0]);
283     listBoxMap.setSelectedItemIndex(initialMapSelection);
284 
285     labelMapInfo.registerGraphicComponent(containerName,"labelMapInfo");
286 	labelMapInfo.init(xoffset+100, mapPos-labelOffset-10, 200, 40);
287 
288     labelTileset.registerGraphicComponent(containerName,"labelTileset");
289 	labelTileset.init(xoffset+500, mapHeadPos);
290 	labelTileset.setText(lang.getString("Tileset"));
291 
292 	//tileset listBox
293 	listBoxTileset.registerGraphicComponent(containerName,"listBoxTileset");
294 	listBoxTileset.init(xoffset+500, mapPos, 160);
295 
296 	setupTilesetList("");
297 	Chrono seed(true);
298 	srand((unsigned int)seed.getCurTicks());
299 
300 	listBoxTileset.setSelectedItemIndex(rand() % listBoxTileset.getItemCount());
301 
302     //tech Tree listBox
303     int initialTechSelection = setupTechList("", true);
304 
305 	listBoxTechTree.registerGraphicComponent(containerName,"listBoxTechTree");
306 	listBoxTechTree.init(xoffset+700, mapPos, 180);
307 	if(listBoxTechTree.getItemCount() > 0) {
308 		listBoxTechTree.setSelectedItemIndex(initialTechSelection);
309 	}
310 
311     labelTechTree.registerGraphicComponent(containerName,"labelTechTree");
312 	labelTechTree.init(xoffset+700, mapHeadPos);
313 	labelTechTree.setText(lang.getString("TechTree"));
314 
315 	// fog - o - war
316 	// @350 ? 300 ?
317 	labelFogOfWar.registerGraphicComponent(containerName,"labelFogOfWar");
318 	labelFogOfWar.init(xoffset+100, aHeadPos, 165);
319 	labelFogOfWar.setText(lang.getString("FogOfWar"));
320 
321 	listBoxFogOfWar.registerGraphicComponent(containerName,"listBoxFogOfWar");
322 	listBoxFogOfWar.init(xoffset+100, aPos, 165);
323 	listBoxFogOfWar.pushBackItem(lang.getString("Enabled"));
324 	listBoxFogOfWar.pushBackItem(lang.getString("Explored"));
325 	listBoxFogOfWar.pushBackItem(lang.getString("Disabled"));
326 	listBoxFogOfWar.setSelectedItemIndex(0);
327 
328 	// Allow Observers
329 	labelAllowObservers.registerGraphicComponent(containerName,"labelAllowObservers");
330 	labelAllowObservers.init(xoffset+325, aHeadPos, 80);
331 	labelAllowObservers.setText(lang.getString("AllowObservers"));
332 
333 	checkBoxAllowObservers.registerGraphicComponent(containerName,"checkBoxAllowObservers");
334 	checkBoxAllowObservers.init(xoffset+325, aPos);
335 	checkBoxAllowObservers.setValue(false);
336 
337 	vector<string> rMultiplier;
338 	for(int i=0; i<45; ++i){
339 		rMultiplier.push_back(floatToStr(0.5f+0.1f*i,1));
340 	}
341 
342 	labelFallbackCpuMultiplier.registerGraphicComponent(containerName,"labelFallbackCpuMultiplier");
343 	labelFallbackCpuMultiplier.init(xoffset+500, aHeadPos, 80);
344 	labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier"));
345 
346 	listBoxFallbackCpuMultiplier.registerGraphicComponent(containerName,"listBoxFallbackCpuMultiplier");
347 	listBoxFallbackCpuMultiplier.init(xoffset+500, aPos, 80);
348 	listBoxFallbackCpuMultiplier.setItems(rMultiplier);
349 	listBoxFallbackCpuMultiplier.setSelectedItem("1.0");
350 
351 	// Allow Switch Team Mode
352 	labelEnableSwitchTeamMode.registerGraphicComponent(containerName,"labelEnableSwitchTeamMode");
353 	labelEnableSwitchTeamMode.init(xoffset+325, aHeadPos+45, 80);
354 	labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode"));
355 
356 	checkBoxEnableSwitchTeamMode.registerGraphicComponent(containerName,"checkBoxEnableSwitchTeamMode");
357 	checkBoxEnableSwitchTeamMode.init(xoffset+325, aPos+45);
358 	checkBoxEnableSwitchTeamMode.setValue(false);
359 
360 	labelAISwitchTeamAcceptPercent.registerGraphicComponent(containerName,"labelAISwitchTeamAcceptPercent");
361 	labelAISwitchTeamAcceptPercent.init(xoffset+500, aHeadPos+45, 80);
362 	labelAISwitchTeamAcceptPercent.setText(lang.getString("AISwitchTeamAcceptPercent"));
363 
364 	listBoxAISwitchTeamAcceptPercent.registerGraphicComponent(containerName,"listBoxAISwitchTeamAcceptPercent");
365 	listBoxAISwitchTeamAcceptPercent.init(xoffset+500, aPos+45, 80);
366 	for(int i = 0; i <= 100; i = i + 10) {
367 		listBoxAISwitchTeamAcceptPercent.pushBackItem(intToStr(i));
368 	}
369 	listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(30));
370 
371 	labelAllowNativeLanguageTechtree.registerGraphicComponent(containerName,"labelAllowNativeLanguageTechtree");
372 	labelAllowNativeLanguageTechtree.init(xoffset+700, aHeadPos+45);
373 	labelAllowNativeLanguageTechtree.setText(lang.getString("AllowNativeLanguageTechtree"));
374 
375 	checkBoxAllowNativeLanguageTechtree.registerGraphicComponent(containerName,"checkBoxAllowNativeLanguageTechtree");
376 	checkBoxAllowNativeLanguageTechtree.init(xoffset+700, aPos+45);
377 	checkBoxAllowNativeLanguageTechtree.setValue(false);
378 
379 	// Network Scenario
380 	int scenarioX=xoffset+700;
381 	int scenarioY=aPos;
382     labelScenario.registerGraphicComponent(containerName,"labelScenario");
383     labelScenario.init(scenarioX, aHeadPos);
384     labelScenario.setText(lang.getString("Scenario"));
385 	listBoxScenario.registerGraphicComponent(containerName,"listBoxScenario");
386     listBoxScenario.init(scenarioX+30, scenarioY,190);
387     checkBoxScenario.registerGraphicComponent(containerName,"checkBoxScenario");
388     checkBoxScenario.init(scenarioX, scenarioY);
389     checkBoxScenario.setValue(false);
390 
391     //scenario listbox
392     vector<string> resultsScenarios;
393 	findDirs(dirList, resultsScenarios);
394 	// Filter out only scenarios with no network slots
395 	for(int i= 0; i < (int)resultsScenarios.size(); ++i) {
396 		string scenario = resultsScenarios[i];
397 		string file = Scenario::getScenarioPath(dirList, scenario);
398 
399 		try {
400 			if(file != "") {
401 				bool isTutorial = Scenario::isGameTutorial(file);
402 				Scenario::loadScenarioInfo(file, &scenarioInfo, isTutorial);
403 
404 				bool isNetworkScenario = false;
405 				for(unsigned int j = 0; isNetworkScenario == false && j < (unsigned int)GameConstants::maxPlayers; ++j) {
406 					if(scenarioInfo.factionControls[j] == ctNetwork) {
407 						isNetworkScenario = true;
408 					}
409 				}
410 				if(isNetworkScenario == true) {
411 					scenarioFiles.push_back(scenario);
412 				}
413 			}
414 		}
415 		catch(const std::exception &ex) {
416 		    char szBuf[8096]="";
417 		    snprintf(szBuf,8096,"In [%s::%s %d]\nError loading scenario [%s]:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,scenario.c_str(),ex.what());
418 		    SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
419 		    if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
420 
421 		    showGeneralError=true;
422 			generalErrorToShow = szBuf;
423 		    //throw megaglest_runtime_error(szBuf);
424 		}
425 	}
426 	resultsScenarios.clear();
427 	for(int i = 0; i < (int)scenarioFiles.size(); ++i) {
428 		resultsScenarios.push_back(formatString(scenarioFiles[i]));
429 	}
430     listBoxScenario.setItems(resultsScenarios);
431     if(resultsScenarios.empty() == true) {
432     	checkBoxScenario.setEnabled(false);
433     }
434 	// Advanced Options
435 	labelAdvanced.registerGraphicComponent(containerName,"labelAdvanced");
436 	labelAdvanced.init(scenarioX, 80, 80);
437 	labelAdvanced.setText(lang.getString("AdvancedGameOptions"));
438 
439 	checkBoxAdvanced.registerGraphicComponent(containerName,"checkBoxAdvanced");
440 	checkBoxAdvanced.init(scenarioX, 80-labelOffset);
441 	checkBoxAdvanced.setValue(false);
442 
443 	// network things
444 	// PublishServer
445 	xoffset=90;
446 
447 	labelPublishServer.registerGraphicComponent(containerName,"labelPublishServer");
448 	labelPublishServer.init(20, networkHeadPos, 100);
449 	labelPublishServer.setText(lang.getString("PublishServer"));
450 
451 	checkBoxPublishServer.registerGraphicComponent(containerName,"checkBoxPublishServer");
452 	checkBoxPublishServer.init(20, networkPos);
453 
454 	checkBoxPublishServer.setValue(false);
455 	if((this->headlessServerMode == true ||
456 		(openNetworkSlots == true && parentMenuState != pLanGame)) &&
457 			GlobalStaticFlags::isFlagSet(gsft_lan_mode) == false) {
458 		checkBoxPublishServer.setValue(true);
459 	}
460 
461 	labelGameName.registerGraphicComponent(containerName,"labelGameName");
462 	labelGameName.init(20+checkBoxPublishServer.getW()+5, networkPos,200);
463 	labelGameName.setFont(CoreData::getInstance().getMenuFontBig());
464 	labelGameName.setFont3D(CoreData::getInstance().getMenuFontBig3D());
465 	labelGameName.setText(createGameName());
466 	labelGameName.setEditable(true);
467 	labelGameName.setMaxEditWidth(20);
468 	labelGameName.setMaxEditRenderWidth(200);
469 
470 
471 	bool allowInProgressJoin = Config::getInstance().getBool("EnableJoinInProgressGame","false");
472 	labelAllowInGameJoinPlayer.registerGraphicComponent(containerName,"labelAllowInGameJoinPlayer");
473 	labelAllowInGameJoinPlayer.init(50, networkPos - 30, 80);
474 	labelAllowInGameJoinPlayer.setText(lang.getString("AllowInGameJoinPlayer"));
475 	labelAllowInGameJoinPlayer.setVisible(allowInProgressJoin);
476 
477 	checkBoxAllowInGameJoinPlayer.registerGraphicComponent(containerName,"checkBoxAllowInGameJoinPlayer");
478 	checkBoxAllowInGameJoinPlayer.init(20, networkPos - 30);
479 	checkBoxAllowInGameJoinPlayer.setValue(false);
480 	checkBoxAllowInGameJoinPlayer.setVisible(allowInProgressJoin);
481 
482 
483 	labelAllowTeamUnitSharing.registerGraphicComponent(containerName,"labelAllowTeamUnitSharing");
484 	labelAllowTeamUnitSharing.init(xoffset+410, 670, 80);
485 	labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing"));
486 	labelAllowTeamUnitSharing.setVisible(true);
487 
488 	checkBoxAllowTeamUnitSharing.registerGraphicComponent(containerName,"checkBoxAllowTeamUnitSharing");
489 	checkBoxAllowTeamUnitSharing.init(xoffset+612, 670);
490 	checkBoxAllowTeamUnitSharing.setValue(false);
491 	checkBoxAllowTeamUnitSharing.setVisible(true);
492 
493 	labelAllowTeamResourceSharing.registerGraphicComponent(containerName,"labelAllowTeamResourceSharing");
494 	labelAllowTeamResourceSharing.init(xoffset+410, 640, 80);
495 	labelAllowTeamResourceSharing.setText(lang.getString("AllowTeamResourceSharing"));
496 	labelAllowTeamResourceSharing.setVisible(true);
497 
498 	checkBoxAllowTeamResourceSharing.registerGraphicComponent(containerName,"checkBoxAllowTeamResourceSharing");
499 	checkBoxAllowTeamResourceSharing.init(xoffset+612, 640);
500 	checkBoxAllowTeamResourceSharing.setValue(false);
501 	checkBoxAllowTeamResourceSharing.setVisible(true);
502 
503 
504 	// Network Pause for lagged clients
505 	labelNetworkPauseGameForLaggedClients.registerGraphicComponent(containerName,"labelNetworkPauseGameForLaggedClients");
506 	labelNetworkPauseGameForLaggedClients.init(labelAllowTeamResourceSharing.getX(), networkHeadPos, 80);
507 	labelNetworkPauseGameForLaggedClients.setText(lang.getString("NetworkPauseGameForLaggedClients"));
508 
509 	checkBoxNetworkPauseGameForLaggedClients.registerGraphicComponent(containerName,"checkBoxNetworkPauseGameForLaggedClients");
510 	checkBoxNetworkPauseGameForLaggedClients.init(checkBoxAllowTeamResourceSharing.getX(), networkHeadPos);
511 	checkBoxNetworkPauseGameForLaggedClients.setValue(true);
512 
513 	//list boxes
514 	xoffset=5;
515 	int rowHeight=27;
516     for(int i=0; i<GameConstants::maxPlayers; ++i){
517 
518     	labelPlayers[i].registerGraphicComponent(containerName,"labelPlayers" + intToStr(i));
519 		labelPlayers[i].init(xoffset-1, setupPos-30-i*rowHeight+2);
520 		labelPlayers[i].setFont(CoreData::getInstance().getMenuFontVeryBig());
521 		labelPlayers[i].setFont3D(CoreData::getInstance().getMenuFontVeryBig3D());
522 
523 		labelPlayerStatus[i].registerGraphicComponent(containerName,"labelPlayerStatus" + intToStr(i));
524 		labelPlayerStatus[i].init(xoffset+14, setupPos-30-i*rowHeight+2);
525 		labelPlayerNames[i].registerGraphicComponent(containerName,"labelPlayerNames" + intToStr(i));
526 		labelPlayerNames[i].init(xoffset+30,setupPos-30-i*rowHeight);
527 
528 		listBoxControls[i].registerGraphicComponent(containerName,"listBoxControls" + intToStr(i));
529         listBoxControls[i].init(xoffset+160, setupPos-30-i*rowHeight, 174);
530 
531         buttonBlockPlayers[i].registerGraphicComponent(containerName,"buttonBlockPlayers" + intToStr(i));
532         //buttonBlockPlayers[i].init(xoffset+355, setupPos-30-i*rowHeight, 70);
533         buttonBlockPlayers[i].init(xoffset+185, setupPos-30-i*rowHeight, 124);
534         buttonBlockPlayers[i].setText(lang.getString("BlockPlayer"));
535         buttonBlockPlayers[i].setFont(CoreData::getInstance().getDisplayFontSmall());
536         buttonBlockPlayers[i].setFont3D(CoreData::getInstance().getDisplayFontSmall3D());
537 
538         listBoxRMultiplier[i].registerGraphicComponent(containerName,"listBoxRMultiplier" + intToStr(i));
539         listBoxRMultiplier[i].init(xoffset+336, setupPos-30-i*rowHeight,70);
540 
541         listBoxFactions[i].registerGraphicComponent(containerName,"listBoxFactions" + intToStr(i));
542         listBoxFactions[i].init(xoffset+411, setupPos-30-i*rowHeight, 247);
543         listBoxFactions[i].setLeftControlled(true);
544 
545         listBoxTeams[i].registerGraphicComponent(containerName,"listBoxTeams" + intToStr(i));
546 		listBoxTeams[i].init(xoffset+660, setupPos-30-i*rowHeight, 60);
547 		listBoxTeams[i].setLighted(true);
548 
549 		labelNetStatus[i].registerGraphicComponent(containerName,"labelNetStatus" + intToStr(i));
550 		labelNetStatus[i].init(xoffset+726, setupPos-30-i*rowHeight, 60);
551 		labelNetStatus[i].setFont(CoreData::getInstance().getDisplayFontSmall());
552 		labelNetStatus[i].setFont3D(CoreData::getInstance().getDisplayFontSmall3D());
553     }
554 
555 	buttonClearBlockedPlayers.registerGraphicComponent(containerName,"buttonClearBlockedPlayers");
556 	buttonClearBlockedPlayers.init(xoffset+160, setupPos-30-8*rowHeight, 174+2+70);
557 
558 	labelControl.registerGraphicComponent(containerName,"labelControl");
559 	labelControl.init(xoffset+160, setupPos, 50, GraphicListBox::defH, true);
560 	labelControl.setText(lang.getString("Control"));
561 
562     labelRMultiplier.registerGraphicComponent(containerName,"labelRMultiplier");
563 	labelRMultiplier.init(xoffset+310, setupPos, 50, GraphicListBox::defH, true);
564 
565 	labelFaction.registerGraphicComponent(containerName,"labelFaction");
566     labelFaction.init(xoffset+411, setupPos, 50, GraphicListBox::defH, true);
567     labelFaction.setText(lang.getString("Faction"));
568 
569     labelTeam.registerGraphicComponent(containerName,"labelTeam");
570     labelTeam.init(xoffset+660, setupPos, 50, GraphicListBox::defH, true);
571     labelTeam.setText(lang.getString("Team"));
572 
573     labelControl.setFont(CoreData::getInstance().getMenuFontBig());
574     labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D());
575     labelRMultiplier.setFont(CoreData::getInstance().getMenuFontBig());
576     labelRMultiplier.setFont3D(CoreData::getInstance().getMenuFontBig3D());
577 	labelFaction.setFont(CoreData::getInstance().getMenuFontBig());
578 	labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D());
579 	labelTeam.setFont(CoreData::getInstance().getMenuFontBig());
580 	labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D());
581 
582     //xoffset=100;
583 
584 	//texts
585 	buttonClearBlockedPlayers.setText(lang.getString("BlockPlayerClear"));
586 	buttonReturn.setText(lang.getString("Return"));
587 	buttonPlayNow.setText(lang.getString("PlayNow"));
588 	buttonRestoreLastSettings.setText(lang.getString("ReloadLastGameSettings"));
589 
590 	vector<string> controlItems;
591     controlItems.push_back(lang.getString("Closed"));
592 	controlItems.push_back(lang.getString("CpuEasy"));
593 	controlItems.push_back(lang.getString("Cpu"));
594     controlItems.push_back(lang.getString("CpuUltra"));
595     controlItems.push_back(lang.getString("CpuMega"));
596 	controlItems.push_back(lang.getString("Network"));
597 	controlItems.push_back(lang.getString("NetworkUnassigned"));
598 	controlItems.push_back(lang.getString("Human"));
599 
600 	if(config.getBool("EnableNetworkCpu","false") == true) {
601 		controlItems.push_back(lang.getString("NetworkCpuEasy"));
602 		controlItems.push_back(lang.getString("NetworkCpu"));
603 	    controlItems.push_back(lang.getString("NetworkCpuUltra"));
604 	    controlItems.push_back(lang.getString("NetworkCpuMega"));
605 	}
606 
607 	vector<string> teamItems;
608 	for(int i = 1; i <= GameConstants::maxPlayers; ++i) {
609 		teamItems.push_back(intToStr(i));
610 	}
611 	for(int i = GameConstants::maxPlayers + 1; i <= GameConstants::maxPlayers + GameConstants::specialFactions; ++i) {
612 		teamItems.push_back(intToStr(i));
613 	}
614 
615 	reloadFactions(false,"");
616 
617 	if(factionFiles.empty() == true) {
618 		showGeneralError=true;
619 		generalErrorToShow = "[#1] There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]";
620     }
621 
622 	for(int i=0; i < GameConstants::maxPlayers; ++i) {
623 		labelPlayerStatus[i].setText(" ");
624 		labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusReadyTexture());
625 		labelPlayerStatus[i].setH(16);
626 		labelPlayerStatus[i].setW(12);
627 
628 		//labelPlayers[i].setText(lang.getString("Player")+" "+intToStr(i));
629 		labelPlayers[i].setText(intToStr(i+1));
630 		labelPlayerNames[i].setText("*");
631 		labelPlayerNames[i].setMaxEditWidth(16);
632 		labelPlayerNames[i].setMaxEditRenderWidth(127);
633 
634         listBoxTeams[i].setItems(teamItems);
635 		listBoxTeams[i].setSelectedItemIndex(i);
636 		lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex();
637 
638 		listBoxControls[i].setItems(controlItems);
639 		listBoxRMultiplier[i].setItems(rMultiplier);
640 		listBoxRMultiplier[i].setSelectedItem("1.0");
641 		labelNetStatus[i].setText("");
642     }
643 
644 	loadMapInfo(Config::getMapPath(getCurrentMapFile()), &mapInfo, true);
645 	labelMapInfo.setText(mapInfo.desc);
646 
647 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
648 
649 	//init controllers
650 	if(serverInitError == false) {
651 		ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
652 		if(serverInterface == NULL) {
653 			throw megaglest_runtime_error("serverInterface == NULL");
654 		}
655 		if(this->headlessServerMode == true) {
656 			listBoxControls[0].setSelectedItemIndex(ctNetwork);
657 			updateResourceMultiplier(0);
658 		}
659 		else {
660 			setSlotHuman(0);
661 			updateResourceMultiplier(0);
662 		}
663 		labelPlayerNames[0].setText("");
664 		labelPlayerNames[0].setText(getHumanPlayerName());
665 
666 		if(openNetworkSlots == true) {
667 			for(int i= 1; i< mapInfo.players; ++i){
668 				listBoxControls[i].setSelectedItemIndex(ctNetwork);
669 			}
670 		}
671 		else{
672 			listBoxControls[1].setSelectedItemIndex(ctCpu);
673 		}
674 		updateControlers();
675 		updateNetworkSlots();
676 
677 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
678 
679 		// Ensure we have set the gamesettings at least once
680 		GameSettings gameSettings;
681 		loadGameSettings(&gameSettings);
682 
683 		serverInterface->setGameSettings(&gameSettings,false);
684 	}
685 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
686 
687 	updateAllResourceMultiplier();
688 
689 	// write hint to console:
690 	Config &configKeys = Config::getInstance(std::pair<ConfigType,ConfigType>(cfgMainKeys,cfgUserKeys));
691 
692 	console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + configKeys.getString("ToggleMusic") + "\"");
693 
694 	chatManager.init(&console, -1,true);
695 
696 	GraphicComponent::applyAllCustomProperties(containerName);
697 
698 	static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__);
699 	publishToMasterserverThread = new SimpleTaskThread(this,0,300,false,(void *)tnt_MASTERSERVER);
700 	publishToMasterserverThread->setUniqueID(mutexOwnerId);
701 
702 	static string mutexOwnerId2 = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__);
703 	publishToClientsThread = new SimpleTaskThread(this,0,200,false,(void *)tnt_CLIENTS,false);
704 	publishToClientsThread->setUniqueID(mutexOwnerId2);
705 
706 	publishToMasterserverThread->start();
707 	publishToClientsThread->start();
708 
709 	if(openNetworkSlots == true) {
710 		string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey);
711 
712 		if(fileExists(data_path + DEFAULT_NETWORKGAME_FILENAME) == true)
713 			loadGameSettings(data_path + DEFAULT_NETWORKGAME_FILENAME);
714 	}
715 	else {
716 		string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey);
717 
718 		if(fileExists(data_path + DEFAULT_GAME_FILENAME) == true)
719 			loadGameSettings(data_path + DEFAULT_GAME_FILENAME);
720 	}
721 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
722 
723 	}
724 	catch(const std::exception &ex) {
725 	    char szBuf[8096]="";
726 	    snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
727 	    SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
728 	    if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
729 
730 	    throw megaglest_runtime_error(szBuf);
731 	}
732 }
733 
createGameName(string controllingPlayer)734 string MenuStateCustomGame::createGameName(string controllingPlayer){
735 	Config &config = Config::getInstance();
736 	string serverTitle=config.getString("ServerTitle","");
737 
738 	if(serverTitle!="" && controllingPlayer == ""){
739 		return serverTitle;
740 	}
741 	else if (this->headlessServerMode == true) {
742 		if (controllingPlayer != "") {
743 			return controllingPlayer + " controls";
744 		} else {
745 			return "Headless (" + defaultPlayerName + ")";
746 		}
747 	} else {
748 		string defaultPlayerNameEnd = defaultPlayerName.substr(defaultPlayerName.size()-1, 1);
749 		if(defaultPlayerNameEnd == "s") {
750 			return defaultPlayerName+"' game";
751 		} else {
752 			return defaultPlayerName+"'s game";
753 		}
754 	}
755 }
756 
reloadUI()757 void MenuStateCustomGame::reloadUI() {
758 	Lang &lang= Lang::getInstance();
759     Config &config = Config::getInstance();
760 
761     console.resetFonts();
762 	mainMessageBox.init(lang.getString("Ok"),500,300);
763 
764 
765 	if(EndsWith(glestVersionString, "-dev") == false){
766 		labelLocalGameVersion.setText(glestVersionString);
767 	}
768 	else {
769 		//labelLocalGameVersion.setText(glestVersionString + " [" + getCompileDateTime() + ", " + getGITRevisionString() + "]");
770 		labelLocalGameVersion.setText(glestVersionString + " [" + getGITRevisionString() + "]");
771 	}
772 
773 	//vector<string> teamItems, controlItems, results , rMultiplier;
774 
775 	string ipText = "none";
776 	std::vector<std::string> ipList = Socket::getLocalIPAddressList();
777 	if(ipList.empty() == false) {
778 		ipText = "";
779 		for(int idx = 0; idx < (int)ipList.size(); idx++) {
780 			string ip = ipList[idx];
781 			if(ipText != "") {
782 				ipText += ", ";
783 			}
784 			ipText += ip;
785 		}
786 	}
787 	string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str());
788 	string externalPort=config.getString("PortExternal", serverPort.c_str());
789 
790 	labelLocalIP.setText(lang.getString("LanIP") + ipText + "  ( "+serverPort+" / "+externalPort+" )");
791 
792 	labelMap.setText(lang.getString("Map"));
793 
794 	labelMapFilter.setText(lang.getString("MapFilter"));
795 
796 	labelTileset.setText(lang.getString("Tileset"));
797 
798 	labelTechTree.setText(lang.getString("TechTree"));
799 
800 	labelAllowNativeLanguageTechtree.setText(lang.getString("AllowNativeLanguageTechtree"));
801 
802 	labelFogOfWar.setText(lang.getString("FogOfWar"));
803 
804 	std::vector<std::string> listBoxData;
805 	listBoxData.push_back(lang.getString("Enabled"));
806 	listBoxData.push_back(lang.getString("Explored"));
807 	listBoxData.push_back(lang.getString("Disabled"));
808 	listBoxFogOfWar.setItems(listBoxData);
809 
810 	// Allow Observers
811 	labelAllowObservers.setText(lang.getString("AllowObservers"));
812 
813 	// Allow Switch Team Mode
814 	labelEnableSwitchTeamMode.setText(lang.getString("EnableSwitchTeamMode"));
815 
816 	labelAllowInGameJoinPlayer.setText(lang.getString("AllowInGameJoinPlayer"));
817 
818 	labelAllowTeamUnitSharing.setText(lang.getString("AllowTeamUnitSharing"));
819 	labelAllowTeamResourceSharing.setText(lang.getString("AllowTeamResourceSharing"));
820 
821 	labelAISwitchTeamAcceptPercent.setText(lang.getString("AISwitchTeamAcceptPercent"));
822 
823 	listBoxData.clear();
824 
825 	// Advanced Options
826 	labelAdvanced.setText(lang.getString("AdvancedGameOptions"));
827 
828 	labelPublishServer.setText(lang.getString("PublishServer"));
829 
830 	labelGameName.setFont(CoreData::getInstance().getMenuFontBig());
831 	labelGameName.setFont3D(CoreData::getInstance().getMenuFontBig3D());
832 
833 	labelGameName.setText(createGameName());
834 
835 	labelNetworkPauseGameForLaggedClients.setText(lang.getString("NetworkPauseGameForLaggedClients"));
836 
837     for(int i=0; i < GameConstants::maxPlayers; ++i) {
838         buttonBlockPlayers[i].setText(lang.getString("BlockPlayer"));
839     }
840 
841 	labelControl.setText(lang.getString("Control"));
842 
843     labelFaction.setText(lang.getString("Faction"));
844 
845     labelTeam.setText(lang.getString("Team"));
846 
847     labelControl.setFont(CoreData::getInstance().getMenuFontBig());
848     labelControl.setFont3D(CoreData::getInstance().getMenuFontBig3D());
849     labelRMultiplier.setFont(CoreData::getInstance().getMenuFontBig());
850     labelRMultiplier.setFont3D(CoreData::getInstance().getMenuFontBig3D());
851 	labelFaction.setFont(CoreData::getInstance().getMenuFontBig());
852 	labelFaction.setFont3D(CoreData::getInstance().getMenuFontBig3D());
853 	labelTeam.setFont(CoreData::getInstance().getMenuFontBig());
854 	labelTeam.setFont3D(CoreData::getInstance().getMenuFontBig3D());
855 
856 	//texts
857 	buttonClearBlockedPlayers.setText(lang.getString("BlockPlayerClear"));
858 	buttonReturn.setText(lang.getString("Return"));
859 	buttonPlayNow.setText(lang.getString("PlayNow"));
860 	buttonRestoreLastSettings.setText(lang.getString("ReloadLastGameSettings"));
861 
862 	vector<string> controlItems;
863     controlItems.push_back(lang.getString("Closed"));
864 	controlItems.push_back(lang.getString("CpuEasy"));
865 	controlItems.push_back(lang.getString("Cpu"));
866     controlItems.push_back(lang.getString("CpuUltra"));
867     controlItems.push_back(lang.getString("CpuMega"));
868 	controlItems.push_back(lang.getString("Network"));
869 	controlItems.push_back(lang.getString("NetworkUnassigned"));
870 	controlItems.push_back(lang.getString("Human"));
871 
872 	if(config.getBool("EnableNetworkCpu","false") == true) {
873 		controlItems.push_back(lang.getString("NetworkCpuEasy"));
874 		controlItems.push_back(lang.getString("NetworkCpu"));
875 	    controlItems.push_back(lang.getString("NetworkCpuUltra"));
876 	    controlItems.push_back(lang.getString("NetworkCpuMega"));
877 	}
878 
879 	for(int i=0; i < GameConstants::maxPlayers; ++i) {
880 		labelPlayers[i].setText(intToStr(i+1));
881 
882 		listBoxControls[i].setItems(controlItems);
883     }
884 
885     labelFallbackCpuMultiplier.setText(lang.getString("FallbackCpuMultiplier"));
886 
887 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
888 
889 	vector<string> playerStatuses;
890 	playerStatuses.push_back(lang.getString("PlayerStatusSetup"));
891 	playerStatuses.push_back(lang.getString("PlayerStatusBeRightBack"));
892 	playerStatuses.push_back(lang.getString("PlayerStatusReady"));
893 	listBoxPlayerStatus.setItems(playerStatuses);
894 
895 	labelScenario.setText(lang.getString("Scenario"));
896 
897 	reloadFactions(true,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : ""));
898 
899 	// write hint to console:
900 	Config &configKeys = Config::getInstance(std::pair<ConfigType,ConfigType>(cfgMainKeys,cfgUserKeys));
901 
902 	console.addLine(lang.getString("ToSwitchOffMusicPress") + " - \"" + configKeys.getString("ToggleMusic") + "\"");
903 
904 	chatManager.init(&console, -1,true);
905 
906 	GraphicComponent::reloadFontsForRegisterGraphicComponents(containerName);
907 }
908 
cleanupThread(SimpleTaskThread ** thread)909 void MenuStateCustomGame::cleanupThread(SimpleTaskThread **thread) {
910 	//printf("LINE: %d *thread = %p\n",__LINE__,*thread);
911 
912     if(thread != NULL && *thread != NULL) {
913     	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1 cleanupThread callingThread [%p]\n",*thread);
914 
915     	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
916 
917     	SimpleTaskThread *threadPtr = *thread;
918     	int value = threadPtr->getUserdataAsInt();
919     	THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value;
920 
921     	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1. cleanupThread callingThread [%p] value = %d\n",*thread,value);
922 
923         needToBroadcastServerSettings = false;
924         needToRepublishToMasterserver = false;
925         lastNetworkPing               = time(NULL);
926         threadPtr->setThreadOwnerValid(false);
927 
928         if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
929 
930         if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1.. cleanupThread callingThread [%p] value = %d\n",*thread,value);
931 
932         if(forceWaitForShutdown == true) {
933     		time_t elapsed = time(NULL);
934     		threadPtr->signalQuit();
935 
936     		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1a cleanupThread callingThread [%p]\n",*thread);
937 
938     		for(;(threadPtr->canShutdown(false) == false  ||
939     				threadPtr->getRunningStatus() == true) &&
940     			difftime((long int)time(NULL),elapsed) <= 15;) {
941     			//sleep(150);
942     		}
943 
944     		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1b cleanupThread callingThread [%p]\n",*thread);
945 
946     		if(threadPtr->canShutdown(true) == true &&
947     				threadPtr->getRunningStatus() == false) {
948     			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1c cleanupThread callingThread [%p]\n",*thread);
949 
950     			delete threadPtr;
951     			//printf("LINE: %d *thread = %p\n",__LINE__,*thread);
952     			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
953     		}
954     		else {
955     			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1d cleanupThread callingThread [%p]\n",*thread);
956 
957     			char szBuf[8096]="";
958     			snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown thread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
959     			//SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
960     			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf);
961     			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
962 
963     			if(threadType == tnt_MASTERSERVER) {
964     				threadPtr->setOverrideShutdownTask(shutdownTaskStatic);
965     			}
966     			threadPtr->setDeleteSelfOnExecutionDone(true);
967     			threadPtr->setDeleteAfterExecute(true);
968     			//printf("LINE: %d *thread = %p\n",__LINE__,*thread);
969     		}
970     		threadPtr = NULL;
971     		//if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1e cleanupThread callingThread [%p]\n",*thread);
972         }
973         else {
974         	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1f cleanupThread callingThread [%p]\n",*thread);
975         	threadPtr->signalQuit();
976         	sleep(0);
977         	if(threadPtr->canShutdown(true) == true &&
978         			threadPtr->getRunningStatus() == false) {
979         		if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1g cleanupThread callingThread [%p]\n",*thread);
980         		delete threadPtr;
981         		//printf("LINE: %d *thread = %p\n",__LINE__,*thread);
982         	}
983     		else {
984     			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1h cleanupThread callingThread [%p]\n",*thread);
985     			char szBuf[8096]="";
986     			snprintf(szBuf,8096,"In [%s::%s %d] Error cannot shutdown thread\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
987     			//SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
988     			if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s",szBuf);
989     			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
990 
991     			if(threadType == tnt_MASTERSERVER) {
992     				threadPtr->setOverrideShutdownTask(shutdownTaskStatic);
993     			}
994     			threadPtr->setDeleteSelfOnExecutionDone(true);
995     			threadPtr->setDeleteAfterExecute(true);
996     			//printf("LINE: %d *thread = %p\n",__LINE__,*thread);
997     		}
998         }
999 
1000         *thread = NULL;
1001         if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#2 cleanupThread callingThread [%p]\n",*thread);
1002     }
1003     //printf("LINE: %d *thread = %p\n",__LINE__,*thread);
1004 }
1005 
cleanup()1006 void MenuStateCustomGame::cleanup() {
1007 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1008 
1009 	if(publishToMasterserverThread) {
1010 		//printf("LINE: %d\n",__LINE__);
1011 		cleanupThread(&publishToMasterserverThread);
1012 	}
1013 	if(publishToClientsThread) {
1014 		//printf("LINE: %d\n",__LINE__);
1015 		cleanupThread(&publishToClientsThread);
1016 	}
1017 
1018 	//printf("LINE: %d\n",__LINE__);
1019 
1020     if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1021 
1022 	cleanupMapPreviewTexture();
1023 
1024 	if(factionVideo != NULL) {
1025 		factionVideo->closePlayer();
1026 		delete factionVideo;
1027 		factionVideo = NULL;
1028 	}
1029 
1030 	if(forceWaitForShutdown == true) {
1031 		NetworkManager::getInstance().end();
1032 	}
1033 
1034 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1035 }
1036 
~MenuStateCustomGame()1037 MenuStateCustomGame::~MenuStateCustomGame() {
1038 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1039 
1040     cleanup();
1041 
1042     if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1043 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1044 }
1045 
returnToParentMenu()1046 void MenuStateCustomGame::returnToParentMenu() {
1047 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1048 
1049 	needToBroadcastServerSettings = false;
1050 	needToRepublishToMasterserver = false;
1051 	lastNetworkPing               = time(NULL);
1052 	ParentMenuState parentMenuState = this->parentMenuState;
1053 
1054 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1055 
1056 	forceWaitForShutdown = false;
1057 	if(parentMenuState==pMasterServer) {
1058 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1059 		cleanup();
1060 		mainMenu->setState(new MenuStateMasterserver(program, mainMenu));
1061 	}
1062 	else if(parentMenuState==pLanGame) {
1063 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1064 		cleanup();
1065 		mainMenu->setState(new MenuStateJoinGame(program, mainMenu));
1066 	}
1067 	else {
1068 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1069 		cleanup();
1070 		mainMenu->setState(new MenuStateNewGame(program, mainMenu));
1071 	}
1072 
1073 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1074 }
1075 
mouseClick(int x,int y,MouseButton mouseButton)1076 void MenuStateCustomGame::mouseClick(int x, int y, MouseButton mouseButton) {
1077 	if(isMasterserverMode() == true) {
1078 		return;
1079 	}
1080 
1081     try {
1082         CoreData &coreData= CoreData::getInstance();
1083         SoundRenderer &soundRenderer= SoundRenderer::getInstance();
1084         int oldListBoxMapfilterIndex=listBoxMapFilter.getSelectedItemIndex();
1085 
1086         if(mainMessageBox.getEnabled()){
1087             int button= 0;
1088             if(mainMessageBox.mouseClick(x, y, button)) {
1089                 soundRenderer.playFx(coreData.getClickSoundA());
1090                 if(button == 0) {
1091                     mainMessageBox.setEnabled(false);
1092                 }
1093             }
1094         }
1095         else {
1096         	string advanceToItemStartingWith = "";
1097         	if(::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == true) {
1098 				const wchar_t lastKey = ::Shared::Platform::Window::extractLastKeyPressed();
1099 //				string helpString = "";
1100 //				helpString = lastKey;
1101 //				printf("lastKey = '%s'\n",helpString.c_str());
1102 				advanceToItemStartingWith =  lastKey;
1103         	}
1104 
1105         	if(mapPreviewTexture != NULL) {
1106 //        		printf("X: %d Y: %d      [%d, %d, %d, %d]\n",
1107 //        				x, y,
1108 //        				this->render_mapPreviewTexture_X, this->render_mapPreviewTexture_X + this->render_mapPreviewTexture_W,
1109 //        				this->render_mapPreviewTexture_Y, this->render_mapPreviewTexture_Y + this->render_mapPreviewTexture_H);
1110 
1111 				if( x >= this->render_mapPreviewTexture_X && x <= this->render_mapPreviewTexture_X + this->render_mapPreviewTexture_W &&
1112 					y >= this->render_mapPreviewTexture_Y && y <= this->render_mapPreviewTexture_Y + this->render_mapPreviewTexture_H) {
1113 
1114 					if( this->render_mapPreviewTexture_X == mapPreviewTexture_X &&
1115 						this->render_mapPreviewTexture_Y == mapPreviewTexture_Y &&
1116 						this->render_mapPreviewTexture_W == mapPreviewTexture_W &&
1117 						this->render_mapPreviewTexture_H == mapPreviewTexture_H) {
1118 
1119 						const Metrics &metrics= Metrics::getInstance();
1120 
1121 						this->render_mapPreviewTexture_X = 0;
1122 						this->render_mapPreviewTexture_Y = 0;
1123 						this->render_mapPreviewTexture_W = metrics.getVirtualW();
1124 						this->render_mapPreviewTexture_H = metrics.getVirtualH();
1125 						this->zoomedMap = true;
1126 
1127 						cleanupMapPreviewTexture();
1128 					}
1129 					else {
1130 						this->render_mapPreviewTexture_X = mapPreviewTexture_X;
1131 						this->render_mapPreviewTexture_Y = mapPreviewTexture_Y;
1132 						this->render_mapPreviewTexture_W = mapPreviewTexture_W;
1133 						this->render_mapPreviewTexture_H = mapPreviewTexture_H;
1134 						this->zoomedMap = false;
1135 
1136 						cleanupMapPreviewTexture();
1137 					}
1138 					return;
1139 				}
1140 	        	if(this->zoomedMap == true){
1141 	        		return;
1142 	        	}
1143         	}
1144 
1145         	if(activeInputLabel!=NULL && !(activeInputLabel->mouseClick(x,y))){
1146 				setActiveInputLabel(NULL);
1147 			}
1148 			if(buttonReturn.mouseClick(x,y) || serverInitError == true) {
1149 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1150 
1151 				soundRenderer.playFx(coreData.getClickSoundA());
1152 
1153 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1154 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1155 				needToBroadcastServerSettings = false;
1156 				needToRepublishToMasterserver = false;
1157 				lastNetworkPing               = time(NULL);
1158 				safeMutex.ReleaseLock();
1159 				safeMutexCLI.ReleaseLock();
1160 
1161 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1162 
1163 				returnToParentMenu();
1164 				return;
1165 			}
1166 			else if(buttonPlayNow.mouseClick(x,y) && buttonPlayNow.getEnabled()) {
1167 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1168 
1169 				PlayNow(true);
1170 				return;
1171 			}
1172 			else if(buttonRestoreLastSettings.mouseClick(x,y) && buttonRestoreLastSettings.getEnabled()) {
1173 				soundRenderer.playFx(coreData.getClickSoundB());
1174 
1175 				RestoreLastGameSettings();
1176 			}
1177 			else if(listBoxMap.mouseClick(x, y,advanceToItemStartingWith)){
1178 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n", getCurrentMapFile().c_str());
1179 
1180 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1181 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1182 
1183 				loadMapInfo(Config::getMapPath(getCurrentMapFile(),"",false), &mapInfo, true);
1184 				labelMapInfo.setText(mapInfo.desc);
1185 				updateControlers();
1186 				updateNetworkSlots();
1187 
1188 				if(checkBoxPublishServer.getValue() == true) {
1189 					needToRepublishToMasterserver = true;
1190 				}
1191 
1192 				if(hasNetworkGameSettings() == true) {
1193 					//delay publishing for 5 seconds
1194 					needToPublishDelayed=true;
1195 					mapPublishingDelayTimer=time(NULL);
1196 				}
1197 			}
1198 			else if (checkBoxAdvanced.getValue() == 1 && listBoxFogOfWar.mouseClick(x, y)) {
1199 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1200 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1201 
1202 				cleanupMapPreviewTexture();
1203 				if(checkBoxPublishServer.getValue() == true) {
1204 					needToRepublishToMasterserver = true;
1205 				}
1206 
1207 				if(hasNetworkGameSettings() == true) {
1208 					needToSetChangedGameSettings = true;
1209 					lastSetChangedGameSettings   = time(NULL);
1210 				}
1211 			}
1212 			else if (checkBoxAdvanced.getValue() == 1 && checkBoxAllowObservers.mouseClick(x, y)) {
1213 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1214 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1215 
1216 				if(checkBoxPublishServer.getValue() == true) {
1217 					needToRepublishToMasterserver = true;
1218 				}
1219 
1220 				reloadFactions(true,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : ""));
1221 
1222 				if(hasNetworkGameSettings() == true) {
1223 					needToSetChangedGameSettings = true;
1224 					lastSetChangedGameSettings   = time(NULL);
1225 				}
1226 			}
1227 			else if (checkBoxAllowInGameJoinPlayer.mouseClick(x, y)) {
1228 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1229 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1230 
1231 				if(checkBoxPublishServer.getValue() == true) {
1232 					needToRepublishToMasterserver = true;
1233 				}
1234 
1235 				if(hasNetworkGameSettings() == true) {
1236 					needToSetChangedGameSettings = true;
1237 					lastSetChangedGameSettings   = time(NULL);
1238 				}
1239 
1240 				ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1241 				serverInterface->setAllowInGameConnections(checkBoxAllowInGameJoinPlayer.getValue() == true);
1242 			}
1243 			else if (checkBoxAdvanced.getValue() == 1 && checkBoxAllowTeamUnitSharing.mouseClick(x, y)) {
1244 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1245 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1246 
1247 
1248 				if(checkBoxPublishServer.getValue() == true) {
1249 					needToRepublishToMasterserver = true;
1250 				}
1251 
1252 				if(hasNetworkGameSettings() == true) {
1253 					needToSetChangedGameSettings = true;
1254 					lastSetChangedGameSettings   = time(NULL);
1255 				}
1256 			}
1257 			else if (checkBoxAdvanced.getValue() == 1 && checkBoxAllowTeamResourceSharing.mouseClick(x, y)) {
1258 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1259 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1260 
1261 
1262 				if(checkBoxPublishServer.getValue() == true) {
1263 					needToRepublishToMasterserver = true;
1264 				}
1265 
1266 				if(hasNetworkGameSettings() == true) {
1267 					needToSetChangedGameSettings = true;
1268 					lastSetChangedGameSettings   = time(NULL);
1269 				}
1270 			}
1271 			else if (checkBoxAllowNativeLanguageTechtree.mouseClick(x, y)) {
1272 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1273 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1274 
1275 				if(checkBoxPublishServer.getValue() == true) {
1276 					needToRepublishToMasterserver = true;
1277 				}
1278 
1279 				if(hasNetworkGameSettings() == true)
1280 				{
1281 					needToSetChangedGameSettings = true;
1282 					lastSetChangedGameSettings   = time(NULL);
1283 				}
1284 			}
1285 			else if (checkBoxAdvanced.getValue() == 1 && checkBoxEnableSwitchTeamMode.mouseClick(x, y)) {
1286 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1287 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1288 
1289 				if(checkBoxPublishServer.getValue() == true) {
1290 					needToRepublishToMasterserver = true;
1291 				}
1292 
1293 				if(hasNetworkGameSettings() == true)
1294 				{
1295 					needToSetChangedGameSettings = true;
1296 					lastSetChangedGameSettings   = time(NULL);
1297 				}
1298 			}
1299 			else if (checkBoxAdvanced.getValue() == 1 && listBoxAISwitchTeamAcceptPercent.getEnabled() && listBoxAISwitchTeamAcceptPercent.mouseClick(x, y)) {
1300 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1301 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1302 
1303 				if(checkBoxPublishServer.getValue() == true) {
1304 					needToRepublishToMasterserver = true;
1305 				}
1306 
1307 				if(hasNetworkGameSettings() == true)
1308 				{
1309 					needToSetChangedGameSettings = true;
1310 					lastSetChangedGameSettings   = time(NULL);
1311 				}
1312 			}
1313 			else if (checkBoxAdvanced.getValue() == 1 && listBoxFallbackCpuMultiplier.getEditable() == true && listBoxFallbackCpuMultiplier.mouseClick(x, y)) {
1314 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1315 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1316 
1317 				if(checkBoxPublishServer.getValue() == true) {
1318 					needToRepublishToMasterserver = true;
1319 				}
1320 
1321 				if(hasNetworkGameSettings() == true)
1322 				{
1323 					needToSetChangedGameSettings = true;
1324 					lastSetChangedGameSettings   = time(NULL);
1325 				}
1326 			}
1327 			else if (checkBoxAdvanced.mouseClick(x, y)) {
1328 			}
1329 			else if(listBoxTileset.mouseClick(x, y,advanceToItemStartingWith)) {
1330 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1331 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1332 
1333 				if(checkBoxPublishServer.getValue() == true) {
1334 					needToRepublishToMasterserver = true;
1335 				}
1336 				if(hasNetworkGameSettings() == true)
1337 				{
1338 
1339 					//delay publishing for 5 seconds
1340 					needToPublishDelayed=true;
1341 					mapPublishingDelayTimer=time(NULL);
1342 				}
1343 			}
1344 			else if(listBoxMapFilter.mouseClick(x, y)){
1345 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1346 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1347 
1348 				switchToNextMapGroup(listBoxMapFilter.getSelectedItemIndex()-oldListBoxMapfilterIndex);
1349 
1350 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s\n", getCurrentMapFile().c_str());
1351 
1352 				loadMapInfo(Config::getMapPath(getCurrentMapFile()), &mapInfo, true);
1353 				labelMapInfo.setText(mapInfo.desc);
1354 				updateControlers();
1355 				updateNetworkSlots();
1356 
1357 				if(checkBoxPublishServer.getValue() == true) {
1358 					needToRepublishToMasterserver = true;
1359 				}
1360 
1361 				if(hasNetworkGameSettings() == true)
1362 				{
1363 					needToSetChangedGameSettings = true;
1364 					lastSetChangedGameSettings   = time(NULL);
1365 				}
1366 			}
1367 			else if(listBoxTechTree.mouseClick(x, y,advanceToItemStartingWith)){
1368 				reloadFactions(listBoxTechTree.getItemCount() <= 1,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : ""));
1369 
1370 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1371 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1372 
1373 				if(checkBoxPublishServer.getValue() == true) {
1374 					needToRepublishToMasterserver = true;
1375 				}
1376 
1377 				if(hasNetworkGameSettings() == true)
1378 				{
1379 					needToSetChangedGameSettings = true;
1380 					lastSetChangedGameSettings   = time(NULL);
1381 				}
1382 			}
1383 			else if(checkBoxPublishServer.mouseClick(x, y) && checkBoxPublishServer.getEditable()) {
1384 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1385 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1386 
1387 				needToRepublishToMasterserver = true;
1388 				soundRenderer.playFx(coreData.getClickSoundC());
1389 
1390 				ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1391 				serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == true);
1392 			}
1393 			else if(labelGameName.mouseClick(x, y) && checkBoxPublishServer.getEditable()){
1394 				setActiveInputLabel(&labelGameName);
1395 			}
1396 			else if(checkBoxAdvanced.getValue() == 1 && checkBoxNetworkPauseGameForLaggedClients.mouseClick(x, y)) {
1397 				MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1398 				MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1399 
1400 				if(checkBoxPublishServer.getValue() == true) {
1401 					needToRepublishToMasterserver = true;
1402 				}
1403 				if(hasNetworkGameSettings() == true)
1404 				{
1405 					needToSetChangedGameSettings = true;
1406 					lastSetChangedGameSettings   = time(NULL);
1407 				}
1408 
1409 				soundRenderer.playFx(coreData.getClickSoundC());
1410 			}
1411 		    else if(listBoxScenario.mouseClick(x, y) || checkBoxScenario.mouseClick(x,y)) {
1412 		        processScenario();
1413 			}
1414 			else {
1415 				for(int i = 0; i < mapInfo.players; ++i) {
1416 					MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1417 					MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1418 
1419 					// set multiplier
1420 					if(listBoxRMultiplier[i].mouseClick(x, y)) {
1421 						//printf("Line: %d multiplier index: %d i: %d itemcount: %d\n",__LINE__,listBoxRMultiplier[i].getSelectedItemIndex(),i,listBoxRMultiplier[i].getItemCount());
1422 
1423 						//for(int indexData = 0; indexData < listBoxRMultiplier[i].getItemCount(); ++indexData) {
1424 							//string item = listBoxRMultiplier[i].getItem(indexData);
1425 
1426 							//printf("Item index: %d value: %s\n",indexData,item.c_str());
1427 						//}
1428 					}
1429 
1430 					//ensure thet only 1 human player is present
1431 					ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1432 					ConnectionSlot *slot = serverInterface->getSlot(i,true);
1433 
1434 					bool checkControTypeClicked = false;
1435 					int selectedControlItemIndex = listBoxControls[i].getSelectedItemIndex();
1436 					if(selectedControlItemIndex != ctNetwork ||
1437 						(selectedControlItemIndex == ctNetwork && (slot == NULL || slot->isConnected() == false))) {
1438 						checkControTypeClicked = true;
1439 					}
1440 
1441 					//printf("checkControTypeClicked = %d selectedControlItemIndex = %d i = %d\n",checkControTypeClicked,selectedControlItemIndex,i);
1442 
1443 					if(selectedControlItemIndex != ctHuman &&
1444 							checkControTypeClicked == true &&
1445 							listBoxControls[i].mouseClick(x, y)) {
1446 						if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1447 
1448 						ControlType currentControlType = static_cast<ControlType>(
1449 								listBoxControls[i].getSelectedItemIndex());
1450 						int slotsToChangeStart = i;
1451 						int slotsToChangeEnd = i;
1452 						// If control is pressed while changing player types then change all other slots to same type
1453 						if(::Shared::Platform::Window::isKeyStateModPressed(KMOD_CTRL) == true &&
1454 								currentControlType != ctHuman) {
1455 							slotsToChangeStart = 0;
1456 							slotsToChangeEnd = mapInfo.players-1;
1457 						}
1458 
1459 						for(int index = slotsToChangeStart; index <= slotsToChangeEnd; ++index) {
1460 							if(index != i && static_cast<ControlType>(
1461 									listBoxControls[index].getSelectedItemIndex()) != ctHuman) {
1462 								listBoxControls[index].setSelectedItemIndex(listBoxControls[i].getSelectedItemIndex());
1463 							}
1464 							// Skip over networkunassigned
1465 							if(listBoxControls[index].getSelectedItemIndex() == ctNetworkUnassigned &&
1466 								selectedControlItemIndex != ctNetworkUnassigned) {
1467 								listBoxControls[index].mouseClick(x, y);
1468 							}
1469 
1470 							//look for human players
1471 							int humanIndex1= -1;
1472 							int humanIndex2= -1;
1473 							for(int j = 0; j < GameConstants::maxPlayers; ++j) {
1474 								ControlType ct= static_cast<ControlType>(listBoxControls[j].getSelectedItemIndex());
1475 								if(ct == ctHuman) {
1476 									if(humanIndex1 == -1) {
1477 										humanIndex1= j;
1478 									}
1479 									else {
1480 										humanIndex2= j;
1481 									}
1482 								}
1483 							}
1484 
1485 							if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] humanIndex1 = %d, humanIndex2 = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,humanIndex1,humanIndex2);
1486 
1487 							//no human
1488 							if(humanIndex1 == -1 && humanIndex2 == -1) {
1489 								setSlotHuman(index);
1490 								if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] i = %d, labelPlayerNames[i].getText() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index,labelPlayerNames[index].getText().c_str());
1491 
1492 								//printf("humanIndex1 = %d humanIndex2 = %d i = %d listBoxControls[i].getSelectedItemIndex() = %d\n",humanIndex1,humanIndex2,i,listBoxControls[i].getSelectedItemIndex());
1493 							}
1494 							//2 humans
1495 							else if(humanIndex1 != -1 && humanIndex2 != -1) {
1496 								int closeSlotIndex = (humanIndex1 == index ? humanIndex2: humanIndex1);
1497 								int humanSlotIndex = (closeSlotIndex == humanIndex1 ? humanIndex2 : humanIndex1);
1498 
1499 								string origPlayName = labelPlayerNames[closeSlotIndex].getText();
1500 
1501 								if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] closeSlotIndex = %d, origPlayName [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,closeSlotIndex,origPlayName.c_str());
1502 
1503 								listBoxControls[closeSlotIndex].setSelectedItemIndex(ctClosed);
1504 								setSlotHuman(humanSlotIndex);
1505 								labelPlayerNames[humanSlotIndex].setText((origPlayName != "" ? origPlayName : getHumanPlayerName()));
1506 							}
1507 							updateNetworkSlots();
1508 
1509 							if(checkBoxPublishServer.getValue() == true) {
1510 								needToRepublishToMasterserver = true;
1511 							}
1512 
1513 							if(hasNetworkGameSettings() == true) {
1514 								needToSetChangedGameSettings = true;
1515 								lastSetChangedGameSettings   = time(NULL);
1516 							}
1517 							updateResourceMultiplier(index);
1518 						}
1519 					}
1520 					else if(buttonClearBlockedPlayers.mouseClick(x, y)) {
1521 						soundRenderer.playFx(coreData.getClickSoundB());
1522 
1523 						ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1524 						if(serverInterface != NULL) {
1525 							ServerSocket *serverSocket = serverInterface->getServerSocket();
1526 							if(serverSocket != NULL) {
1527 								serverSocket->clearBlockedIPAddress();
1528 							}
1529 						}
1530 					}
1531 					else if(buttonBlockPlayers[i].mouseClick(x, y)) {
1532 						soundRenderer.playFx(coreData.getClickSoundB());
1533 
1534 						ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1535 						if(serverInterface != NULL) {
1536 							if(serverInterface->getSlot(i,true) != NULL &&
1537 							   serverInterface->getSlot(i,true)->isConnected()) {
1538 
1539 								ServerSocket *serverSocket = serverInterface->getServerSocket();
1540 								if(serverSocket != NULL) {
1541 									serverSocket->addIPAddressToBlockedList(serverInterface->getSlot(i,true)->getIpAddress());
1542 
1543 									Lang &lang= Lang::getInstance();
1544 									const vector<string> languageList = serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages();
1545 									for(unsigned int j = 0; j < languageList.size(); ++j) {
1546 										char szMsg[8096]="";
1547 										if(lang.hasString("BlockPlayerServerMsg",languageList[j]) == true) {
1548 											snprintf(szMsg,8096,lang.getString("BlockPlayerServerMsg",languageList[j]).c_str(),serverInterface->getSlot(i,true)->getIpAddress().c_str());
1549 										}
1550 										else {
1551 											snprintf(szMsg,8096,"The server has temporarily blocked IP Address [%s] from this game.",serverInterface->getSlot(i,true)->getIpAddress().c_str());
1552 										}
1553 
1554 										serverInterface->sendTextMessage(szMsg,-1, true,languageList[j]);
1555 									}
1556 									sleep(1);
1557 									serverInterface->getSlot(i,true)->close();
1558 								}
1559 							}
1560 						}
1561 					}
1562 					else if(listBoxFactions[i].mouseClick(x, y,advanceToItemStartingWith)) {
1563 						// Disallow CPU players to be observers
1564 						if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME) &&
1565 							(listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu ||
1566 							 listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) {
1567 							listBoxFactions[i].setSelectedItemIndex(0);
1568 						}
1569 						//
1570 
1571 						if(checkBoxPublishServer.getValue() == true) {
1572 							needToRepublishToMasterserver = true;
1573 						}
1574 
1575 						if(hasNetworkGameSettings() == true)
1576 						{
1577 							needToSetChangedGameSettings = true;
1578 							lastSetChangedGameSettings   = time(NULL);
1579 						}
1580 					}
1581 					else if(listBoxTeams[i].mouseClick(x, y))
1582 					{
1583 						if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] != formatString(GameConstants::OBSERVER_SLOTNAME)) {
1584 							if(listBoxTeams[i].getSelectedItemIndex() + 1 != (GameConstants::maxPlayers + fpt_Observer)) {
1585 								lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex();
1586 							}
1587 						}
1588 						else {
1589 							lastSelectedTeamIndex[i] = -1;
1590 						}
1591 
1592 						if(checkBoxPublishServer.getValue() == true) {
1593 							needToRepublishToMasterserver = true;
1594 						}
1595 
1596 						if(hasNetworkGameSettings() == true)
1597 						{
1598 							needToSetChangedGameSettings = true;
1599 							lastSetChangedGameSettings   = time(NULL);;
1600 						}
1601 					}
1602 					else if(labelPlayerNames[i].mouseClick(x, y)) {
1603 						ControlType ct= static_cast<ControlType>(listBoxControls[i].getSelectedItemIndex());
1604 						if(ct == ctHuman) {
1605 							setActiveInputLabel(&labelPlayerNames[i]);
1606 							break;
1607 						}
1608 					}
1609 				}
1610 			}
1611         }
1612 
1613 		if(hasNetworkGameSettings() == true && listBoxPlayerStatus.mouseClick(x,y)) {
1614 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1615 
1616 			soundRenderer.playFx(coreData.getClickSoundC());
1617 			if(getNetworkPlayerStatus()==npst_PickSettings)
1618 			{
1619 				listBoxPlayerStatus.setTextColor(Vec3f(1.0f,0.0f,0.0f));
1620 				listBoxPlayerStatus.setLighted(true);
1621 			}
1622 			else if(getNetworkPlayerStatus()==npst_BeRightBack)
1623 			{
1624 				listBoxPlayerStatus.setTextColor(Vec3f(1.0f,1.0f,0.0f));
1625 				listBoxPlayerStatus.setLighted(true);
1626 			}
1627 			else if(getNetworkPlayerStatus()==npst_Ready)
1628 			{
1629 				listBoxPlayerStatus.setTextColor(Vec3f(0.0f,1.0f,0.0f));
1630 				listBoxPlayerStatus.setLighted(false);
1631 			}
1632 
1633 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1634 
1635             if(checkBoxPublishServer.getValue() == true) {
1636                 needToRepublishToMasterserver = true;
1637             }
1638 
1639             if(hasNetworkGameSettings() == true) {
1640                 needToSetChangedGameSettings = true;
1641                 lastSetChangedGameSettings   = time(NULL);
1642             }
1643 		}
1644     }
1645 	catch(const std::exception &ex) {
1646 		char szBuf[8096]="";
1647 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
1648 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
1649 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
1650 
1651 		showGeneralError=true;
1652 		generalErrorToShow = szBuf;
1653 	}
1654 
1655 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1656 }
1657 
updateAllResourceMultiplier()1658 void MenuStateCustomGame::updateAllResourceMultiplier() {
1659 	for(int j=0; j<GameConstants::maxPlayers; ++j) {
1660 		updateResourceMultiplier(j);
1661 	}
1662 }
1663 
updateResourceMultiplier(const int index)1664 void MenuStateCustomGame::updateResourceMultiplier(const int index) {
1665 	//printf("Line: %d multiplier index: %d index: %d\n",__LINE__,listBoxRMultiplier[index].getSelectedItemIndex(),index);
1666 
1667 	ControlType ct= static_cast<ControlType>(listBoxControls[index].getSelectedItemIndex());
1668 	if(ct == ctCpuEasy || ct == ctNetworkCpuEasy)
1669 	{
1670 		listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::easyMultiplier,1));
1671 		listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false);
1672 	}
1673 	else if(ct == ctCpu || ct == ctNetworkCpu) {
1674 		listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::normalMultiplier,1));
1675 		listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false);
1676 	}
1677 	else if(ct == ctCpuUltra || ct == ctNetworkCpuUltra)
1678 	{
1679 		listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::ultraMultiplier,1));
1680 		listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false);
1681 	}
1682 	else if(ct == ctCpuMega || ct == ctNetworkCpuMega)
1683 	{
1684 		listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::megaMultiplier,1));
1685 		listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false);
1686 	}
1687 	//if(ct == ctHuman || ct == ctNetwork || ct == ctClosed) {
1688 	else {
1689 		listBoxRMultiplier[index].setSelectedItem(floatToStr(GameConstants::normalMultiplier,1));
1690 		listBoxRMultiplier[index].setEnabled(false);
1691 		//!!!listBoxRMultiplier[index].setEnabled(checkBoxScenario.getValue() == false);
1692 	}
1693 
1694 	listBoxRMultiplier[index].setEditable(listBoxRMultiplier[index].getEnabled());
1695 	listBoxRMultiplier[index].setVisible(ct != ctHuman && ct != ctNetwork && ct != ctClosed);
1696 	//listBoxRMultiplier[index].setVisible(ct != ctClosed);
1697 
1698 	//printf("Line: %d multiplier index: %d index: %d\n",__LINE__,listBoxRMultiplier[index].getSelectedItemIndex(),index);
1699 }
1700 
loadGameSettings(std::string fileName)1701 void MenuStateCustomGame::loadGameSettings(std::string fileName) {
1702 	// Ensure we have set the gamesettings at least once
1703 	GameSettings gameSettings = loadGameSettingsFromFile(fileName);
1704 	if(gameSettings.getMap() == "") {
1705 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1706 
1707 		loadGameSettings(&gameSettings);
1708 	}
1709 
1710 	ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1711 	serverInterface->setGameSettings(&gameSettings,false);
1712 
1713 	MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1714 	MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1715 
1716 	if(checkBoxPublishServer.getValue() == true) {
1717 		needToRepublishToMasterserver = true;
1718 	}
1719 
1720 	if(hasNetworkGameSettings() == true) {
1721 		needToSetChangedGameSettings = true;
1722 		lastSetChangedGameSettings   = time(NULL);
1723 	}
1724 }
1725 
RestoreLastGameSettings()1726 void MenuStateCustomGame::RestoreLastGameSettings() {
1727 	loadGameSettings(SAVED_GAME_FILENAME);
1728 }
1729 
checkNetworkPlayerDataSynch(bool checkMapCRC,bool checkTileSetCRC,bool checkTechTreeCRC)1730 bool MenuStateCustomGame::checkNetworkPlayerDataSynch(bool checkMapCRC,
1731 		bool checkTileSetCRC, bool checkTechTreeCRC) {
1732 	ServerInterface* serverInterface = NetworkManager::getInstance().getServerInterface();
1733 
1734 	bool dataSynchCheckOk = true;
1735 	for(int i= 0; i < mapInfo.players; ++i) {
1736 		if(listBoxControls[i].getSelectedItemIndex() == ctNetwork) {
1737 
1738 			MutexSafeWrapper safeMutex(serverInterface->getSlotMutex(i),CODE_AT_LINE);
1739 			ConnectionSlot *slot = serverInterface->getSlot(i,false);
1740 			if(	slot != NULL && slot->isConnected() &&
1741 				(slot->getAllowDownloadDataSynch() == true ||
1742 				 slot->getAllowGameDataSynchCheck() == true)) {
1743 
1744 				if(checkMapCRC == true &&
1745 						slot->getNetworkGameDataSynchCheckOkMap() == false) {
1746 					dataSynchCheckOk = false;
1747 					break;
1748 				}
1749 				if(checkTileSetCRC == true &&
1750 						slot->getNetworkGameDataSynchCheckOkTile() == false) {
1751 					dataSynchCheckOk = false;
1752 					break;
1753 				}
1754 				if(checkTechTreeCRC == true &&
1755 						slot->getNetworkGameDataSynchCheckOkTech() == false) {
1756 					dataSynchCheckOk = false;
1757 					break;
1758 				}
1759 			}
1760 		}
1761 	}
1762 
1763 	return dataSynchCheckOk;
1764 }
1765 
PlayNow(bool saveGame)1766 void MenuStateCustomGame::PlayNow(bool saveGame) {
1767 	if(listBoxTechTree.getItemCount() <= 0) {
1768 		mainMessageBoxState=1;
1769 
1770 		char szMsg[8096]="";
1771 		strcpy(szMsg,"Cannot start game.\nThere are no tech-trees!\n");
1772 		printf("%s",szMsg);
1773 
1774 		showMessageBox(szMsg, "", false);
1775 		return;
1776 	}
1777 
1778 	MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1779 	MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
1780 
1781 	if(saveGame == true) {
1782 		saveGameSettingsToFile(SAVED_GAME_FILENAME);
1783 	}
1784 
1785 	forceWaitForShutdown = false;
1786 	closeUnusedSlots();
1787 	CoreData &coreData= CoreData::getInstance();
1788 	SoundRenderer &soundRenderer= SoundRenderer::getInstance();
1789 	soundRenderer.playFx(coreData.getClickSoundC());
1790 
1791 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1792 
1793 	std::vector<string> randomFactionSelectionList;
1794 	int RandomCount = 0;
1795 	for(int i= 0; i < mapInfo.players; ++i) {
1796 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1797 
1798 		// Check for random faction selection and choose the faction now
1799 		if(listBoxControls[i].getSelectedItemIndex() != ctClosed) {
1800 			if(listBoxFactions[i].getSelectedItem() == formatString(GameConstants::RANDOMFACTION_SLOTNAME) &&
1801 				listBoxFactions[i].getItemCount() > 1) {
1802 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i);
1803 
1804 				// Max 1000 tries to get a random, unused faction
1805 				for(int findRandomFaction = 1; findRandomFaction < 1000; ++findRandomFaction) {
1806 					Chrono seed(true);
1807 					srand((unsigned int)seed.getCurTicks() + findRandomFaction);
1808 
1809 					int selectedFactionIndex = rand() % listBoxFactions[i].getItemCount();
1810 					string selectedFactionName = listBoxFactions[i].getItem(selectedFactionIndex);
1811 
1812 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] selectedFactionName [%s] selectedFactionIndex = %d, findRandomFaction = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,selectedFactionName.c_str(),selectedFactionIndex,findRandomFaction);
1813 
1814 					if(	selectedFactionName != formatString(GameConstants::RANDOMFACTION_SLOTNAME) &&
1815 						selectedFactionName != formatString(GameConstants::OBSERVER_SLOTNAME) &&
1816 						std::find(randomFactionSelectionList.begin(),randomFactionSelectionList.end(),selectedFactionName) == randomFactionSelectionList.end()) {
1817 
1818 						if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1819 						listBoxFactions[i].setSelectedItem(selectedFactionName);
1820 						randomFactionSelectionList.push_back(selectedFactionName);
1821 						break;
1822 					}
1823 				}
1824 
1825 				if(listBoxFactions[i].getSelectedItem() == formatString(GameConstants::RANDOMFACTION_SLOTNAME)) {
1826 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] RandomCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,RandomCount);
1827 
1828 					// Find first real faction and use it
1829 					int factionIndexToUse = RandomCount;
1830 					for(int useIdx = 0; useIdx < listBoxFactions[i].getItemCount(); useIdx++) {
1831 						string selectedFactionName = listBoxFactions[i].getItem(useIdx);
1832 						if(	selectedFactionName != formatString(GameConstants::RANDOMFACTION_SLOTNAME) &&
1833 							selectedFactionName != formatString(GameConstants::OBSERVER_SLOTNAME)) {
1834 							factionIndexToUse = useIdx;
1835 							break;
1836 						}
1837 					}
1838 					listBoxFactions[i].setSelectedItemIndex(factionIndexToUse);
1839 					randomFactionSelectionList.push_back(listBoxFactions[i].getItem(factionIndexToUse));
1840 				}
1841 
1842 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] i = %d, listBoxFactions[i].getSelectedItem() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,listBoxFactions[i].getSelectedItem().c_str());
1843 
1844 				RandomCount++;
1845 			}
1846 		}
1847 	}
1848 
1849 	if(RandomCount > 0) {
1850 		needToSetChangedGameSettings = true;
1851 	}
1852 
1853 	safeMutex.ReleaseLock(true);
1854 	safeMutexCLI.ReleaseLock(true);
1855 	GameSettings gameSettings;
1856 	loadGameSettings(&gameSettings, true);
1857 
1858 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1859 	ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
1860 
1861 	// Send the game settings to each client if we have at least one networked client
1862 	safeMutex.Lock();
1863 	safeMutexCLI.Lock();
1864 
1865 	bool dataSynchCheckOk = checkNetworkPlayerDataSynch(true, true, true);
1866 
1867 	// Ensure we have no dangling network players
1868 	for(int i= 0; i < GameConstants::maxPlayers; ++i) {
1869 		if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
1870 			mainMessageBoxState=1;
1871 
1872 			Lang &lang= Lang::getInstance();
1873 			string sMsg = "";
1874 			if(lang.hasString("NetworkSlotUnassignedErrorUI") == true) {
1875 				sMsg = lang.getString("NetworkSlotUnassignedErrorUI");
1876 			}
1877 			else {
1878 				sMsg = "Cannot start game.\nSome player(s) are not in a network game slot!";
1879 			}
1880 
1881 			showMessageBox(sMsg, "", false);
1882 
1883 	    	const vector<string> languageList = serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages();
1884 	    	for(unsigned int j = 0; j < languageList.size(); ++j) {
1885 				char szMsg[8096]="";
1886 				if(lang.hasString("NetworkSlotUnassignedError",languageList[j]) == true) {
1887 					string msg_string = lang.getString("NetworkSlotUnassignedError");
1888 #ifdef WIN32
1889 					strncpy(szMsg,msg_string.c_str(),min((int)msg_string.length(),8095));
1890 #else
1891 					strncpy(szMsg,msg_string.c_str(),std::min((int)msg_string.length(),8095));
1892 #endif
1893 				}
1894 				else {
1895 					strcpy(szMsg,"Cannot start game, some player(s) are not in a network game slot!");
1896 				}
1897 
1898 				serverInterface->sendTextMessage(szMsg,-1, true,languageList[j]);
1899 	    	}
1900 
1901 			safeMutex.ReleaseLock();
1902 			safeMutexCLI.ReleaseLock();
1903 			return;
1904 		}
1905 	}
1906 
1907 	if(dataSynchCheckOk == false) {
1908 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1909 		mainMessageBoxState=1;
1910 		showMessageBox("You cannot start the game because\none or more clients do not have the same game data!", "Data Mismatch Error", false);
1911 
1912 		safeMutex.ReleaseLock();
1913 		safeMutexCLI.ReleaseLock();
1914 		return;
1915 	}
1916 	else {
1917 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1918 		if( (hasNetworkGameSettings() == true &&
1919 			 needToSetChangedGameSettings == true) || (RandomCount > 0)) {
1920 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1921 			serverInterface->setGameSettings(&gameSettings,true);
1922 			serverInterface->broadcastGameSetup(&gameSettings);
1923 
1924 			needToSetChangedGameSettings    = false;
1925 			lastSetChangedGameSettings      = time(NULL);
1926 		}
1927 
1928 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1929 
1930 		// Last check, stop human player from being in same slot as network
1931 		if(isMasterserverMode() == false) {
1932 			bool hasHuman = false;
1933 			for(int i= 0; i < mapInfo.players; ++i) {
1934 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1935 
1936 				// Check for random faction selection and choose the faction now
1937 				if(listBoxControls[i].getSelectedItemIndex() == ctHuman) {
1938 					hasHuman = true;
1939 					break;
1940 				}
1941 			}
1942 			if(hasHuman == false) {
1943 				mainMessageBoxState=1;
1944 
1945 				Lang &lang= Lang::getInstance();
1946 				string sMsg = lang.getString("NetworkSlotNoHumanErrorUI","",true);
1947 				showMessageBox(sMsg, "", false);
1948 
1949 		    	const vector<string> languageList = serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages();
1950 		    	for(unsigned int j = 0; j < languageList.size(); ++j) {
1951 					sMsg = lang.getString("NetworkSlotNoHumanError","",true);
1952 
1953 					serverInterface->sendTextMessage(sMsg,-1, true,languageList[j]);
1954 		    	}
1955 
1956 				safeMutex.ReleaseLock();
1957 				safeMutexCLI.ReleaseLock();
1958 				return;
1959 			}
1960 		}
1961 
1962 		// Tell the server Interface whether or not to publish game status updates to masterserver
1963 		serverInterface->setNeedToRepublishToMasterserver(checkBoxPublishServer.getValue() == true);
1964 
1965 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1966 		bool bOkToStart = serverInterface->launchGame(&gameSettings);
1967 		if(bOkToStart == true) {
1968 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1969 
1970 			if( checkBoxPublishServer.getEditable() &&
1971 					checkBoxPublishServer.getValue() == true) {
1972 
1973 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1974 
1975 				needToRepublishToMasterserver = true;
1976 				lastMasterserverPublishing = 0;
1977 
1978 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1979 			}
1980 			needToBroadcastServerSettings = false;
1981 			needToRepublishToMasterserver = false;
1982 			lastNetworkPing               = time(NULL);
1983 			safeMutex.ReleaseLock();
1984 			safeMutexCLI.ReleaseLock();
1985 
1986 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1987 
1988 			assert(program != NULL);
1989 
1990 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
1991 			cleanup();
1992 			Game *newGame = new Game(program, &gameSettings, this->headlessServerMode);
1993 			forceWaitForShutdown = false;
1994 			program->setState(newGame);
1995 			return;
1996 		}
1997 		else {
1998 			safeMutex.ReleaseLock();
1999 			safeMutexCLI.ReleaseLock();
2000 		}
2001 	}
2002 }
2003 
mouseMove(int x,int y,const MouseState * ms)2004 void MenuStateCustomGame::mouseMove(int x, int y, const MouseState *ms) {
2005 	if(isMasterserverMode() == true) {
2006 		return;
2007 	}
2008 
2009 	if (mainMessageBox.getEnabled()) {
2010 		mainMessageBox.mouseMove(x, y);
2011 	}
2012 	buttonReturn.mouseMove(x, y);
2013 	buttonPlayNow.mouseMove(x, y);
2014 	buttonRestoreLastSettings.mouseMove(x, y);
2015 	buttonClearBlockedPlayers.mouseMove(x, y);
2016 
2017 	for(int i = 0; i < GameConstants::maxPlayers; ++i) {
2018 		listBoxRMultiplier[i].mouseMove(x, y);
2019         listBoxControls[i].mouseMove(x, y);
2020         buttonBlockPlayers[i].mouseMove(x, y);
2021         listBoxFactions[i].mouseMove(x, y);
2022 		listBoxTeams[i].mouseMove(x, y);
2023     }
2024 
2025 	listBoxMap.mouseMove(x, y);
2026 
2027 	if(checkBoxAdvanced.getValue() == 1) {
2028 		listBoxFogOfWar.mouseMove(x, y);
2029 		checkBoxAllowObservers.mouseMove(x, y);
2030 
2031 		checkBoxEnableSwitchTeamMode.mouseMove(x, y);
2032 		listBoxAISwitchTeamAcceptPercent.mouseMove(x, y);
2033 		listBoxFallbackCpuMultiplier.mouseMove(x, y);
2034 
2035 		labelNetworkPauseGameForLaggedClients.mouseMove(x, y);
2036 		checkBoxNetworkPauseGameForLaggedClients.mouseMove(x, y);
2037 
2038 		labelAllowTeamUnitSharing.mouseMove(x,y);
2039 		checkBoxAllowTeamUnitSharing.mouseMove(x,y);
2040 		labelAllowTeamResourceSharing.mouseMove(x,y);
2041 		checkBoxAllowTeamResourceSharing.mouseMove(x,y);
2042 	}
2043 	checkBoxAllowInGameJoinPlayer.mouseMove(x, y);
2044 
2045 	checkBoxAllowNativeLanguageTechtree.mouseMove(x, y);
2046 
2047 	listBoxTileset.mouseMove(x, y);
2048 	listBoxMapFilter.mouseMove(x, y);
2049 	listBoxTechTree.mouseMove(x, y);
2050 	checkBoxPublishServer.mouseMove(x, y);
2051 
2052 	checkBoxAdvanced.mouseMove(x, y);
2053 
2054 	checkBoxScenario.mouseMove(x, y);
2055 	listBoxScenario.mouseMove(x, y);
2056 }
2057 
isMasterserverMode() const2058 bool MenuStateCustomGame::isMasterserverMode() const {
2059 	return (this->headlessServerMode == true && this->masterserverModeMinimalResources == true);
2060 	//return false;
2061 }
2062 
isVideoPlaying()2063 bool MenuStateCustomGame::isVideoPlaying() {
2064 	bool result = false;
2065 	if(factionVideo != NULL) {
2066 		result = factionVideo->isPlaying();
2067 	}
2068 	return result;
2069 }
2070 
render()2071 void MenuStateCustomGame::render() {
2072 	try {
2073 		Renderer &renderer= Renderer::getInstance();
2074 
2075 		if(mainMessageBox.getEnabled() == false) {
2076 			if(factionTexture != NULL) {
2077 				if(factionVideo == NULL || factionVideo->isPlaying() == false) {
2078 					renderer.renderTextureQuad(800,600,200,150,factionTexture,1.0f);
2079 				}
2080 			}
2081 		}
2082 		if(factionVideo != NULL) {
2083 			if(factionVideo->isPlaying() == true) {
2084 				factionVideo->playFrame(false);
2085 			}
2086 			else {
2087 				if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false &&
2088 						::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) {
2089 					if(factionVideo != NULL) {
2090 						factionVideo->closePlayer();
2091 						delete factionVideo;
2092 						factionVideo = NULL;
2093 
2094 						ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2095 						if(serverInterface != NULL) {
2096 							initFactionPreview(serverInterface->getGameSettings());
2097 						}
2098 					}
2099 				}
2100 			}
2101 		}
2102 
2103 		if(mainMessageBox.getEnabled()) {
2104 			renderer.renderMessageBox(&mainMessageBox);
2105 
2106 			renderer.renderButton(&buttonReturn);
2107 		}
2108 		else {
2109 			if(mapPreviewTexture != NULL) {
2110 				//renderer.renderTextureQuad(5,185,150,150,mapPreviewTexture,1.0f);
2111 				renderer.renderTextureQuad(	this->render_mapPreviewTexture_X,
2112 											this->render_mapPreviewTexture_Y,
2113 											this->render_mapPreviewTexture_W,
2114 											this->render_mapPreviewTexture_H,
2115 											mapPreviewTexture,1.0f);
2116 				if(this->zoomedMap==true) {
2117 					return;
2118 				}
2119 				//printf("=================> Rendering map preview texture\n");
2120 			}
2121 			if(scenarioLogoTexture != NULL) {
2122 				renderer.renderTextureQuad(300,350,400,300,scenarioLogoTexture,1.0f);
2123 				//renderer.renderBackground(scenarioLogoTexture);
2124 			}
2125 
2126 			renderer.renderButton(&buttonReturn);
2127 			renderer.renderButton(&buttonPlayNow);
2128 			renderer.renderButton(&buttonRestoreLastSettings);
2129 
2130 			// Get a reference to the player texture cache
2131 			std::map<int,Texture2D *> &crcPlayerTextureCache = CacheManager::getCachedItem< std::map<int,Texture2D *> >(GameConstants::playerTextureCacheLookupKey);
2132 
2133 			// START - this code ensure player title and player names don't overlap
2134 			int offsetPosition=0;
2135 		    for(int i=0; i < GameConstants::maxPlayers; ++i) {
2136 				FontMetrics *fontMetrics= NULL;
2137 				if(Renderer::renderText3DEnabled == false) {
2138 					fontMetrics = labelPlayers[i].getFont()->getMetrics();
2139 				}
2140 				else {
2141 					fontMetrics = labelPlayers[i].getFont3D()->getMetrics();
2142 				}
2143 				if(fontMetrics == NULL) {
2144 					throw megaglest_runtime_error("fontMetrics == NULL");
2145 				}
2146 				int curWidth = (fontMetrics->getTextWidth(labelPlayers[i].getText()));
2147 				int newOffsetPosition = labelPlayers[i].getX() + curWidth + 2;
2148 
2149 				//printf("labelPlayers[i].getX() = %d curWidth = %d labelPlayerNames[i].getX() = %d offsetPosition = %d newOffsetPosition = %d [%s]\n",labelPlayers[i].getX(),curWidth,labelPlayerNames[i].getX(),offsetPosition,newOffsetPosition,labelPlayers[i].getText().c_str());
2150 
2151 				if(labelPlayers[i].getX() + curWidth >= labelPlayerNames[i].getX()) {
2152 					if(offsetPosition < newOffsetPosition) {
2153 						offsetPosition = newOffsetPosition;
2154 					}
2155 				}
2156 		    }
2157 		    // END
2158 
2159 		    ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2160 		    if(hasNetworkGameSettings() == true) {
2161 		    	renderer.renderListBox(&listBoxPlayerStatus);
2162 		    	if( serverInterface != NULL &&
2163 		    		serverInterface->getServerSocket() != NULL ) {
2164 		    		renderer.renderButton(&buttonClearBlockedPlayers);
2165 		    	}
2166 		    }
2167 			for(int i = 0; i < GameConstants::maxPlayers; ++i) {
2168 		    	if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
2169 		    		//printf("Player #%d [%s] control = %d\n",i,labelPlayerNames[i].getText().c_str(),listBoxControls[i].getSelectedItemIndex());
2170 
2171 					labelPlayers[i].setVisible(true);
2172 					labelPlayerNames[i].setVisible(true);
2173 					listBoxControls[i].setVisible(true);
2174 					listBoxFactions[i].setVisible(true);
2175 					listBoxTeams[i].setVisible(true);
2176 					labelNetStatus[i].setVisible(true);
2177 		    	}
2178 
2179 				if( hasNetworkGameSettings() == true &&
2180 					listBoxControls[i].getSelectedItemIndex() != ctClosed) {
2181 
2182 					renderer.renderLabel(&labelPlayerStatus[i]);
2183 				}
2184 
2185 				if(crcPlayerTextureCache[i] != NULL) {
2186 					// Render the player # label the player's color
2187 					Vec3f playerColor = crcPlayerTextureCache[i]->getPixmap()->getPixel3f(0, 0);
2188 					renderer.renderLabel(&labelPlayers[i],&playerColor);
2189 				}
2190 				else {
2191 					renderer.renderLabel(&labelPlayers[i]);
2192 				}
2193 
2194 				if(offsetPosition > 0) {
2195 					labelPlayerNames[i].setX(offsetPosition);
2196 				}
2197 				renderer.renderLabel(&labelPlayerNames[i]);
2198 
2199 				renderer.renderListBox(&listBoxControls[i]);
2200 
2201 				if( hasNetworkGameSettings() == true &&
2202 					listBoxControls[i].getSelectedItemIndex() != ctClosed) {
2203 
2204 					renderer.renderLabel(&labelPlayerStatus[i]);
2205 
2206 					if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
2207 						ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2208 						if( serverInterface != NULL &&
2209 							serverInterface->getSlot(i,true) != NULL &&
2210 		                    serverInterface->getSlot(i,true)->isConnected()) {
2211 							renderer.renderButton(&buttonBlockPlayers[i]);
2212 						}
2213 					}
2214 				}
2215 
2216 				if(listBoxControls[i].getSelectedItemIndex()!=ctClosed){
2217 					renderer.renderListBox(&listBoxRMultiplier[i]);
2218 					renderer.renderListBox(&listBoxFactions[i]);
2219 
2220 					int teamnumber=listBoxTeams[i].getSelectedItemIndex();
2221 					Vec3f teamcolor=Vec3f(1.0f,1.0f,1.0f);
2222 					if(teamnumber>=0 && teamnumber<8){
2223 						teamcolor=crcPlayerTextureCache[teamnumber]->getPixmap()->getPixel3f(0, 0);
2224 					}
2225 					listBoxTeams[i].setTextColor(teamcolor);
2226 
2227 					renderer.renderListBox(&listBoxTeams[i]);
2228 					renderer.renderLabel(&labelNetStatus[i]);
2229 				}
2230 			}
2231 
2232 			renderer.renderLabel(&labelLocalGameVersion);
2233 			renderer.renderLabel(&labelLocalIP);
2234 			renderer.renderLabel(&labelMap);
2235 
2236 			if(checkBoxAdvanced.getValue() == 1) {
2237 				renderer.renderLabel(&labelFogOfWar);
2238 				renderer.renderLabel(&labelAllowObservers);
2239 				renderer.renderLabel(&labelFallbackCpuMultiplier);
2240 
2241 				renderer.renderLabel(&labelEnableSwitchTeamMode);
2242 				renderer.renderLabel(&labelAISwitchTeamAcceptPercent);
2243 
2244 				renderer.renderListBox(&listBoxFogOfWar);
2245 				renderer.renderCheckBox(&checkBoxAllowObservers);
2246 
2247 				renderer.renderCheckBox(&checkBoxEnableSwitchTeamMode);
2248 				renderer.renderListBox(&listBoxAISwitchTeamAcceptPercent);
2249 				renderer.renderListBox(&listBoxFallbackCpuMultiplier);
2250 
2251 				renderer.renderLabel(&labelAllowTeamUnitSharing);
2252 				renderer.renderCheckBox(&checkBoxAllowTeamUnitSharing);
2253 
2254 				renderer.renderLabel(&labelAllowTeamResourceSharing);
2255 				renderer.renderCheckBox(&checkBoxAllowTeamResourceSharing);
2256 			}
2257 			renderer.renderLabel(&labelAllowInGameJoinPlayer);
2258 			renderer.renderCheckBox(&checkBoxAllowInGameJoinPlayer);
2259 
2260 			renderer.renderLabel(&labelTileset);
2261 			renderer.renderLabel(&labelMapFilter);
2262 			renderer.renderLabel(&labelTechTree);
2263 			renderer.renderLabel(&labelControl);
2264 			renderer.renderLabel(&labelFaction);
2265 			renderer.renderLabel(&labelTeam);
2266 			renderer.renderLabel(&labelMapInfo);
2267 			renderer.renderLabel(&labelAdvanced);
2268 
2269 			renderer.renderListBox(&listBoxMap);
2270 			renderer.renderListBox(&listBoxTileset);
2271 			renderer.renderListBox(&listBoxMapFilter);
2272 			renderer.renderListBox(&listBoxTechTree);
2273 			renderer.renderCheckBox(&checkBoxAdvanced);
2274 
2275 			if(checkBoxPublishServer.getEditable())
2276 			{
2277 				renderer.renderCheckBox(&checkBoxPublishServer);
2278 				renderer.renderLabel(&labelPublishServer);
2279 				renderer.renderLabel(&labelGameName);
2280 				if(checkBoxAdvanced.getValue() == 1) {
2281 					renderer.renderLabel(&labelNetworkPauseGameForLaggedClients);
2282 					renderer.renderCheckBox(&checkBoxNetworkPauseGameForLaggedClients);
2283 				}
2284 			}
2285 
2286 			renderer.renderCheckBox(&checkBoxScenario);
2287 			renderer.renderLabel(&labelScenario);
2288 			if(checkBoxScenario.getValue() == true) {
2289 				renderer.renderListBox(&listBoxScenario);
2290 			}
2291 
2292 			renderer.renderLabel(&labelAllowNativeLanguageTechtree);
2293 			renderer.renderCheckBox(&checkBoxAllowNativeLanguageTechtree);
2294 		}
2295 
2296 		if(program != NULL) program->renderProgramMsgBox();
2297 
2298 		if( enableMapPreview == true &&
2299 			mapPreview.hasFileLoaded() == true) {
2300 
2301 		    if(mapPreviewTexture == NULL) {
2302 		    	bool renderAll = (listBoxFogOfWar.getSelectedItemIndex() == 2);
2303 		    	//printf("=================> Rendering map preview into a texture BEFORE (%p)\n", mapPreviewTexture);
2304 
2305 		    	//renderer.renderMapPreview(&mapPreview, renderAll, 10, 350,&mapPreviewTexture);
2306 		    	renderer.renderMapPreview(&mapPreview, renderAll,
2307 		    			this->render_mapPreviewTexture_X,
2308 		    			this->render_mapPreviewTexture_Y,
2309 		    			&mapPreviewTexture);
2310 
2311 		    	//printf("=================> Rendering map preview into a texture AFTER (%p)\n", mapPreviewTexture);
2312 		    }
2313 		}
2314 
2315 		if(mainMessageBox.getEnabled() == false) {
2316 			if(hasNetworkGameSettings() == true) {
2317 				renderer.renderChatManager(&chatManager);
2318 			}
2319 		}
2320 		renderer.renderConsole(&console,showFullConsole?consoleFull:consoleStoredAndNormal);
2321 	}
2322 	catch(const std::exception &ex) {
2323 		char szBuf[8096]="";
2324 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
2325 		//throw megaglest_runtime_error(szBuf);
2326 
2327 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
2328 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
2329 		showGeneralError=true;
2330 		generalErrorToShow = szBuf;
2331 	}
2332 }
2333 
switchSetupForSlots(SwitchSetupRequest ** switchSetupRequests,ServerInterface * & serverInterface,int startIndex,int endIndex,bool onlyNetworkUnassigned)2334 void MenuStateCustomGame::switchSetupForSlots(SwitchSetupRequest **switchSetupRequests,
2335 		ServerInterface *& serverInterface, int startIndex, int endIndex, bool onlyNetworkUnassigned) {
2336     for(int i= startIndex; i < endIndex; ++i) {
2337 		if(switchSetupRequests[i] != NULL) {
2338 			//printf("Switch slot = %d control = %d newIndex = %d currentindex = %d onlyNetworkUnassigned = %d\n",i,listBoxControls[i].getSelectedItemIndex(),switchSetupRequests[i]->getToFactionIndex(),switchSetupRequests[i]->getCurrentFactionIndex(),onlyNetworkUnassigned);
2339 
2340 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] switchSetupRequests[i]->getSwitchFlags() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,switchSetupRequests[i]->getSwitchFlags());
2341 
2342 			if(onlyNetworkUnassigned == true && listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) {
2343 				if(i < mapInfo.players || (i >= mapInfo.players && listBoxControls[i].getSelectedItemIndex() != ctNetwork)) {
2344 					continue;
2345 				}
2346 			}
2347 
2348 			if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
2349 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] switchSetupRequests[i]->getToFactionIndex() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,switchSetupRequests[i]->getToSlotIndex());
2350 
2351 				if(switchSetupRequests[i]->getToSlotIndex() != -1) {
2352 					int newFactionIdx = switchSetupRequests[i]->getToSlotIndex();
2353 
2354 					//printf("switchSlot request from %d to %d\n",switchSetupRequests[i]->getCurrentFactionIndex(),switchSetupRequests[i]->getToFactionIndex());
2355 					int switchFactionIdx = switchSetupRequests[i]->getCurrentSlotIndex();
2356 					if(serverInterface->switchSlot(switchFactionIdx,newFactionIdx)) {
2357 						try {
2358 							ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2359 							ConnectionSlot *slot = serverInterface->getSlot(newFactionIdx,true);
2360 
2361 							if(switchSetupRequests[i]->getSelectedFactionName() != "" &&
2362 								(slot != NULL &&
2363 								 switchSetupRequests[i]->getSelectedFactionName() != Lang::getInstance().getString("DataMissing",slot->getNetworkPlayerLanguage(),true) &&
2364 								 switchSetupRequests[i]->getSelectedFactionName() != "???DataMissing???")) {
2365 								listBoxFactions[newFactionIdx].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName());
2366 							}
2367 							if(switchSetupRequests[i]->getToTeam() != -1) {
2368 								listBoxTeams[newFactionIdx].setSelectedItemIndex(switchSetupRequests[i]->getToTeam());
2369 							}
2370 							if(switchSetupRequests[i]->getNetworkPlayerName() != "") {
2371 								if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] i = %d, labelPlayerNames[newFactionIdx].getText() [%s] switchSetupRequests[i]->getNetworkPlayerName() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,labelPlayerNames[newFactionIdx].getText().c_str(),switchSetupRequests[i]->getNetworkPlayerName().c_str());
2372 								labelPlayerNames[newFactionIdx].setText(switchSetupRequests[i]->getNetworkPlayerName());
2373 							}
2374 
2375 							if(listBoxControls[switchFactionIdx].getSelectedItemIndex() == ctNetworkUnassigned) {
2376 								serverInterface->removeSlot(switchFactionIdx);
2377 								listBoxControls[switchFactionIdx].setSelectedItemIndex(ctClosed);
2378 
2379 								labelPlayers[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players);
2380 								labelPlayerNames[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players);
2381 						        listBoxControls[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players);
2382 						        listBoxFactions[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players);
2383 								listBoxTeams[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players);
2384 								labelNetStatus[switchFactionIdx].setVisible(switchFactionIdx+1 <= mapInfo.players);
2385 							}
2386 						}
2387 						catch(const runtime_error &e) {
2388 							SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
2389 							if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] caught exception error = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
2390 						}
2391 					}
2392 				}
2393 				else {
2394 					try {
2395 						int factionIdx = switchSetupRequests[i]->getCurrentSlotIndex();
2396 						ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2397 						ConnectionSlot *slot = serverInterface->getSlot(factionIdx,true);
2398 
2399 						if(switchSetupRequests[i]->getSelectedFactionName() != "" &&
2400 							(slot != NULL &&
2401 							 switchSetupRequests[i]->getSelectedFactionName() != Lang::getInstance().getString("DataMissing",slot->getNetworkPlayerLanguage(),true) &&
2402 							 switchSetupRequests[i]->getSelectedFactionName() != "???DataMissing???")) {
2403 							listBoxFactions[i].setSelectedItem(switchSetupRequests[i]->getSelectedFactionName());
2404 						}
2405 						if(switchSetupRequests[i]->getToTeam() != -1) {
2406 							listBoxTeams[i].setSelectedItemIndex(switchSetupRequests[i]->getToTeam());
2407 						}
2408 
2409 						if((switchSetupRequests[i]->getSwitchFlags() & ssrft_NetworkPlayerName) == ssrft_NetworkPlayerName) {
2410 							if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, switchSetupRequests[i]->getSwitchFlags() = %d, switchSetupRequests[i]->getNetworkPlayerName() [%s], labelPlayerNames[i].getText() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,switchSetupRequests[i]->getSwitchFlags(),switchSetupRequests[i]->getNetworkPlayerName().c_str(),labelPlayerNames[i].getText().c_str());
2411 
2412 							if(switchSetupRequests[i]->getNetworkPlayerName() != GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) {
2413 								labelPlayerNames[i].setText(switchSetupRequests[i]->getNetworkPlayerName());
2414 							}
2415 							else {
2416 								labelPlayerNames[i].setText("");
2417 							}
2418 						}
2419 					}
2420 					catch(const runtime_error &e) {
2421 						SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
2422 						if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] caught exception error = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what());
2423 					}
2424 				}
2425 			}
2426 
2427 			delete switchSetupRequests[i];
2428 			switchSetupRequests[i]=NULL;
2429 		}
2430 	}
2431 }
2432 
update()2433 void MenuStateCustomGame::update() {
2434 	Chrono chrono;
2435 	if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start();
2436 
2437 	// Test openal buffer underrun issue
2438 	//sleep(200);
2439 	// END
2440 
2441 	MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
2442 	MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
2443 
2444 	try {
2445 		if(serverInitError == true) {
2446 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
2447 
2448 			if(showGeneralError) {
2449 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
2450 
2451 
2452 				showGeneralError=false;
2453 				mainMessageBoxState=1;
2454 				showMessageBox( generalErrorToShow, "Error", false);
2455 			}
2456 
2457 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
2458 
2459 			if(this->headlessServerMode == false) {
2460 				return;
2461 			}
2462 		}
2463 		ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2464 		Lang& lang= Lang::getInstance();
2465 
2466 		if( serverInterface != NULL && serverInterface->getServerSocket() != NULL ){
2467 			buttonClearBlockedPlayers.setEditable( serverInterface->getServerSocket()->hasBlockedIPAddresses());
2468 		}
2469 
2470 		if(this->autoloadScenarioName != "") {
2471 			listBoxScenario.setSelectedItem(formatString(this->autoloadScenarioName),false);
2472 			lastSetChangedGameSettings = time(NULL);
2473 			if(serverInterface != NULL){
2474 				lastGameSettingsreceivedCount=serverInterface->getGameSettingsUpdateCount();
2475 			}
2476 			if(listBoxScenario.getSelectedItem() != formatString(this->autoloadScenarioName)) {
2477 				mainMessageBoxState=1;
2478 				showMessageBox( "Could not find scenario name: " + formatString(this->autoloadScenarioName), "Scenario Missing", false);
2479 				this->autoloadScenarioName = "";
2480 			}
2481 			else {
2482 				loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), &scenarioInfo);
2483 				//labelInfo.setText(scenarioInfo.desc);
2484 
2485 				SoundRenderer &soundRenderer= SoundRenderer::getInstance();
2486 				CoreData &coreData= CoreData::getInstance();
2487 				soundRenderer.playFx(coreData.getClickSoundC());
2488 				//launchGame();
2489 				PlayNow(true);
2490 				return;
2491 			}
2492 		}
2493 
2494 		if(needToLoadTextures) {
2495 			// this delay is done to make it possible to switch faster
2496 			if(difftime((long int)time(NULL), previewLoadDelayTimer) >= 2){
2497 				//loadScenarioPreviewTexture();
2498 				needToLoadTextures= false;
2499 			}
2500 		}
2501 
2502 		//bool haveAtLeastOneNetworkClientConnected = false;
2503 		bool hasOneNetworkSlotOpen = false;
2504 		int currentConnectionCount=0;
2505 		Config &config = Config::getInstance();
2506 
2507 		bool masterServerErr = showMasterserverError;
2508 
2509 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2510 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2511 
2512 		if(masterServerErr) {
2513 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
2514 
2515 			if(EndsWith(masterServererErrorToShow, "wrong router setup") == true) {
2516 				masterServererErrorToShow=lang.getString("WrongRouterSetup");
2517 			}
2518 
2519 			Lang &lang= Lang::getInstance();
2520 			string publishText = " (disabling publish)";
2521 			if(lang.hasString("PublishDisabled") == true) {
2522 				publishText = lang.getString("PublishDisabled");
2523 			}
2524 
2525             masterServererErrorToShow += "\n\n"+ publishText;
2526 			showMasterserverError=false;
2527 			mainMessageBoxState=1;
2528 			showMessageBox( masterServererErrorToShow, lang.getString("ErrorFromMasterserver"), false);
2529 
2530 			if(this->headlessServerMode == false) {
2531 				checkBoxPublishServer.setValue(false);
2532 			}
2533 
2534             ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2535             serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == true);
2536 		}
2537 		else if(showGeneralError) {
2538 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
2539 
2540 			showGeneralError=false;
2541 			mainMessageBoxState=1;
2542 			showMessageBox( generalErrorToShow, "Error", false);
2543 		}
2544 
2545 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2546 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2547 
2548 		if(this->headlessServerMode == true && serverInterface == NULL) {
2549 			throw megaglest_runtime_error("serverInterface == NULL");
2550 		}
2551 		if(this->headlessServerMode == true && serverInterface->getGameSettingsUpdateCount() > lastMasterServerSettingsUpdateCount &&
2552 				serverInterface->getGameSettings() != NULL) {
2553 			const GameSettings *settings = serverInterface->getGameSettings();
2554 			//printf("\n\n\n\n=====#1 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),settings->toString().c_str());
2555 
2556 			lastMasterServerSettingsUpdateCount = serverInterface->getGameSettingsUpdateCount();
2557 			//printf("#2 custom menu got map [%s]\n",settings->getMap().c_str());
2558 
2559 			setupUIFromGameSettings(*settings);
2560 			printf("received Settings map filter=%d\n",settings->getMapFilter());
2561 
2562             GameSettings gameSettings;
2563             loadGameSettings(&gameSettings);
2564 
2565             //printf("\n\n\n\n=====#1.1 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),gameSettings.toString().c_str());
2566 
2567 		}
2568 		if(this->headlessServerMode == true && serverInterface->getMasterserverAdminRequestLaunch() == true) {
2569 			serverInterface->setMasterserverAdminRequestLaunch(false);
2570 			safeMutex.ReleaseLock();
2571 			safeMutexCLI.ReleaseLock();
2572 
2573 			PlayNow(false);
2574 			return;
2575 		}
2576 
2577 		// handle setting changes from clients
2578 		SwitchSetupRequest ** switchSetupRequests = serverInterface->getSwitchSetupRequests();
2579 		//!!!
2580 		switchSetupForSlots(switchSetupRequests, serverInterface, 0, mapInfo.players, false);
2581 		switchSetupForSlots(switchSetupRequests, serverInterface, mapInfo.players, GameConstants::maxPlayers, true);
2582 
2583 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2584 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2585 
2586 		GameSettings gameSettings;
2587 		loadGameSettings(&gameSettings);
2588 
2589 		listBoxAISwitchTeamAcceptPercent.setEnabled(checkBoxEnableSwitchTeamMode.getValue());
2590 
2591 		int factionCount = 0;
2592 		for(int i= 0; i< mapInfo.players; ++i) {
2593 			if(hasNetworkGameSettings() == true) {
2594 				if(listBoxControls[i].getSelectedItemIndex() != ctClosed) {
2595 					int slotIndex = factionCount;
2596 					if(listBoxControls[i].getSelectedItemIndex() == ctHuman) {
2597 						switch(gameSettings.getNetworkPlayerStatuses(slotIndex)) {
2598 							case npst_BeRightBack:
2599 								labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusBRBTexture());
2600 								break;
2601 							case npst_Ready:
2602 								labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusReadyTexture());
2603 								break;
2604 							case npst_PickSettings:
2605 								labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusNotReadyTexture());
2606 								break;
2607 							case npst_Disconnected:
2608 								labelPlayerStatus[i].setTexture(NULL);
2609 								break;
2610 
2611 							default:
2612 								labelPlayerStatus[i].setTexture(NULL);
2613 								break;
2614 						}
2615 					}
2616 					else {
2617 						labelPlayerStatus[i].setTexture(NULL);
2618 					}
2619 
2620 					factionCount++;
2621 				}
2622 				else {
2623 					labelPlayerStatus[i].setTexture(NULL);
2624 				}
2625 			}
2626 
2627 			if(listBoxControls[i].getSelectedItemIndex() == ctNetwork ||
2628 				listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
2629 				hasOneNetworkSlotOpen=true;
2630 
2631 				if(serverInterface->getSlot(i,true) != NULL &&
2632                    serverInterface->getSlot(i,true)->isConnected()) {
2633 
2634 					if(hasNetworkGameSettings() == true) {
2635 						switch(serverInterface->getSlot(i,true)->getNetworkPlayerStatus()) {
2636 							case npst_BeRightBack:
2637 								labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusBRBTexture());
2638 								break;
2639 							case npst_Ready:
2640 								labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusReadyTexture());
2641 								break;
2642 							case npst_PickSettings:
2643 							default:
2644 								labelPlayerStatus[i].setTexture(CoreData::getInstance().getStatusNotReadyTexture());
2645 								break;
2646 						}
2647 					}
2648 
2649 					serverInterface->getSlot(i,true)->setName(labelPlayerNames[i].getText());
2650 
2651 					//printf("FYI we have at least 1 client connected, slot = %d'\n",i);
2652 
2653 					//haveAtLeastOneNetworkClientConnected = true;
2654 					if(serverInterface->getSlot(i,true) != NULL &&
2655                        serverInterface->getSlot(i,true)->getConnectHasHandshaked()) {
2656 						currentConnectionCount++;
2657                     }
2658 					string label = (serverInterface->getSlot(i,true) != NULL ? serverInterface->getSlot(i,true)->getVersionString() : "");
2659 
2660 					if(serverInterface->getSlot(i,true) != NULL &&
2661 					   serverInterface->getSlot(i,true)->getAllowDownloadDataSynch() == true &&
2662 					   serverInterface->getSlot(i,true)->getAllowGameDataSynchCheck() == true) {
2663 						if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOk() == false) {
2664 							label += " -waiting to synch:";
2665 							if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkMap() == false) {
2666 								label = label + " map";
2667 							}
2668 							if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTile() == false) {
2669 								label = label + " tile";
2670 							}
2671 							if(serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTech() == false) {
2672 								label = label + " techtree";
2673 							}
2674 						}
2675 						else {
2676 							label += " - data synch is ok";
2677 						}
2678 					}
2679 					else {
2680 						if(serverInterface->getSlot(i,true) != NULL &&
2681 						   serverInterface->getSlot(i,true)->getAllowGameDataSynchCheck() == true &&
2682 						   serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOk() == false) {
2683 							label += " -synch mismatch:";
2684 
2685 							if(serverInterface->getSlot(i,true) != NULL && serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkMap() == false) {
2686 								label = label + " map";
2687 
2688 								if(serverInterface->getSlot(i,true)->getReceivedDataSynchCheck() == true &&
2689 									lastMapDataSynchError != "map CRC mismatch, " + listBoxMap.getSelectedItem()) {
2690 									lastMapDataSynchError = "map CRC mismatch, " + listBoxMap.getSelectedItem();
2691 									ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2692 									serverInterface->sendTextMessage(lastMapDataSynchError,-1, true,"");
2693 								}
2694 							}
2695 
2696 							if(serverInterface->getSlot(i,true) != NULL &&
2697                                serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTile() == false) {
2698 								label = label + " tile";
2699 
2700 								if(serverInterface->getSlot(i,true)->getReceivedDataSynchCheck() == true &&
2701 									lastTileDataSynchError != "tile CRC mismatch, " + listBoxTileset.getSelectedItem()) {
2702 									lastTileDataSynchError = "tile CRC mismatch, " + listBoxTileset.getSelectedItem();
2703 									ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2704 									serverInterface->sendTextMessage(lastTileDataSynchError,-1,true,"");
2705 								}
2706 							}
2707 
2708 							if(serverInterface->getSlot(i,true) != NULL &&
2709                                serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckOkTech() == false) {
2710 								label = label + " techtree";
2711 
2712 								if(serverInterface->getSlot(i,true)->getReceivedDataSynchCheck() == true) {
2713 									ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2714 									string report = serverInterface->getSlot(i,true)->getNetworkGameDataSynchCheckTechMismatchReport();
2715 
2716 									if(lastTechtreeDataSynchError != "techtree CRC mismatch" + report) {
2717 										lastTechtreeDataSynchError = "techtree CRC mismatch" + report;
2718 
2719 										if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] report: %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,report.c_str());
2720 
2721 										serverInterface->sendTextMessage("techtree CRC mismatch",-1,true,"");
2722 										vector<string> reportLineTokens;
2723 										Tokenize(report,reportLineTokens,"\n");
2724 										for(int reportLine = 0; reportLine < (int)reportLineTokens.size(); ++reportLine) {
2725 											serverInterface->sendTextMessage(reportLineTokens[reportLine],-1,true,"");
2726 										}
2727 									}
2728 								}
2729 							}
2730 
2731 							if(serverInterface->getSlot(i,true) != NULL) {
2732 								serverInterface->getSlot(i,true)->setReceivedDataSynchCheck(false);
2733 							}
2734 						}
2735 					}
2736 
2737 					//float pingTime = serverInterface->getSlot(i)->getThreadedPingMS(serverInterface->getSlot(i)->getIpAddress().c_str());
2738 					char szBuf[8096]="";
2739 					snprintf(szBuf,8096,"%s",label.c_str());
2740 
2741 					labelNetStatus[i].setText(szBuf);
2742 				}
2743 				else {
2744 					string port = "("+intToStr(config.getInt("PortServer"))+")";
2745 					labelNetStatus[i].setText("--- " + port);
2746 				}
2747 			}
2748 			else{
2749 				labelNetStatus[i].setText("");
2750 			}
2751 		}
2752 
2753 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2754 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2755 
2756 		//ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2757 
2758 		if(checkBoxScenario.getValue() == false) {
2759 			for(int i= 0; i< GameConstants::maxPlayers; ++i) {
2760 				if(i >= mapInfo.players) {
2761 					listBoxControls[i].setEditable(false);
2762 					listBoxControls[i].setEnabled(false);
2763 
2764 					//printf("In [%s::%s] Line: %d i = %d mapInfo.players = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players);
2765 				}
2766 				else if(listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) {
2767 					ConnectionSlot *slot = serverInterface->getSlot(i,true);
2768 					if((listBoxControls[i].getSelectedItemIndex() != ctNetwork) ||
2769 						(listBoxControls[i].getSelectedItemIndex() == ctNetwork && (slot == NULL || slot->isConnected() == false))) {
2770 						listBoxControls[i].setEditable(true);
2771 						listBoxControls[i].setEnabled(true);
2772 					}
2773 					else {
2774 						listBoxControls[i].setEditable(false);
2775 						listBoxControls[i].setEnabled(false);
2776 
2777 						//printf("In [%s::%s] Line: %d i = %d mapInfo.players = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players);
2778 					}
2779 				}
2780 				else {
2781 					listBoxControls[i].setEditable(false);
2782 					listBoxControls[i].setEnabled(false);
2783 
2784 					//printf("In [%s::%s] Line: %d i = %d mapInfo.players = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,mapInfo.players);
2785 				}
2786 			}
2787 		}
2788 
2789 		bool checkDataSynch = (serverInterface->getAllowGameDataSynchCheck() == true &&
2790 					needToSetChangedGameSettings == true &&
2791 					(( difftime((long int)time(NULL),lastSetChangedGameSettings) >= BROADCAST_SETTINGS_SECONDS)||
2792 					(this->headlessServerMode == true)));
2793 
2794 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2795 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2796 
2797 		// Send the game settings to each client if we have at least one networked client
2798 		if(checkDataSynch == true) {
2799 			serverInterface->setGameSettings(&gameSettings,false);
2800 			needToSetChangedGameSettings    = false;
2801 		}
2802 
2803 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2804 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2805 
2806 		if(this->headlessServerMode == true || hasOneNetworkSlotOpen == true ||
2807 				checkBoxAllowInGameJoinPlayer.getValue() == true) {
2808 			if(this->headlessServerMode == true &&
2809 					GlobalStaticFlags::isFlagSet(gsft_lan_mode) == false) {
2810 				checkBoxPublishServer.setValue(true);
2811 			}
2812 			listBoxFallbackCpuMultiplier.setEditable(true);
2813 			checkBoxPublishServer.setEditable(true);
2814 
2815 			// Masterserver always needs one network slot
2816 			if(this->headlessServerMode == true && hasOneNetworkSlotOpen == false) {
2817 				bool anyoneConnected = false;
2818 				for(int i= 0; i < mapInfo.players; ++i) {
2819 					MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
2820 
2821 					ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2822 					ConnectionSlot *slot = serverInterface->getSlot(i,true);
2823 					if(slot != NULL && slot->isConnected() == true) {
2824 						anyoneConnected = true;
2825 						break;
2826 					}
2827 				}
2828 
2829 				for(int i= 0; i < mapInfo.players; ++i) {
2830 					if(anyoneConnected == false && listBoxControls[i].getSelectedItemIndex() != ctNetwork) {
2831 						listBoxControls[i].setSelectedItemIndex(ctNetwork);
2832 					}
2833 				}
2834 
2835 				updateNetworkSlots();
2836 			}
2837 		}
2838 		else {
2839 			checkBoxPublishServer.setValue(false);
2840 			checkBoxPublishServer.setEditable(false);
2841 			listBoxFallbackCpuMultiplier.setEditable(false);
2842 			listBoxFallbackCpuMultiplier.setSelectedItem("1.0");
2843 
2844             ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2845             serverInterface->setPublishEnabled(checkBoxPublishServer.getValue() == true);
2846 		}
2847 
2848 		bool republishToMaster = (difftime((long int)time(NULL),lastMasterserverPublishing) >= MASTERSERVER_BROADCAST_PUBLISH_SECONDS);
2849 
2850 		if(republishToMaster == true) {
2851 			if(checkBoxPublishServer.getValue() == true) {
2852 				needToRepublishToMasterserver = true;
2853 				lastMasterserverPublishing = time(NULL);
2854 			}
2855 		}
2856 
2857 		bool callPublishNow = (checkBoxPublishServer.getEditable() &&
2858 								checkBoxPublishServer.getValue() == true &&
2859 							   needToRepublishToMasterserver == true);
2860 
2861 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2862 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2863 
2864 		if(callPublishNow == true) {
2865 			// give it to me baby, aha aha ...
2866 			publishToMasterserver();
2867 		}
2868 		if(needToPublishDelayed) {
2869 			// this delay is done to make it possible to switch over maps which are not meant to be distributed
2870 			if((difftime((long int)time(NULL), mapPublishingDelayTimer) >= BROADCAST_MAP_DELAY_SECONDS) ||
2871 					(this->headlessServerMode == true)	){
2872 				// after 5 seconds we are allowed to publish again!
2873 				needToSetChangedGameSettings = true;
2874 				lastSetChangedGameSettings   = time(NULL);
2875 				// set to normal....
2876 				needToPublishDelayed=false;
2877 			}
2878 		}
2879 		if(needToPublishDelayed == false || headlessServerMode == true) {
2880 			bool broadCastSettings = (difftime((long int)time(NULL),lastSetChangedGameSettings) >= BROADCAST_SETTINGS_SECONDS);
2881 
2882 			if(headlessServerMode==true){
2883 				// publish settings directly when we receive them
2884 				ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2885 				if(lastGameSettingsreceivedCount<serverInterface->getGameSettingsUpdateCount()){
2886 					needToBroadcastServerSettings=true;
2887 					lastSetChangedGameSettings = time(NULL);
2888 					lastGameSettingsreceivedCount=serverInterface->getGameSettingsUpdateCount();
2889 				}
2890 			}
2891 
2892 			if(broadCastSettings == true) {
2893 				needToBroadcastServerSettings=true;
2894 				lastSetChangedGameSettings = time(NULL);
2895 			}
2896 
2897 			if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2898 			if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2899 
2900 			//broadCastSettings = (difftime(time(NULL),lastSetChangedGameSettings) >= 2);
2901 			//if (broadCastSettings == true) {// reset timer here on bottom becasue used for different things
2902 			//	lastSetChangedGameSettings = time(NULL);
2903 			//}
2904 		}
2905 
2906 		if(this->headlessServerMode == true) {
2907 			lastPlayerDisconnected();
2908 		}
2909 
2910 		//call the chat manager
2911 		chatManager.updateNetwork();
2912 
2913 		//console
2914 		console.update();
2915 
2916 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
2917 
2918 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2919 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2920 
2921 		if(currentConnectionCount > soundConnectionCount){
2922 			soundConnectionCount = currentConnectionCount;
2923 			SoundRenderer::getInstance().playFx(CoreData::getInstance().getAttentionSound());
2924 			//switch on music again!!
2925 			Config &config = Config::getInstance();
2926 			float configVolume = (config.getInt("SoundVolumeMusic") / 100.f);
2927 			CoreData::getInstance().getMenuMusic()->setVolume(configVolume);
2928 		}
2929 		soundConnectionCount = currentConnectionCount;
2930 
2931 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2932 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2933 
2934 		if(enableFactionTexturePreview == true) {
2935 			if( currentTechName_factionPreview != gameSettings.getTech() ||
2936 				currentFactionName_factionPreview != gameSettings.getFactionTypeName(gameSettings.getThisFactionIndex())) {
2937 
2938 				currentTechName_factionPreview=gameSettings.getTech();
2939 				currentFactionName_factionPreview=gameSettings.getFactionTypeName(gameSettings.getThisFactionIndex());
2940 
2941 				initFactionPreview(&gameSettings);
2942 			}
2943 		}
2944 
2945 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis());
2946 		if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start();
2947 
2948 		if(autostart == true) {
2949 			autostart = false;
2950 			safeMutex.ReleaseLock();
2951 			safeMutexCLI.ReleaseLock();
2952 			if(autoStartSettings != NULL) {
2953 
2954 				setupUIFromGameSettings(*autoStartSettings);
2955 				ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
2956 				serverInterface->setGameSettings(autoStartSettings,false);
2957 			}
2958 			else {
2959 				RestoreLastGameSettings();
2960 			}
2961 			PlayNow((autoStartSettings == NULL));
2962 			return;
2963 		}
2964 	}
2965     catch(megaglest_runtime_error& ex) {
2966     	//abort();
2967     	//printf("1111111bbbb ex.wantStackTrace() = %d\n",ex.wantStackTrace());
2968 		char szBuf[8096]="";
2969 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
2970 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
2971 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
2972 
2973 		//printf("2222222bbbb ex.wantStackTrace() = %d\n",ex.wantStackTrace());
2974 
2975 		showGeneralError=true;
2976 		generalErrorToShow = szBuf;
2977     }
2978 	catch(const std::exception &ex) {
2979 		char szBuf[8096]="";
2980 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
2981 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
2982 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
2983 
2984 		showGeneralError=true;
2985 		generalErrorToShow = szBuf;
2986 	}
2987 }
2988 
initFactionPreview(const GameSettings * gameSettings)2989 void MenuStateCustomGame::initFactionPreview(const GameSettings *gameSettings) {
2990 	string factionVideoUrl = "";
2991 	string factionVideoUrlFallback = "";
2992 
2993 	string factionDefinitionXML = Game::findFactionLogoFile(gameSettings, NULL,currentFactionName_factionPreview + ".xml");
2994 	if(factionDefinitionXML != "" && currentFactionName_factionPreview != GameConstants::RANDOMFACTION_SLOTNAME &&
2995 			currentFactionName_factionPreview != GameConstants::OBSERVER_SLOTNAME && fileExists(factionDefinitionXML) == true) {
2996 		XmlTree	xmlTree;
2997 		std::map<string,string> mapExtraTagReplacementValues;
2998 		xmlTree.load(factionDefinitionXML, Properties::getTagReplacementValues(&mapExtraTagReplacementValues));
2999 		const XmlNode *factionNode= xmlTree.getRootNode();
3000 		if(factionNode->hasAttribute("faction-preview-video") == true) {
3001 			factionVideoUrl = factionNode->getAttribute("faction-preview-video")->getValue();
3002 		}
3003 
3004 		factionVideoUrlFallback = Game::findFactionLogoFile(gameSettings, NULL,"preview_video.*");
3005 		if(factionVideoUrl == "") {
3006 			factionVideoUrl = factionVideoUrlFallback;
3007 			factionVideoUrlFallback = "";
3008 		}
3009 	}
3010 	//printf("currentFactionName_factionPreview [%s] random [%s] observer [%s] factionVideoUrl [%s]\n",currentFactionName_factionPreview.c_str(),GameConstants::RANDOMFACTION_SLOTNAME,GameConstants::OBSERVER_SLOTNAME,factionVideoUrl.c_str());
3011 
3012 
3013 	if(factionVideoUrl != "") {
3014 		//SoundRenderer &soundRenderer= SoundRenderer::getInstance();
3015 		if(CoreData::getInstance().getMenuMusic()->getVolume() != 0) {
3016 			CoreData::getInstance().getMenuMusic()->setVolume(0);
3017 			factionVideoSwitchedOffVolume=true;
3018 		}
3019 
3020 		if(currentFactionLogo != factionVideoUrl) {
3021 			currentFactionLogo = factionVideoUrl;
3022 			if(GlobalStaticFlags::getIsNonGraphicalModeEnabled() == false &&
3023 					::Shared::Graphics::VideoPlayer::hasBackEndVideoPlayer() == true) {
3024 
3025 				if(factionVideo != NULL) {
3026 					factionVideo->closePlayer();
3027 					delete factionVideo;
3028 					factionVideo = NULL;
3029 				}
3030 				string introVideoFile = factionVideoUrl;
3031 				string introVideoFileFallback = factionVideoUrlFallback;
3032 
3033 				Context *c= GraphicsInterface::getInstance().getCurrentContext();
3034 				SDL_Window *window = static_cast<ContextGl*>(c)->getPlatformContextGlPtr()->getScreenWindow();
3035 				SDL_Surface *screen = static_cast<ContextGl*>(c)->getPlatformContextGlPtr()->getScreenSurface();
3036 
3037 				string vlcPluginsPath = Config::getInstance().getString("VideoPlayerPluginsPath","");
3038 				//printf("screen->w = %d screen->h = %d screen->format->BitsPerPixel = %d\n",screen->w,screen->h,screen->format->BitsPerPixel);
3039 				factionVideo = new VideoPlayer(
3040 						&Renderer::getInstance(),
3041 						introVideoFile,
3042 						introVideoFileFallback,
3043 						window,
3044 						0,0,
3045 						screen->w,
3046 						screen->h,
3047 						screen->format->BitsPerPixel,
3048 						true,
3049 						vlcPluginsPath,
3050 						SystemFlags::VERBOSE_MODE_ENABLED);
3051 				factionVideo->initPlayer();
3052 			}
3053 		}
3054 	}
3055 	else {
3056 		//SoundRenderer &soundRenderer= SoundRenderer::getInstance();
3057 		//switch on music again!!
3058 		Config &config = Config::getInstance();
3059 		float configVolume = (config.getInt("SoundVolumeMusic") / 100.f);
3060 		if(factionVideoSwitchedOffVolume){
3061 			if(CoreData::getInstance().getMenuMusic()->getVolume() != configVolume) {
3062 				CoreData::getInstance().getMenuMusic()->setVolume(configVolume);
3063 			}
3064 			factionVideoSwitchedOffVolume=false;
3065 		}
3066 
3067 		if(factionVideo != NULL) {
3068 			factionVideo->closePlayer();
3069 			delete factionVideo;
3070 			factionVideo = NULL;
3071 		}
3072 	}
3073 
3074 	if(factionVideo == NULL) {
3075 		string factionLogo = Game::findFactionLogoFile(gameSettings, NULL,GameConstants::PREVIEW_SCREEN_FILE_FILTER);
3076 		if(factionLogo == "") {
3077 			factionLogo = Game::findFactionLogoFile(gameSettings, NULL);
3078 		}
3079 		if(currentFactionLogo != factionLogo) {
3080 			currentFactionLogo = factionLogo;
3081 			loadFactionTexture(currentFactionLogo);
3082 		}
3083 	}
3084 }
3085 
publishToMasterserver()3086 void MenuStateCustomGame::publishToMasterserver() {
3087 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3088 
3089 	int slotCountUsed=0;
3090 	int slotCountHumans=0;
3091 	int slotCountConnectedPlayers=0;
3092 	ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
3093 	GameSettings gameSettings;
3094 	loadGameSettings(&gameSettings);
3095 	Config &config= Config::getInstance();
3096 	//string serverinfo="";
3097 
3098 	MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
3099 
3100 	publishToServerInfo.clear();
3101 
3102 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3103 
3104 	for(int i= 0; i < mapInfo.players; ++i) {
3105 		if(listBoxControls[i].getSelectedItemIndex() != ctClosed) {
3106 			slotCountUsed++;
3107 		}
3108 
3109 		if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned)
3110 		{
3111 			slotCountHumans++;
3112 			if(serverInterface->getSlot(i,true) != NULL &&
3113                serverInterface->getSlot(i,true)->isConnected()) {
3114 				slotCountConnectedPlayers++;
3115 			}
3116 		}
3117 		else if(listBoxControls[i].getSelectedItemIndex() == ctHuman) {
3118 			slotCountHumans++;
3119 			slotCountConnectedPlayers++;
3120 		}
3121 	}
3122 
3123 	publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId","");
3124 
3125 	//?status=waiting&system=linux&info=titus
3126 	publishToServerInfo["glestVersion"] = glestVersionString;
3127 	publishToServerInfo["platform"] = getPlatformNameString() + "-" + getGITRevisionString();
3128     publishToServerInfo["binaryCompileDate"] = getCompileDateTime();
3129 
3130 	//game info:
3131 	publishToServerInfo["serverTitle"] = gameSettings.getGameName();
3132 	//ip is automatically set
3133 
3134 	//game setup info:
3135 
3136 	//publishToServerInfo["tech"] = listBoxTechTree.getSelectedItem();
3137     publishToServerInfo["tech"] = techTreeFiles[listBoxTechTree.getSelectedItemIndex()];
3138 	//publishToServerInfo["map"] = listBoxMap.getSelectedItem();
3139     publishToServerInfo["map"] = getCurrentMapFile();
3140 	//publishToServerInfo["tileset"] = listBoxTileset.getSelectedItem();
3141     publishToServerInfo["tileset"] = tilesetFiles[listBoxTileset.getSelectedItemIndex()];
3142 
3143 	publishToServerInfo["activeSlots"] = intToStr(slotCountUsed);
3144 	publishToServerInfo["networkSlots"] = intToStr(slotCountHumans);
3145 	publishToServerInfo["connectedClients"] = intToStr(slotCountConnectedPlayers);
3146 
3147 	string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str());
3148 	string externalPort=config.getString("PortExternal", serverPort.c_str());
3149 	publishToServerInfo["externalconnectport"] = externalPort;
3150 	publishToServerInfo["privacyPlease"] = intToStr(config.getBool("PrivacyPlease","false"));
3151 
3152 	publishToServerInfo["gameStatus"] = intToStr(game_status_waiting_for_players);
3153 	if(slotCountHumans <= slotCountConnectedPlayers) {
3154 		publishToServerInfo["gameStatus"] = intToStr(game_status_waiting_for_start);
3155 	}
3156 
3157 	publishToServerInfo["gameUUID"] = gameSettings.getGameUUID();
3158 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3159 }
3160 
setupTask(BaseThread * callingThread,void * userdata)3161 void MenuStateCustomGame::setupTask(BaseThread *callingThread,void *userdata) {
3162 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\nsetupTask callingThread [%p] userdata [%p]\n",callingThread,userdata);
3163 	if(userdata != NULL) {
3164 		int value = *((int*)&userdata);
3165 		THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value;
3166 		//printf("\n\nsetupTask callingThread [%p] userdata [%p]\n",callingThread,userdata);
3167 		if(threadType == tnt_MASTERSERVER) {
3168 			MenuStateCustomGame::setupTaskStatic(callingThread);
3169 		}
3170 	}
3171 }
shutdownTask(BaseThread * callingThread,void * userdata)3172 void MenuStateCustomGame::shutdownTask(BaseThread *callingThread,void *userdata) {
3173 	//printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n",callingThread,userdata);
3174 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n",callingThread,userdata);
3175 	if(userdata != NULL) {
3176 		int value = *((int*)&userdata);
3177 		THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value;
3178 		//printf("\n\nshutdownTask callingThread [%p] userdata [%p]\n",callingThread,userdata);
3179 		if(threadType == tnt_MASTERSERVER) {
3180 			MenuStateCustomGame::shutdownTaskStatic(callingThread);
3181 		}
3182 	}
3183 }
setupTaskStatic(BaseThread * callingThread)3184 void MenuStateCustomGame::setupTaskStatic(BaseThread *callingThread) {
3185 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3186 
3187 	CURL *handle = SystemFlags::initHTTP();
3188 	callingThread->setGenericData<CURL>(handle);
3189 
3190 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3191 }
shutdownTaskStatic(BaseThread * callingThread)3192 void MenuStateCustomGame::shutdownTaskStatic(BaseThread *callingThread) {
3193 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3194 
3195 	//printf("LINE: %d\n",__LINE__);
3196 	CURL *handle = callingThread->getGenericData<CURL>();
3197 	SystemFlags::cleanupHTTP(&handle);
3198 
3199 	if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3200 }
3201 
simpleTask(BaseThread * callingThread,void * userdata)3202 void MenuStateCustomGame::simpleTask(BaseThread *callingThread,void *userdata) {
3203 	//printf("\n\nSimple Task callingThread [%p] userdata [%p]\n",callingThread,userdata);
3204 	int value = *((int*)&userdata);
3205 	//printf("\n\nSimple Task callingThread [%p] userdata [%p] value = %d\n",callingThread,userdata,value);
3206 
3207 	THREAD_NOTIFIER_TYPE threadType = (THREAD_NOTIFIER_TYPE)value;
3208 	if(threadType == tnt_MASTERSERVER) {
3209 		simpleTaskForMasterServer(callingThread);
3210 	}
3211 	else if(threadType == tnt_CLIENTS) {
3212 		simpleTaskForClients(callingThread);
3213 	}
3214 }
3215 
simpleTaskForMasterServer(BaseThread * callingThread)3216 void MenuStateCustomGame::simpleTaskForMasterServer(BaseThread *callingThread) {
3217     try {
3218         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - A\n");
3219 
3220         MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__));
3221         if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) {
3222             return;
3223         }
3224 
3225         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - B\n");
3226 
3227         MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(),string(__FILE__) + "_" + intToStr(__LINE__));
3228         bool republish                                  = (needToRepublishToMasterserver == true  && publishToServerInfo.empty() == false);
3229         needToRepublishToMasterserver                   = false;
3230         std::map<string,string> newPublishToServerInfo  = publishToServerInfo;
3231         publishToServerInfo.clear();
3232 
3233         //printf("simpleTask broadCastSettings = %d\n",broadCastSettings);
3234 
3235         if(callingThread->getQuitStatus() == true) {
3236             return;
3237         }
3238 
3239         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - C\n");
3240 
3241         if(republish == true) {
3242         	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3243 
3244             string request = Config::getInstance().getString("Masterserver");
3245     		if(request != "") {
3246     			endPathWithSlash(request,false);
3247     		}
3248     		request += "addServerInfo.php?";
3249 
3250             //CURL *handle = SystemFlags::initHTTP();
3251             CURL *handle = callingThread->getGenericData<CURL>();
3252 
3253             int paramIndex = 0;
3254             for(std::map<string,string>::const_iterator iterMap = newPublishToServerInfo.begin();
3255                 iterMap != newPublishToServerInfo.end(); ++iterMap) {
3256 
3257                 request += iterMap->first;
3258                 request += "=";
3259                 request += SystemFlags::escapeURL(iterMap->second,handle);
3260 
3261                 paramIndex++;
3262                 if(paramIndex < (int)newPublishToServerInfo.size()) {
3263                 	request += "&";
3264                 }
3265             }
3266 
3267             if(SystemFlags::VERBOSE_MODE_ENABLED) printf("The Lobby request is:\n%s\n",request.c_str());
3268 
3269             if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] the request is:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,request.c_str());
3270             safeMutex.ReleaseLock(true);
3271             safeMutexThreadOwner.ReleaseLock();
3272 
3273             std::string serverInfo = SystemFlags::getHTTP(request,handle);
3274             //SystemFlags::cleanupHTTP(&handle);
3275 
3276             MutexSafeWrapper safeMutexThreadOwner2(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__));
3277             if(callingThread->getQuitStatus() == true || safeMutexThreadOwner2.isValidMutex() == false) {
3278                 return;
3279             }
3280             safeMutex.Lock();
3281 
3282             //printf("the result is:\n'%s'\n",serverInfo.c_str());
3283             if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] the result is:\n'%s'\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,serverInfo.c_str());
3284 
3285             // uncomment to enable router setup check of this server
3286             if(EndsWith(serverInfo, "OK") == false) {
3287                 if(callingThread->getQuitStatus() == true) {
3288                     return;
3289                 }
3290 
3291                 // Give things another chance to see if we can get a connection from the master server
3292                 if(tMasterserverErrorElapsed > 0 &&
3293                 		difftime((long int)time(NULL),tMasterserverErrorElapsed) > MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS) {
3294                 	showMasterserverError=true;
3295                 	masterServererErrorToShow = (serverInfo != "" ? serverInfo : "No Reply");
3296                 }
3297                 else {
3298                 	if(tMasterserverErrorElapsed == 0) {
3299                 		tMasterserverErrorElapsed = time(NULL);
3300                 	}
3301 
3302                 	SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line %d] error checking response from masterserver elapsed seconds = %.2f / %d\nResponse:\n%s\n",
3303                 			extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,difftime((long int)time(NULL),tMasterserverErrorElapsed),MASTERSERVER_BROADCAST_MAX_WAIT_RESPONSE_SECONDS,serverInfo.c_str());
3304 
3305                 	needToRepublishToMasterserver = true;
3306                 }
3307             }
3308         }
3309         else {
3310             safeMutexThreadOwner.ReleaseLock();
3311         }
3312 
3313         if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3314 
3315         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - D\n");
3316 
3317         safeMutex.ReleaseLock();
3318 
3319         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - F\n");
3320     }
3321 	catch(const std::exception &ex) {
3322 		char szBuf[8096]="";
3323 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
3324 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
3325 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
3326 
3327 		if(callingThread->getQuitStatus() == false) {
3328             //throw megaglest_runtime_error(szBuf);
3329             showGeneralError=true;
3330             generalErrorToShow = ex.what();
3331 		}
3332 	}
3333 
3334 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3335 }
3336 
simpleTaskForClients(BaseThread * callingThread)3337 void MenuStateCustomGame::simpleTaskForClients(BaseThread *callingThread) {
3338     try {
3339         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - A\n");
3340 
3341         MutexSafeWrapper safeMutexThreadOwner(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__));
3342         if(callingThread->getQuitStatus() == true || safeMutexThreadOwner.isValidMutex() == false) {
3343             return;
3344         }
3345 
3346         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - B\n");
3347 
3348         MutexSafeWrapper safeMutex(callingThread->getMutexThreadObjectAccessor(),string(__FILE__) + "_" + intToStr(__LINE__));
3349         bool broadCastSettings                          = needToBroadcastServerSettings;
3350 
3351         //printf("simpleTask broadCastSettings = %d\n",broadCastSettings);
3352 
3353         needToBroadcastServerSettings                   = false;
3354         bool hasClientConnection                        = false;
3355 
3356         if(broadCastSettings == true) {
3357             ServerInterface *serverInterface = NetworkManager::getInstance().getServerInterface(false);
3358             if(serverInterface != NULL) {
3359                 hasClientConnection = serverInterface->hasClientConnection();
3360             }
3361         }
3362         bool needPing = (difftime((long int)time(NULL),lastNetworkPing) >= GameConstants::networkPingInterval);
3363 
3364         if(callingThread->getQuitStatus() == true) {
3365             return;
3366         }
3367 
3368         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - C\n");
3369 
3370         safeMutexThreadOwner.ReleaseLock();
3371 
3372         if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3373 
3374         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - D\n");
3375 
3376         if(broadCastSettings == true) {
3377             MutexSafeWrapper safeMutexThreadOwner2(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__));
3378             if(callingThread->getQuitStatus() == true || safeMutexThreadOwner2.isValidMutex() == false) {
3379                 return;
3380             }
3381 
3382             if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3383 
3384             //printf("simpleTask broadCastSettings = %d hasClientConnection = %d\n",broadCastSettings,hasClientConnection);
3385 
3386             if(callingThread->getQuitStatus() == true) {
3387                 return;
3388             }
3389             ServerInterface *serverInterface= NetworkManager::getInstance().getServerInterface(false);
3390             if(serverInterface != NULL) {
3391 				lastGameSettingsreceivedCount++;
3392             	if(this->headlessServerMode == false || (serverInterface->getGameSettingsUpdateCount() <= lastMasterServerSettingsUpdateCount)) {
3393                     GameSettings gameSettings;
3394                     loadGameSettings(&gameSettings);
3395 
3396                     //printf("\n\n\n\n=====#2 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),gameSettings.toString().c_str());
3397 
3398                     if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3399 
3400 					serverInterface->setGameSettings(&gameSettings,false);
3401 					lastMasterServerSettingsUpdateCount = serverInterface->getGameSettingsUpdateCount();
3402 
3403 					if(hasClientConnection == true) {
3404 						if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3405 						serverInterface->broadcastGameSetup(&gameSettings);
3406 					}
3407             	}
3408             }
3409         }
3410 
3411         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - E\n");
3412 
3413         if(needPing == true) {
3414             MutexSafeWrapper safeMutexThreadOwner2(callingThread->getMutexThreadOwnerValid(),string(__FILE__) + "_" + intToStr(__LINE__));
3415             if(callingThread->getQuitStatus() == true || safeMutexThreadOwner2.isValidMutex() == false) {
3416                 return;
3417             }
3418 
3419             lastNetworkPing = time(NULL);
3420 
3421             if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] Sending nmtPing to clients\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3422 
3423             ServerInterface *serverInterface= NetworkManager::getInstance().getServerInterface(false);
3424             if(serverInterface != NULL) {
3425             	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3426                 NetworkMessagePing *msg = new NetworkMessagePing(GameConstants::networkPingInterval,time(NULL));
3427                 //serverInterface->broadcastPing(&msg);
3428                 serverInterface->queueBroadcastMessage(msg);
3429                 if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3430             }
3431         }
3432         safeMutex.ReleaseLock();
3433 
3434         //printf("-=-=-=-=- IN MenuStateCustomGame simpleTask - F\n");
3435     }
3436 	catch(const std::exception &ex) {
3437 		char szBuf[8096]="";
3438 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
3439 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
3440 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
3441 
3442 		if(callingThread->getQuitStatus() == false) {
3443             //throw megaglest_runtime_error(szBuf);
3444             showGeneralError=true;
3445             generalErrorToShow = ex.what();
3446 		}
3447 	}
3448 
3449 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3450 }
3451 
loadGameSettings(GameSettings * gameSettings,bool forceCloseUnusedSlots)3452 void MenuStateCustomGame::loadGameSettings(GameSettings *gameSettings,bool forceCloseUnusedSlots) {
3453 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3454 
3455 	int factionCount= 0;
3456 	ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
3457 
3458 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3459 
3460 	if(this->headlessServerMode == true && serverInterface->getGameSettingsUpdateCount() > lastMasterServerSettingsUpdateCount &&
3461 			serverInterface->getGameSettings() != NULL) {
3462 		const GameSettings *settings = serverInterface->getGameSettings();
3463 		//printf("\n\n\n\n=====#3 got settings [%d] [%d]:\n%s\n",lastMasterServerSettingsUpdateCount,serverInterface->getGameSettingsUpdateCount(),settings->toString().c_str());
3464 
3465 		lastMasterServerSettingsUpdateCount = serverInterface->getGameSettingsUpdateCount();
3466 		//printf("#1 custom menu got map [%s]\n",settings->getMap().c_str());
3467 
3468 		setupUIFromGameSettings(*settings);
3469 	}
3470 
3471 	gameSettings->setGameName(labelGameName.getText());
3472 
3473     // Test flags values
3474     //gameSettings->setFlagTypes1(ft1_show_map_resources);
3475     //
3476 
3477 	if(checkBoxScenario.getValue() == true) {
3478 		gameSettings->setScenario(scenarioInfo.name);
3479 		gameSettings->setScenarioDir(Scenario::getScenarioPath(dirList, scenarioInfo.name));
3480 
3481 		gameSettings->setDefaultResources(scenarioInfo.defaultResources);
3482 		gameSettings->setDefaultUnits(scenarioInfo.defaultUnits);
3483 		gameSettings->setDefaultVictoryConditions(scenarioInfo.defaultVictoryConditions);
3484 	}
3485 	else {
3486 		gameSettings->setScenario("");
3487 		gameSettings->setScenarioDir("");
3488 	}
3489 
3490 	gameSettings->setGameUUID(this->gameUUID);
3491 
3492 	//printf("scenarioInfo.name [%s] [%s] [%s]\n",scenarioInfo.name.c_str(),listBoxMap.getSelectedItem().c_str(),getCurrentMapFile().c_str());
3493 
3494 	gameSettings->setMapFilter(listBoxMapFilter.getSelectedItemIndex());
3495 	gameSettings->setDescription(formatString(getCurrentMapFile()));
3496 	gameSettings->setMap(getCurrentMapFile());
3497 	if(tilesetFiles.empty() == false) {
3498 		gameSettings->setTileset(tilesetFiles[listBoxTileset.getSelectedItemIndex()]);
3499 	}
3500 	if(techTreeFiles.empty() == false) {
3501 		gameSettings->setTech(techTreeFiles[listBoxTechTree.getSelectedItemIndex()]);
3502 	}
3503 
3504     if(autoStartSettings != NULL) {
3505     	gameSettings->setDefaultUnits(autoStartSettings->getDefaultUnits());
3506     	gameSettings->setDefaultResources(autoStartSettings->getDefaultResources());
3507     	gameSettings->setDefaultVictoryConditions(autoStartSettings->getDefaultVictoryConditions());
3508     }
3509     else if(checkBoxScenario.getValue() == false) {
3510 		gameSettings->setDefaultUnits(true);
3511 		gameSettings->setDefaultResources(true);
3512 		gameSettings->setDefaultVictoryConditions(true);
3513     }
3514 
3515    	gameSettings->setFogOfWar(listBoxFogOfWar.getSelectedItemIndex() == 0 ||
3516 								listBoxFogOfWar.getSelectedItemIndex() == 1 );
3517 
3518 	gameSettings->setAllowObservers(checkBoxAllowObservers.getValue() == 1);
3519 
3520 	uint32 valueFlags1 = gameSettings->getFlagTypes1();
3521 	if(listBoxFogOfWar.getSelectedItemIndex() == 1 ||
3522 		listBoxFogOfWar.getSelectedItemIndex() == 2 ) {
3523         valueFlags1 |= ft1_show_map_resources;
3524         gameSettings->setFlagTypes1(valueFlags1);
3525 	}
3526 	else {
3527         valueFlags1 &= ~ft1_show_map_resources;
3528         gameSettings->setFlagTypes1(valueFlags1);
3529 	}
3530 
3531 	//gameSettings->setEnableObserverModeAtEndGame(listBoxEnableObserverMode.getSelectedItemIndex() == 0);
3532 	gameSettings->setEnableObserverModeAtEndGame(true);
3533 	//gameSettings->setPathFinderType(static_cast<PathFinderType>(listBoxPathFinderType.getSelectedItemIndex()));
3534 
3535 	valueFlags1 = gameSettings->getFlagTypes1();
3536 	if(checkBoxEnableSwitchTeamMode.getValue() == true) {
3537         valueFlags1 |= ft1_allow_team_switching;
3538         gameSettings->setFlagTypes1(valueFlags1);
3539 	}
3540 	else {
3541         valueFlags1 &= ~ft1_allow_team_switching;
3542         gameSettings->setFlagTypes1(valueFlags1);
3543 	}
3544 	gameSettings->setAiAcceptSwitchTeamPercentChance(strToInt(listBoxAISwitchTeamAcceptPercent.getSelectedItem()));
3545 	gameSettings->setFallbackCpuMultiplier(listBoxFallbackCpuMultiplier.getSelectedItemIndex());
3546 
3547 	if(checkBoxAllowInGameJoinPlayer.getValue() == true) {
3548         valueFlags1 |= ft1_allow_in_game_joining;
3549         gameSettings->setFlagTypes1(valueFlags1);
3550 	}
3551 	else {
3552         valueFlags1 &= ~ft1_allow_in_game_joining;
3553         gameSettings->setFlagTypes1(valueFlags1);
3554 	}
3555 
3556 	if(checkBoxAllowTeamUnitSharing.getValue() == true) {
3557         valueFlags1 |= ft1_allow_shared_team_units;
3558         gameSettings->setFlagTypes1(valueFlags1);
3559 	}
3560 	else {
3561         valueFlags1 &= ~ft1_allow_shared_team_units;
3562         gameSettings->setFlagTypes1(valueFlags1);
3563 	}
3564 
3565 	if(checkBoxAllowTeamResourceSharing.getValue() == true) {
3566         valueFlags1 |= ft1_allow_shared_team_resources;
3567         gameSettings->setFlagTypes1(valueFlags1);
3568 	}
3569 	else {
3570         valueFlags1 &= ~ft1_allow_shared_team_resources;
3571         gameSettings->setFlagTypes1(valueFlags1);
3572 	}
3573 
3574 	if(Config::getInstance().getBool("EnableNetworkGameSynchChecks","false") == true) {
3575 		//printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n");
3576 
3577         valueFlags1 |= ft1_network_synch_checks_verbose;
3578         gameSettings->setFlagTypes1(valueFlags1);
3579 
3580 	}
3581 	else {
3582         valueFlags1 &= ~ft1_network_synch_checks_verbose;
3583         gameSettings->setFlagTypes1(valueFlags1);
3584 
3585 	}
3586 	if(Config::getInstance().getBool("EnableNetworkGameSynchMonitor","false") == true) {
3587 		//printf("*WARNING* - EnableNetworkGameSynchChecks is enabled\n");
3588 
3589         valueFlags1 |= ft1_network_synch_checks;
3590         gameSettings->setFlagTypes1(valueFlags1);
3591 
3592 	}
3593 	else {
3594         valueFlags1 &= ~ft1_network_synch_checks;
3595         gameSettings->setFlagTypes1(valueFlags1);
3596 
3597 	}
3598 
3599 	gameSettings->setNetworkAllowNativeLanguageTechtree(checkBoxAllowNativeLanguageTechtree.getValue());
3600 
3601 	// First save Used slots
3602     //for(int i=0; i<mapInfo.players; ++i)
3603 	int AIPlayerCount = 0;
3604 	for(int i = 0; i < GameConstants::maxPlayers; ++i) {
3605 		if (listBoxControls[i].getSelectedItemIndex() == ctHuman && this->headlessServerMode == true) {
3606 			// switch slot to network, because no human in headless mode
3607 			listBoxControls[i].setSelectedItemIndex(ctNetwork) ;
3608 			updateResourceMultiplier(i);
3609 		}
3610 
3611 		ControlType ct= static_cast<ControlType>(listBoxControls[i].getSelectedItemIndex());
3612 
3613 		if(forceCloseUnusedSlots == true && (ct == ctNetworkUnassigned || ct == ctNetwork)) {
3614 			if(serverInterface != NULL &&
3615 			   (serverInterface->getSlot(i,true) == NULL ||
3616                serverInterface->getSlot(i,true)->isConnected() == false)) {
3617 				if(checkBoxScenario.getValue() == false) {
3618 				//printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str());
3619 
3620 					listBoxControls[i].setSelectedItemIndex(ctClosed);
3621 					ct = ctClosed;
3622 				}
3623 			}
3624 		}
3625 		else if(ct == ctNetworkUnassigned && i < mapInfo.players) {
3626 			listBoxControls[i].setSelectedItemIndex(ctNetwork);
3627 			ct = ctNetwork;
3628 		}
3629 
3630 		if(ct != ctClosed) {
3631 			int slotIndex = factionCount;
3632 			gameSettings->setFactionControl(slotIndex, ct);
3633 			if(ct == ctHuman) {
3634 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, slotIndex = %d, getHumanPlayerName(i) [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,slotIndex,getHumanPlayerName(i).c_str());
3635 
3636 				gameSettings->setThisFactionIndex(slotIndex);
3637 				gameSettings->setNetworkPlayerName(slotIndex, getHumanPlayerName(i));
3638 				gameSettings->setNetworkPlayerUUID(slotIndex,Config::getInstance().getString("PlayerId",""));
3639 				gameSettings->setNetworkPlayerPlatform(slotIndex,getPlatformNameString());
3640 				gameSettings->setNetworkPlayerStatuses(slotIndex, getNetworkPlayerStatus());
3641 				Lang &lang= Lang::getInstance();
3642 				gameSettings->setNetworkPlayerLanguages(slotIndex, lang.getLanguage());
3643 			}
3644 			else if(serverInterface != NULL && serverInterface->getSlot(i,true) != NULL) {
3645 				gameSettings->setNetworkPlayerLanguages(slotIndex, serverInterface->getSlot(i,true)->getNetworkPlayerLanguage());
3646 			}
3647 
3648 			//if(slotIndex == 0) printf("slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex());
3649 
3650 			//printf("Line: %d multiplier index: %d slotIndex: %d\n",__LINE__,listBoxRMultiplier[i].getSelectedItemIndex(),slotIndex);
3651 			gameSettings->setResourceMultiplierIndex(slotIndex, listBoxRMultiplier[i].getSelectedItemIndex());
3652 			//printf("Line: %d multiplier index: %d slotIndex: %d\n",__LINE__,gameSettings->getResourceMultiplierIndex(slotIndex),slotIndex);
3653 
3654 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, factionFiles[listBoxFactions[i].getSelectedItemIndex()] [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,factionFiles[listBoxFactions[i].getSelectedItemIndex()].c_str());
3655 
3656 			gameSettings->setFactionTypeName(slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]);
3657 			if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME)) {
3658 				listBoxTeams[i].setSelectedItem(intToStr(GameConstants::maxPlayers + fpt_Observer));
3659 			}
3660 			else if(listBoxTeams[i].getSelectedItem() == intToStr(GameConstants::maxPlayers + fpt_Observer)) {
3661 
3662 				//printf("Line: %d lastSelectedTeamIndex[i] = %d \n",__LINE__,lastSelectedTeamIndex[i]);
3663 
3664 				if((listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu ||
3665 				   listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega) &&
3666 						checkBoxScenario.getValue() == true) {
3667 
3668 				}
3669 				else {
3670 					if(lastSelectedTeamIndex[i] >= 0 && lastSelectedTeamIndex[i] + 1 != (GameConstants::maxPlayers + fpt_Observer)) {
3671 						if(lastSelectedTeamIndex[i] == 0) {
3672 							lastSelectedTeamIndex[i] = GameConstants::maxPlayers-1;
3673 						}
3674 						else if(lastSelectedTeamIndex[i] == GameConstants::maxPlayers-1) {
3675 							lastSelectedTeamIndex[i] = 0;
3676 						}
3677 
3678 						listBoxTeams[i].setSelectedItemIndex(lastSelectedTeamIndex[i]);
3679 					}
3680 					else {
3681 						listBoxTeams[i].setSelectedItem(intToStr(1));
3682 					}
3683 				}
3684 			}
3685 
3686 			gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex());
3687 			gameSettings->setStartLocationIndex(slotIndex, i);
3688 
3689 			if(listBoxControls[i].getSelectedItemIndex() == ctNetwork ||
3690 				listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
3691 				if(serverInterface != NULL &&
3692 					serverInterface->getSlot(i,true) != NULL &&
3693                    serverInterface->getSlot(i,true)->isConnected()) {
3694 
3695 					gameSettings->setNetworkPlayerStatuses(slotIndex,serverInterface->getSlot(i,true)->getNetworkPlayerStatus());
3696 
3697 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, connectionSlot->getName() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,serverInterface->getSlot(i,true)->getName().c_str());
3698 
3699 					gameSettings->setNetworkPlayerName(slotIndex, serverInterface->getSlot(i,true)->getName());
3700 					gameSettings->setNetworkPlayerUUID(i,serverInterface->getSlot(i,true)->getUUID());
3701 					gameSettings->setNetworkPlayerPlatform(i,serverInterface->getSlot(i,true)->getPlatform());
3702 					labelPlayerNames[i].setText(serverInterface->getSlot(i,true)->getName());
3703 				}
3704 				else {
3705 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, playername unconnected\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i);
3706 
3707 					gameSettings->setNetworkPlayerName(slotIndex, GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME);
3708 					labelPlayerNames[i].setText("");
3709 				}
3710 			}
3711 			else if (listBoxControls[i].getSelectedItemIndex() != ctHuman) {
3712 				AIPlayerCount++;
3713 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, playername is AI (blank)\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i);
3714 
3715 				Lang &lang= Lang::getInstance();
3716 				gameSettings->setNetworkPlayerName(slotIndex, lang.getString("AI") + intToStr(AIPlayerCount));
3717 				labelPlayerNames[i].setText("");
3718 			}
3719 			if (listBoxControls[i].getSelectedItemIndex() == ctHuman) {
3720 				setSlotHuman(i);
3721 			}
3722 			if(serverInterface != NULL && serverInterface->getSlot(i,true) != NULL) {
3723 				gameSettings->setNetworkPlayerUUID(slotIndex,serverInterface->getSlot(i,true)->getUUID());
3724 				gameSettings->setNetworkPlayerPlatform(slotIndex,serverInterface->getSlot(i,true)->getPlatform());
3725 			}
3726 
3727 			factionCount++;
3728 		}
3729 		else {
3730 			//gameSettings->setNetworkPlayerName("");
3731 			gameSettings->setNetworkPlayerStatuses(factionCount, npst_None);
3732 			labelPlayerNames[i].setText("");
3733 		}
3734     }
3735 
3736 	// Next save closed slots
3737 	int closedCount = 0;
3738 	for(int i = 0; i < GameConstants::maxPlayers; ++i) {
3739 		ControlType ct= static_cast<ControlType>(listBoxControls[i].getSelectedItemIndex());
3740 		if(ct == ctClosed) {
3741 			int slotIndex = factionCount + closedCount;
3742 
3743 			gameSettings->setFactionControl(slotIndex, ct);
3744 			gameSettings->setTeam(slotIndex, listBoxTeams[i].getSelectedItemIndex());
3745 			gameSettings->setStartLocationIndex(slotIndex, i);
3746 			//gameSettings->setResourceMultiplierIndex(slotIndex, 10);
3747 			listBoxRMultiplier[i].setSelectedItem("1.0");
3748 			gameSettings->setResourceMultiplierIndex(slotIndex, listBoxRMultiplier[i].getSelectedItemIndex());
3749 			//printf("Test multiplier = %s\n",listBoxRMultiplier[i].getSelectedItem().c_str());
3750 
3751 
3752 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, factionFiles[listBoxFactions[i].getSelectedItemIndex()] [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,factionFiles[listBoxFactions[i].getSelectedItemIndex()].c_str());
3753 
3754 			gameSettings->setFactionTypeName(slotIndex, factionFiles[listBoxFactions[i].getSelectedItemIndex()]);
3755 			gameSettings->setNetworkPlayerName(slotIndex, GameConstants::NETWORK_SLOT_CLOSED_SLOTNAME);
3756 			gameSettings->setNetworkPlayerUUID(slotIndex,"");
3757 			gameSettings->setNetworkPlayerPlatform(slotIndex,"");
3758 
3759 			closedCount++;
3760 		}
3761     }
3762 
3763 	gameSettings->setFactionCount(factionCount);
3764 
3765 	Config &config = Config::getInstance();
3766 	gameSettings->setEnableServerControlledAI(config.getBool("ServerControlledAI","true"));
3767 	gameSettings->setNetworkFramePeriod(config.getInt("NetworkSendFrameCount","20"));
3768 	gameSettings->setNetworkPauseGameForLaggedClients(((checkBoxNetworkPauseGameForLaggedClients.getValue() == true)));
3769 
3770 	if( gameSettings->getTileset() != "") {
3771 		// Check if client has different data, if so force a CRC refresh
3772 		bool forceRefresh = false;
3773 		if(checkNetworkPlayerDataSynch(false,true, false) == false &&
3774 				last_Forced_CheckedCRCTilesetName != gameSettings->getTileset()) {
3775 			lastCheckedCRCTilesetName = "";
3776 			forceRefresh = true;
3777 			last_Forced_CheckedCRCTilesetName = gameSettings->getTileset();
3778 		}
3779 
3780 		if(lastCheckedCRCTilesetName != gameSettings->getTileset()) {
3781 			//console.addLine("Checking tileset CRC [" + gameSettings->getTileset() + "]");
3782 			lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL,forceRefresh);
3783 			if(lastCheckedCRCTilesetValue == 0) {
3784 				lastCheckedCRCTilesetValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,""), string("/") + gameSettings->getTileset() + string("/*"), ".xml", NULL, true);
3785 			}
3786 			lastCheckedCRCTilesetName = gameSettings->getTileset();
3787 		}
3788 		gameSettings->setTilesetCRC(lastCheckedCRCTilesetValue);
3789 	}
3790 
3791 	if(config.getBool("DisableServerLobbyTechtreeCRCCheck","false") == false) {
3792 		if(gameSettings->getTech() != "") {
3793 			// Check if client has different data, if so force a CRC refresh
3794 			bool forceRefresh = false;
3795 			if(checkNetworkPlayerDataSynch(false,false,true) == false &&
3796 					last_Forced_CheckedCRCTechtreeName != gameSettings->getTech()) {
3797 				lastCheckedCRCTechtreeName = "";
3798 				forceRefresh = true;
3799 				last_Forced_CheckedCRCTechtreeName = gameSettings->getTech();
3800 			}
3801 
3802 			if(lastCheckedCRCTechtreeName != gameSettings->getTech()) {
3803 				//console.addLine("Checking techtree CRC [" + gameSettings->getTech() + "]");
3804 				lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml", NULL,forceRefresh);
3805 				if(lastCheckedCRCTechtreeValue == 0) {
3806 					lastCheckedCRCTechtreeValue = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/*", ".xml", NULL, true);
3807 				}
3808 
3809 				reloadFactions(true,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : ""));
3810 				factionCRCList.clear();
3811 				for(unsigned int factionIdx = 0; factionIdx < factionFiles.size(); ++factionIdx) {
3812 					string factionName = factionFiles[factionIdx];
3813 					if(factionName != GameConstants::RANDOMFACTION_SLOTNAME &&
3814 						factionName != GameConstants::OBSERVER_SLOTNAME) {
3815 						//factionCRC   = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true);
3816 						uint32 factionCRC   = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL);
3817 						if(factionCRC == 0) {
3818 							factionCRC   = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), "/" + gameSettings->getTech() + "/factions/" + factionName + "/*", ".xml", NULL, true);
3819 						}
3820 						factionCRCList.push_back(make_pair(factionName,factionCRC));
3821 					}
3822 				}
3823 				//console.addLine("Found factions: " + intToStr(factionCRCList.size()));
3824 				lastCheckedCRCTechtreeName = gameSettings->getTech();
3825 			}
3826 
3827 			gameSettings->setFactionCRCList(factionCRCList);
3828 			gameSettings->setTechCRC(lastCheckedCRCTechtreeValue);
3829 		}
3830 	}
3831 
3832 	if(gameSettings->getMap() != "") {
3833 		// Check if client has different data, if so force a CRC refresh
3834 		//bool forceRefresh = false;
3835 		if(checkNetworkPlayerDataSynch(true,false,false) == false &&
3836 				last_Forced_CheckedCRCMapName != gameSettings->getMap()) {
3837 			lastCheckedCRCMapName = "";
3838 			//forceRefresh = true;
3839 			last_Forced_CheckedCRCMapName = gameSettings->getMap();
3840 		}
3841 
3842 		if(lastCheckedCRCMapName != gameSettings->getMap()) {
3843 			Checksum checksum;
3844 			string file = Config::getMapPath(gameSettings->getMap(),"",false);
3845 			//console.addLine("Checking map CRC [" + file + "]");
3846 			checksum.addFile(file);
3847 			lastCheckedCRCMapValue = checksum.getSum();
3848 			lastCheckedCRCMapName = gameSettings->getMap();
3849 		}
3850 		gameSettings->setMapCRC(lastCheckedCRCMapValue);
3851 	}
3852 
3853 	if(this->headlessServerMode == true) {
3854 		time_t clientConnectedTime = 0;
3855 		bool masterserver_admin_found=false;
3856 		//printf("mapInfo.players [%d]\n",mapInfo.players);
3857 
3858 		for(int i= 0; i < mapInfo.players; ++i) {
3859 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3860 
3861 			if(listBoxControls[i].getSelectedItemIndex() == ctNetwork || listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
3862 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3863 
3864 				if(	serverInterface->getSlot(i,true) != NULL && serverInterface->getSlot(i,true)->isConnected()) {
3865 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3866 
3867 					//printf("slot = %d serverInterface->getSlot(i)->getConnectedTime() = %d session key [%d]\n",i,serverInterface->getSlot(i)->getConnectedTime(),serverInterface->getSlot(i)->getSessionKey());
3868 
3869 					if(clientConnectedTime == 0 ||
3870 							(serverInterface->getSlot(i,true)->getConnectedTime() > 0 && serverInterface->getSlot(i,true)->getConnectedTime() < clientConnectedTime)) {
3871 						clientConnectedTime = serverInterface->getSlot(i,true)->getConnectedTime();
3872 						gameSettings->setMasterserver_admin(serverInterface->getSlot(i,true)->getSessionKey());
3873 						gameSettings->setMasterserver_admin_faction_index(serverInterface->getSlot(i,true)->getPlayerIndex());
3874 						labelGameName.setText(createGameName(serverInterface->getSlot(i,true)->getName()));
3875 						//printf("slot = %d, admin key [%d] slot connected time[" MG_SIZE_T_SPECIFIER "] clientConnectedTime [" MG_SIZE_T_SPECIFIER "]\n",i,gameSettings->getMasterserver_admin(),serverInterface->getSlot(i)->getConnectedTime(),clientConnectedTime);
3876 					}
3877 					if(serverInterface->getSlot(i,true)->getSessionKey() == gameSettings->getMasterserver_admin()){
3878 						masterserver_admin_found=true;
3879 					}
3880 				}
3881 			}
3882 		}
3883 		if(masterserver_admin_found == false ) {
3884 			for(int i=mapInfo.players; i < GameConstants::maxPlayers; ++i) {
3885 				ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
3886 				//ConnectionSlot *slot = serverInterface->getSlot(i);
3887 
3888 				if(	serverInterface->getSlot(i,true) != NULL && serverInterface->getSlot(i,true)->isConnected()) {
3889 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3890 
3891 					//printf("slot = %d serverInterface->getSlot(i)->getConnectedTime() = %d session key [%d]\n",i,serverInterface->getSlot(i)->getConnectedTime(),serverInterface->getSlot(i)->getSessionKey());
3892 
3893 					if(clientConnectedTime == 0 ||
3894 							(serverInterface->getSlot(i,true)->getConnectedTime() > 0 && serverInterface->getSlot(i,true)->getConnectedTime() < clientConnectedTime)) {
3895 						clientConnectedTime = serverInterface->getSlot(i,true)->getConnectedTime();
3896 						gameSettings->setMasterserver_admin(serverInterface->getSlot(i,true)->getSessionKey());
3897 						gameSettings->setMasterserver_admin_faction_index(serverInterface->getSlot(i,true)->getPlayerIndex());
3898 						labelGameName.setText(createGameName(serverInterface->getSlot(i,true)->getName()));
3899 						//printf("slot = %d, admin key [%d] slot connected time[" MG_SIZE_T_SPECIFIER "] clientConnectedTime [" MG_SIZE_T_SPECIFIER "]\n",i,gameSettings->getMasterserver_admin(),serverInterface->getSlot(i)->getConnectedTime(),clientConnectedTime);
3900 					}
3901 					if(serverInterface->getSlot(i,true)->getSessionKey() == gameSettings->getMasterserver_admin()){
3902 						masterserver_admin_found=true;
3903 					}
3904 				}
3905 			}
3906 		}
3907 
3908 		if(masterserver_admin_found == false)
3909 		{
3910 			labelGameName.setText(createGameName());
3911 		}
3912 	}
3913 
3914 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3915 }
3916 
saveGameSettingsToFile(std::string fileName)3917 void MenuStateCustomGame::saveGameSettingsToFile(std::string fileName) {
3918 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3919 
3920 	GameSettings gameSettings;
3921 	loadGameSettings(&gameSettings);
3922 	CoreData::getInstance().saveGameSettingsToFile(fileName, &gameSettings,checkBoxAdvanced.getValue());
3923 
3924 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3925 }
3926 
KeepCurrentHumanPlayerSlots(GameSettings & gameSettings)3927 void MenuStateCustomGame::KeepCurrentHumanPlayerSlots(GameSettings &gameSettings) {
3928 	//look for human players
3929 	bool foundValidHumanControlTypeInFile = false;
3930 	for(int index2 = 0; index2 < GameConstants::maxPlayers; ++index2) {
3931 		ControlType ctFile = static_cast<ControlType>(gameSettings.getFactionControl(index2));
3932 		if(ctFile == ctHuman) {
3933 			ControlType ctUI = static_cast<ControlType>(listBoxControls[index2].getSelectedItemIndex());
3934 			if(ctUI != ctNetwork && ctUI != ctNetworkUnassigned) {
3935 				foundValidHumanControlTypeInFile = true;
3936 				//printf("Human found in file [%d]\n",index2);
3937 			}
3938 			else if(labelPlayerNames[index2].getText() == "") {
3939 				foundValidHumanControlTypeInFile = true;
3940 			}
3941 		}
3942 	}
3943 
3944 	for(int index = 0; index < GameConstants::maxPlayers; ++index) {
3945 		ControlType ct= static_cast<ControlType>(listBoxControls[index].getSelectedItemIndex());
3946 		if(ct == ctHuman) {
3947 			//printf("Human found in UI [%d] and file [%d]\n",index,foundControlType);
3948 
3949 			if(foundValidHumanControlTypeInFile == false) {
3950 				gameSettings.setFactionControl(index,ctHuman);
3951 				gameSettings.setNetworkPlayerName(index,getHumanPlayerName());
3952 			}
3953 		}
3954 
3955 		ControlType ctFile = static_cast<ControlType>(gameSettings.getFactionControl(index));
3956 		if(ctFile == ctHuman) {
3957 			gameSettings.setFactionControl(index,ctHuman);
3958 		}
3959 	}
3960 }
3961 
loadGameSettingsFromFile(std::string fileName)3962 GameSettings MenuStateCustomGame::loadGameSettingsFromFile(std::string fileName) {
3963 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3964 
3965     GameSettings gameSettings;
3966 
3967     GameSettings originalGameSettings;
3968 	loadGameSettings(&originalGameSettings);
3969 
3970     try {
3971     	CoreData::getInstance().loadGameSettingsFromFile(fileName, &gameSettings);
3972     	KeepCurrentHumanPlayerSlots(gameSettings);
3973 
3974     	// correct game settings for headless:
3975     	if(this->headlessServerMode == true) {
3976     		for(int i = 0; i < GameConstants::maxPlayers; ++i) {
3977     			if(gameSettings.getFactionControl(i)== ctHuman){
3978     				gameSettings.setFactionControl(i,ctNetwork);
3979     			}
3980     		}
3981     	}
3982 		setupUIFromGameSettings(gameSettings);
3983 	}
3984     catch(const exception &ex) {
3985     	SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
3986     	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] ERROR = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
3987 
3988     	showMessageBox( ex.what(), "Error", false);
3989 
3990     	setupUIFromGameSettings(originalGameSettings);
3991     	gameSettings = originalGameSettings;
3992     }
3993 
3994     if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
3995 
3996 	return gameSettings;
3997 }
3998 
setupUIFromGameSettings(const GameSettings & gameSettings)3999 void MenuStateCustomGame::setupUIFromGameSettings(const GameSettings &gameSettings) {
4000 	string humanPlayerName = getHumanPlayerName();
4001 
4002 	string scenarioDir = "";
4003 	checkBoxScenario.setValue((gameSettings.getScenario() != ""));
4004 	if(checkBoxScenario.getValue() == true) {
4005 		listBoxScenario.setSelectedItem(formatString(gameSettings.getScenario()));
4006 
4007 		loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), &scenarioInfo);
4008 		scenarioDir = Scenario::getScenarioDir(dirList, gameSettings.getScenario());
4009 
4010 		//printf("scenarioInfo.fogOfWar = %d scenarioInfo.fogOfWar_exploredFlag = %d\n",scenarioInfo.fogOfWar,scenarioInfo.fogOfWar_exploredFlag);
4011 		if(scenarioInfo.fogOfWar == false && scenarioInfo.fogOfWar_exploredFlag == false) {
4012 			listBoxFogOfWar.setSelectedItemIndex(2);
4013 		}
4014 		else if(scenarioInfo.fogOfWar_exploredFlag == true) {
4015 			listBoxFogOfWar.setSelectedItemIndex(1);
4016 		}
4017 		else {
4018 			listBoxFogOfWar.setSelectedItemIndex(0);
4019 		}
4020 		checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing);
4021 		checkBoxAllowTeamResourceSharing.setValue(scenarioInfo.allowTeamResourceSharing);
4022 	}
4023 	setupMapList(gameSettings.getScenario());
4024 	setupTechList(gameSettings.getScenario(),false);
4025 	setupTilesetList(gameSettings.getScenario());
4026 
4027 	if(checkBoxScenario.getValue() == true) {
4028 		//string file = Scenario::getScenarioPath(dirList, gameSettings.getScenario());
4029 		//loadScenarioInfo(file, &scenarioInfo);
4030 
4031 		//printf("#6.1 about to load map [%s]\n",scenarioInfo.mapName.c_str());
4032 		//loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), &mapInfo, false);
4033 		//printf("#6.2\n");
4034 
4035 		listBoxMapFilter.setSelectedItemIndex(0);
4036 		listBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]);
4037 		listBoxMap.setSelectedItem(formatString(scenarioInfo.mapName));
4038 	}
4039 	else {
4040 		//printf("gameSettings.getMapFilter()=%d \n",gameSettings.getMapFilter());
4041 		if(gameSettings.getMapFilter() == 0) {
4042 			listBoxMapFilter.setSelectedItemIndex(0);
4043 		}
4044 		else {
4045 			listBoxMapFilter.setSelectedItem(intToStr(gameSettings.getMapFilter()));
4046 		}
4047 		listBoxMap.setItems(formattedPlayerSortedMaps[gameSettings.getMapFilter()]);
4048 	}
4049 
4050 	//printf("gameSettings.getMap() [%s] [%s]\n",gameSettings.getMap().c_str(),listBoxMap.getSelectedItem().c_str());
4051 
4052 	string mapFile = gameSettings.getMap();
4053 	if(find(mapFiles.begin(),mapFiles.end(),mapFile) != mapFiles.end()) {
4054 		mapFile = formatString(mapFile);
4055 		listBoxMap.setSelectedItem(mapFile);
4056 
4057 		loadMapInfo(Config::getMapPath(getCurrentMapFile(),scenarioDir,true), &mapInfo, true);
4058 		labelMapInfo.setText(mapInfo.desc);
4059 	}
4060 
4061 	string tilesetFile = gameSettings.getTileset();
4062 	if(find(tilesetFiles.begin(),tilesetFiles.end(),tilesetFile) != tilesetFiles.end()) {
4063 		tilesetFile = formatString(tilesetFile);
4064 		listBoxTileset.setSelectedItem(tilesetFile);
4065 	}
4066 
4067 	string techtreeFile = gameSettings.getTech();
4068 	if(find(techTreeFiles.begin(),techTreeFiles.end(),techtreeFile) != techTreeFiles.end()) {
4069 		techtreeFile = formatString(techtreeFile);
4070 		listBoxTechTree.setSelectedItem(techtreeFile);
4071 	}
4072 
4073 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4074 
4075 	//gameSettings->setDefaultUnits(true);
4076 	//gameSettings->setDefaultResources(true);
4077 	//gameSettings->setDefaultVictoryConditions(true);
4078 
4079 	//FogOfWar
4080 	if(checkBoxScenario.getValue() == false) {
4081 		listBoxFogOfWar.setSelectedItemIndex(0); // default is 0!
4082 		if(gameSettings.getFogOfWar() == false){
4083 			listBoxFogOfWar.setSelectedItemIndex(2);
4084 		}
4085 
4086 		if((gameSettings.getFlagTypes1() & ft1_show_map_resources) == ft1_show_map_resources){
4087 			if(gameSettings.getFogOfWar() == true){
4088 				listBoxFogOfWar.setSelectedItemIndex(1);
4089 			}
4090 		}
4091 	}
4092 
4093 	//printf("In [%s::%s line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4094 
4095 	checkBoxAllowObservers.setValue(gameSettings.getAllowObservers() == true ? true : false);
4096 	//listBoxEnableObserverMode.setSelectedItem(gameSettings.getEnableObserverModeAtEndGame() == true ? lang.getString("Yes") : lang.getString("No"));
4097 
4098 	checkBoxEnableSwitchTeamMode.setValue((gameSettings.getFlagTypes1() & ft1_allow_team_switching) == ft1_allow_team_switching ? true : false);
4099 	listBoxAISwitchTeamAcceptPercent.setSelectedItem(intToStr(gameSettings.getAiAcceptSwitchTeamPercentChance()));
4100 	listBoxFallbackCpuMultiplier.setSelectedItemIndex(gameSettings.getFallbackCpuMultiplier());
4101 
4102 	checkBoxAllowInGameJoinPlayer.setValue((gameSettings.getFlagTypes1() & ft1_allow_in_game_joining) == ft1_allow_in_game_joining ? true : false);
4103 
4104 	checkBoxAllowTeamUnitSharing.setValue((gameSettings.getFlagTypes1() & ft1_allow_shared_team_units) == ft1_allow_shared_team_units ? true : false);
4105 	checkBoxAllowTeamResourceSharing.setValue((gameSettings.getFlagTypes1() & ft1_allow_shared_team_resources) == ft1_allow_shared_team_resources ? true : false);
4106 
4107 	ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4108 	if(serverInterface != NULL) {
4109 		serverInterface->setAllowInGameConnections(checkBoxAllowInGameJoinPlayer.getValue() == true);
4110 	}
4111 
4112 	checkBoxAllowNativeLanguageTechtree.setValue(gameSettings.getNetworkAllowNativeLanguageTechtree());
4113 
4114 	//listBoxPathFinderType.setSelectedItemIndex(gameSettings.getPathFinderType());
4115 
4116 	//listBoxEnableServerControlledAI.setSelectedItem(gameSettings.getEnableServerControlledAI() == true ? lang.getString("Yes") : lang.getString("No"));
4117 
4118 	//labelNetworkFramePeriod.setText(lang.getString("NetworkFramePeriod"));
4119 
4120 	//listBoxNetworkFramePeriod.setSelectedItem(intToStr(gameSettings.getNetworkFramePeriod()/10*10));
4121 
4122 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4123 
4124 	checkBoxNetworkPauseGameForLaggedClients.setValue(gameSettings.getNetworkPauseGameForLaggedClients());
4125 
4126 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4127 
4128 	reloadFactions(false,(checkBoxScenario.getValue() == true ? scenarioFiles[listBoxScenario.getSelectedItemIndex()] : ""));
4129 	//reloadFactions(true);
4130 
4131 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d] gameSettings.getFactionCount() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettings.getFactionCount());
4132 
4133 	for(int i = 0; i < GameConstants::maxPlayers; ++i) {
4134 		int slotIndex = gameSettings.getStartLocationIndex(i);
4135 		if(gameSettings.getFactionControl(i) < listBoxControls[slotIndex].getItemCount()) {
4136 			listBoxControls[slotIndex].setSelectedItemIndex(gameSettings.getFactionControl(i));
4137 		}
4138 
4139 		//if(slotIndex == 0) printf("#2 slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex());
4140 
4141 		updateResourceMultiplier(slotIndex);
4142 
4143 		//if(slotIndex == 0) printf("#3 slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex());
4144 
4145 		listBoxRMultiplier[slotIndex].setSelectedItemIndex(gameSettings.getResourceMultiplierIndex(i));
4146 
4147 		//if(slotIndex == 0) printf("#4 slotIndex = %d, i = %d, multiplier = %d\n",slotIndex,i,listBoxRMultiplier[i].getSelectedItemIndex());
4148 
4149 		listBoxTeams[slotIndex].setSelectedItemIndex(gameSettings.getTeam(i));
4150 
4151 		lastSelectedTeamIndex[slotIndex] = listBoxTeams[slotIndex].getSelectedItemIndex();
4152 
4153 		string factionName = gameSettings.getFactionTypeName(i);
4154 		factionName = formatString(factionName);
4155 
4156 		//printf("\n\n\n*** setupUIFromGameSettings A, i = %d, startLoc = %d, factioncontrol = %d, factionName [%s]\n",i,gameSettings.getStartLocationIndex(i),gameSettings.getFactionControl(i),factionName.c_str());
4157 
4158 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] factionName = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,factionName.c_str());
4159 
4160 		if(listBoxFactions[slotIndex].hasItem(factionName) == true) {
4161 			listBoxFactions[slotIndex].setSelectedItem(factionName);
4162 		}
4163 		else {
4164 			listBoxFactions[slotIndex].setSelectedItem(formatString(GameConstants::RANDOMFACTION_SLOTNAME));
4165 		}
4166 
4167 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] i = %d, gameSettings.getNetworkPlayerName(i) [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,gameSettings.getNetworkPlayerName(i).c_str());
4168 
4169 		//labelPlayerNames[slotIndex].setText(gameSettings.getNetworkPlayerName(i));
4170 	}
4171 
4172 	//SetActivePlayerNameEditor();
4173 
4174 	updateControlers();
4175 	updateNetworkSlots();
4176 
4177 	if(this->headlessServerMode == false && humanPlayerName != "") {
4178 		for(int index = 0; index < GameConstants::maxPlayers; ++index) {
4179 			ControlType ct= static_cast<ControlType>(listBoxControls[index].getSelectedItemIndex());
4180 			if(ct == ctHuman) {
4181 				if(humanPlayerName != labelPlayerNames[index].getText()) {
4182 					//printf("Player name changing from [%s] to [%s]\n",labelPlayerNames[index].getText().c_str(),humanPlayerName.c_str());
4183 
4184 					labelPlayerNames[index].setText("");
4185 					labelPlayerNames[index].setText(humanPlayerName);
4186 				}
4187 			}
4188 		}
4189 	}
4190 
4191 	if(hasNetworkGameSettings() == true) {
4192 		needToSetChangedGameSettings = true;
4193 		lastSetChangedGameSettings   = time(NULL);
4194 	}
4195 }
4196 // ============ PRIVATE ===========================
4197 
lastPlayerDisconnected()4198 void MenuStateCustomGame::lastPlayerDisconnected() {
4199 	// this is for headless mode only!
4200 	// if last player disconnects we load the network defaults.
4201 	if(this->headlessServerMode == false) {
4202 		return;
4203 	}
4204 
4205 	ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4206 	bool foundConnectedPlayer=false;
4207 	for(int i = 0; i < GameConstants::maxPlayers; ++i) {
4208 		if(serverInterface->getSlot(i,true) != NULL &&
4209 			(listBoxControls[i].getSelectedItemIndex() == ctNetwork ||
4210 			listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned)) {
4211 			if(serverInterface->getSlot(i,true)->isConnected() == true) {
4212 				foundConnectedPlayer=true;
4213 			}
4214 		}
4215 	}
4216 
4217 	if(!foundConnectedPlayer && headlessHasConnectedPlayer==true ){
4218 		// load defaults
4219 		string data_path = getGameReadWritePath(GameConstants::path_data_CacheLookupKey);
4220 		if(fileExists(data_path + DEFAULT_NETWORKGAME_FILENAME) == true)
4221 			loadGameSettings(data_path + DEFAULT_NETWORKGAME_FILENAME);
4222 	}
4223 	headlessHasConnectedPlayer=foundConnectedPlayer;
4224 }
4225 
hasNetworkGameSettings()4226 bool MenuStateCustomGame::hasNetworkGameSettings() {
4227     bool hasNetworkSlot = false;
4228 
4229     try {
4230 		for(int i=0; i<mapInfo.players; ++i) {
4231 			ControlType ct= static_cast<ControlType>(listBoxControls[i].getSelectedItemIndex());
4232 			if(ct != ctClosed) {
4233 				if(ct == ctNetwork || ct == ctNetworkUnassigned) {
4234 					hasNetworkSlot = true;
4235 					break;
4236 				}
4237 			}
4238 		}
4239 		if(hasNetworkSlot == false) {
4240 			for(int i=0; i < GameConstants::maxPlayers; ++i) {
4241 				ControlType ct= static_cast<ControlType>(listBoxControls[i].getSelectedItemIndex());
4242 				if(ct != ctClosed) {
4243 					if(ct == ctNetworkUnassigned) {
4244 						hasNetworkSlot = true;
4245 						break;
4246 					}
4247 				}
4248 			}
4249 		}
4250     }
4251 	catch(const std::exception &ex) {
4252 		char szBuf[8096]="";
4253 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4254 		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4255 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
4256 
4257 		showGeneralError=true;
4258 		generalErrorToShow = szBuf;
4259 	}
4260 
4261     return hasNetworkSlot;
4262 }
4263 
loadMapInfo(string file,MapInfo * mapInfo,bool loadMapPreview)4264 void MenuStateCustomGame::loadMapInfo(string file, MapInfo *mapInfo, bool loadMapPreview) {
4265 	try {
4266 		Lang &lang= Lang::getInstance();
4267 		if(MapPreview::loadMapInfo(file, mapInfo, lang.getString("MaxPlayers"),lang.getString("Size"),true) == true) {
4268 			ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4269 			for(int i = 0; i < GameConstants::maxPlayers; ++i) {
4270 				if(serverInterface->getSlot(i,true) != NULL &&
4271 					(listBoxControls[i].getSelectedItemIndex() == ctNetwork ||
4272 					listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned)) {
4273 					if(serverInterface->getSlot(i,true)->isConnected() == true) {
4274 						if(i+1 > mapInfo->players &&
4275 							listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) {
4276 							listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned);
4277 						}
4278 					}
4279 				}
4280 
4281 				labelPlayers[i].setVisible(i+1 <= mapInfo->players);
4282 				labelPlayerNames[i].setVisible(i+1 <= mapInfo->players);
4283 				listBoxControls[i].setVisible(i+1 <= mapInfo->players);
4284 				listBoxFactions[i].setVisible(i+1 <= mapInfo->players);
4285 				listBoxTeams[i].setVisible(i+1 <= mapInfo->players);
4286 				labelNetStatus[i].setVisible(i+1 <= mapInfo->players);
4287 			}
4288 
4289 			// Not painting properly so this is on hold
4290 			if(loadMapPreview == true) {
4291 				if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4292 
4293 				mapPreview.loadFromFile(file.c_str());
4294 
4295 				//printf("Loading map preview MAP\n");
4296 				cleanupMapPreviewTexture();
4297 			}
4298 		}
4299 	}
4300 	catch(exception &e) {
4301 		SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s] loading map [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what(),file.c_str());
4302 		throw megaglest_runtime_error("Error loading map file: [" + file + "] msg: " + e.what());
4303 	}
4304 }
4305 
updateControlers()4306 void MenuStateCustomGame::updateControlers() {
4307 	try {
4308 		bool humanPlayer= false;
4309 
4310 		for(int i = 0; i < mapInfo.players; ++i) {
4311 			if(listBoxControls[i].getSelectedItemIndex() == ctHuman) {
4312 				humanPlayer= true;
4313 			}
4314 		}
4315 
4316 		if(humanPlayer == false) {
4317 			if(this->headlessServerMode == false) {
4318 				bool foundNewSlotForHuman = false;
4319 				for(int i = 0; i < mapInfo.players; ++i) {
4320 					if(listBoxControls[i].getSelectedItemIndex() == ctClosed) {
4321 						setSlotHuman(i);
4322 						foundNewSlotForHuman = true;
4323 						break;
4324 					}
4325 				}
4326 
4327 				if(foundNewSlotForHuman == false) {
4328 					for(int i = 0; i < mapInfo.players; ++i) {
4329 						if(listBoxControls[i].getSelectedItemIndex() == ctClosed ||
4330 							listBoxControls[i].getSelectedItemIndex() == ctCpuEasy ||
4331 							listBoxControls[i].getSelectedItemIndex() == ctCpu ||
4332 							listBoxControls[i].getSelectedItemIndex() == ctCpuUltra ||
4333 							listBoxControls[i].getSelectedItemIndex() == ctCpuMega) {
4334 							setSlotHuman(i);
4335 
4336 							foundNewSlotForHuman = true;
4337 							break;
4338 						}
4339 					}
4340 				}
4341 
4342 				if(foundNewSlotForHuman == false) {
4343 					ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4344 					ConnectionSlot *slot = serverInterface->getSlot(0,true);
4345 					if(slot != NULL && slot->isConnected() == true) {
4346 						serverInterface->removeSlot(0);
4347 					}
4348 					setSlotHuman(0);
4349 				}
4350 			}
4351 		}
4352 
4353 		for(int i= mapInfo.players; i < GameConstants::maxPlayers; ++i) {
4354 			if( listBoxControls[i].getSelectedItemIndex() != ctNetwork &&
4355 				listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) {
4356 				//printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str());
4357 
4358 				listBoxControls[i].setSelectedItemIndex(ctClosed);
4359 			}
4360 		}
4361 	}
4362 	catch(const std::exception &ex) {
4363 		char szBuf[8096]="";
4364 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4365 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
4366 		throw megaglest_runtime_error(szBuf);
4367 	}
4368 }
4369 
closeUnusedSlots()4370 void MenuStateCustomGame::closeUnusedSlots(){
4371 	try {
4372 		if(checkBoxScenario.getValue() == false) {
4373 			ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4374 			//for(int i= 0; i<mapInfo.players; ++i){
4375 			for(int i= 0; i < GameConstants::maxPlayers; ++i){
4376 				if(listBoxControls[i].getSelectedItemIndex() == ctNetwork ||
4377 						listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
4378 					if(serverInterface->getSlot(i,true) == NULL ||
4379 					   serverInterface->getSlot(i,true)->isConnected() == false ||
4380 					   serverInterface->getSlot(i,true)->getConnectHasHandshaked() == false) {
4381 						//printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str());
4382 
4383 						listBoxControls[i].setSelectedItemIndex(ctClosed);
4384 					}
4385 				}
4386 			}
4387 			updateNetworkSlots();
4388 		}
4389 	}
4390 	catch(const std::exception &ex) {
4391 		char szBuf[8096]="";
4392 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4393 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
4394 		throw megaglest_runtime_error(szBuf);
4395 	}
4396 }
4397 
updateNetworkSlots()4398 void MenuStateCustomGame::updateNetworkSlots() {
4399 	try {
4400 		ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4401 
4402         if(hasNetworkGameSettings() == true) {
4403             if(hasCheckedForUPNP == false) {
4404 
4405             	if(checkBoxPublishServer.getValue() == true ||
4406             		this->headlessServerMode == true) {
4407 
4408             		hasCheckedForUPNP = true;
4409             		serverInterface->getServerSocket()->NETdiscoverUPnPDevices();
4410             	}
4411             }
4412         }
4413         else {
4414             hasCheckedForUPNP = false;
4415         }
4416 
4417 		for(int i= 0; i < GameConstants::maxPlayers; ++i) {
4418 			ConnectionSlot *slot = serverInterface->getSlot(i,true);
4419 			//printf("A i = %d control type = %d slot [%p]\n",i,listBoxControls[i].getSelectedItemIndex(),slot);
4420 
4421 			if(slot == NULL &&
4422 				listBoxControls[i].getSelectedItemIndex() == ctNetwork)	{
4423 				try {
4424 					serverInterface->addSlot(i);
4425 				}
4426 				catch(const std::exception &ex) {
4427 					char szBuf[8096]="";
4428 					snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4429 					SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
4430 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
4431 					showGeneralError=true;
4432 					if(serverInterface->isPortBound() == false) {
4433 						generalErrorToShow = Lang::getInstance().getString("ErrorBindingPort") + " : " + intToStr(serverInterface->getBindPort());
4434 					}
4435 					else {
4436 						generalErrorToShow = ex.what();
4437 					}
4438 
4439 					// Revert network to CPU
4440 					listBoxControls[i].setSelectedItemIndex(ctCpu);
4441 				}
4442 			}
4443 			slot = serverInterface->getSlot(i,true);
4444 			if(slot != NULL) {
4445 				if((listBoxControls[i].getSelectedItemIndex() != ctNetwork) ||
4446 					(listBoxControls[i].getSelectedItemIndex() == ctNetwork &&
4447 						slot->isConnected() == false && i >= mapInfo.players)) {
4448 					if(slot->getCanAcceptConnections() == true) {
4449 						slot->setCanAcceptConnections(false);
4450 					}
4451 					if(slot->isConnected() == true) {
4452 						if(listBoxControls[i].getSelectedItemIndex() != ctNetworkUnassigned) {
4453 							listBoxControls[i].setSelectedItemIndex(ctNetworkUnassigned);
4454 						}
4455 					}
4456 					else {
4457 						serverInterface->removeSlot(i);
4458 
4459 						if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned) {
4460 							listBoxControls[i].setSelectedItemIndex(ctClosed);
4461 						}
4462 					}
4463 				}
4464 				else if(slot->getCanAcceptConnections() == false) {
4465 					slot->setCanAcceptConnections(true);
4466 				}
4467 			}
4468 		}
4469 	}
4470 	catch(const std::exception &ex) {
4471 		char szBuf[8096]="";
4472 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4473 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
4474 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
4475 		//throw megaglest_runtime_error(szBuf);
4476 		showGeneralError=true;
4477 		generalErrorToShow = szBuf;
4478 
4479 	}
4480 }
4481 
textInput(std::string text)4482 bool MenuStateCustomGame::textInput(std::string text) {
4483 	//printf("In [%s::%s Line: %d] text [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str());
4484 	if(activeInputLabel != NULL) {
4485 		bool handled = textInputEditLabel(text, &activeInputLabel);
4486 		if(handled == true && &labelGameName != activeInputLabel) {
4487 			MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4488 			MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4489 
4490 			if(hasNetworkGameSettings() == true) {
4491 				needToSetChangedGameSettings = true;
4492 				lastSetChangedGameSettings   = time(NULL);
4493 			}
4494 		}
4495 	}
4496 	else {
4497 		if(hasNetworkGameSettings() == true) {
4498 			chatManager.textInput(text);
4499 		}
4500 	}
4501     return false;
4502 }
4503 
keyDown(SDL_KeyboardEvent key)4504 void MenuStateCustomGame::keyDown(SDL_KeyboardEvent key) {
4505 	if(isMasterserverMode() == true) {
4506 		return;
4507 	}
4508 
4509 	if(activeInputLabel != NULL) {
4510 		bool handled = keyDownEditLabel(key, &activeInputLabel);
4511 		if(handled == true) {
4512 			MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4513 			MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4514 
4515 	        if(hasNetworkGameSettings() == true) {
4516 	            needToSetChangedGameSettings = true;
4517 	            lastSetChangedGameSettings   = time(NULL);
4518 	        }
4519 		}
4520 	}
4521 	else {
4522 		//send key to the chat manager
4523 		if(hasNetworkGameSettings() == true) {
4524 			chatManager.keyDown(key);
4525 		}
4526 		if(chatManager.getEditEnabled() == false &&
4527 				(::Shared::Platform::Window::isKeyStateModPressed(KMOD_SHIFT) == false)	) {
4528 			Config &configKeys = Config::getInstance(std::pair<ConfigType,ConfigType>(cfgMainKeys,cfgUserKeys));
4529 
4530 			//if(key == configKeys.getCharKey("ShowFullConsole")) {
4531 			if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) {
4532 				showFullConsole= true;
4533 			}
4534 			//Toggle music
4535 			//else if(key == configKeys.getCharKey("ToggleMusic")) {
4536 			else if(isKeyPressed(configKeys.getSDLKey("ToggleMusic"),key) == true) {
4537 				Config &config = Config::getInstance();
4538 				Lang &lang= Lang::getInstance();
4539 
4540 				float configVolume = (config.getInt("SoundVolumeMusic") / 100.f);
4541 				float currentVolume = CoreData::getInstance().getMenuMusic()->getVolume();
4542 				if(currentVolume > 0) {
4543 					CoreData::getInstance().getMenuMusic()->setVolume(0.f);
4544 					console.addLine(lang.getString("GameMusic") + " " + lang.getString("Off"));
4545 				}
4546 				else {
4547 					CoreData::getInstance().getMenuMusic()->setVolume(configVolume);
4548 					//If the config says zero, use the default music volume
4549 					//gameMusic->setVolume(configVolume ? configVolume : 0.9);
4550 					console.addLine(lang.getString("GameMusic"));
4551 				}
4552 			}
4553 			//else if(key == configKeys.getCharKey("SaveGUILayout")) {
4554 			else if(isKeyPressed(configKeys.getSDLKey("SaveGUILayout"),key) == true) {
4555 				bool saved = GraphicComponent::saveAllCustomProperties(containerName);
4556 				Lang &lang= Lang::getInstance();
4557 				console.addLine(lang.getString("GUILayoutSaved") + " [" + (saved ? lang.getString("Yes") : lang.getString("No"))+ "]");
4558 			}
4559 		}
4560 	}
4561 }
4562 
keyPress(SDL_KeyboardEvent c)4563 void MenuStateCustomGame::keyPress(SDL_KeyboardEvent c) {
4564 	if(isMasterserverMode() == true) {
4565 		return;
4566 	}
4567 
4568 	if(activeInputLabel != NULL) {
4569 		bool handled = keyPressEditLabel(c, &activeInputLabel);
4570 		if(handled == true && &labelGameName != activeInputLabel) {
4571 			MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4572 			MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4573 
4574 			if(hasNetworkGameSettings() == true) {
4575 				needToSetChangedGameSettings = true;
4576 				lastSetChangedGameSettings   = time(NULL);
4577 			}
4578 		}
4579 	}
4580 	else {
4581 		if(hasNetworkGameSettings() == true) {
4582 			chatManager.keyPress(c);
4583 		}
4584 	}
4585 }
4586 
keyUp(SDL_KeyboardEvent key)4587 void MenuStateCustomGame::keyUp(SDL_KeyboardEvent key) {
4588 	if(isMasterserverMode() == true) {
4589 		return;
4590 	}
4591 
4592 	if(activeInputLabel==NULL) {
4593 		if(hasNetworkGameSettings() == true) {
4594 			chatManager.keyUp(key);
4595 		}
4596 		Config &configKeys = Config::getInstance(std::pair<ConfigType,ConfigType>(cfgMainKeys,cfgUserKeys));
4597 
4598 		if(chatManager.getEditEnabled()) {
4599 			//send key to the chat manager
4600 			if(hasNetworkGameSettings() == true) {
4601 				chatManager.keyUp(key);
4602 			}
4603 		}
4604 		//else if(key == configKeys.getCharKey("ShowFullConsole")) {
4605 		else if(isKeyPressed(configKeys.getSDLKey("ShowFullConsole"),key) == true) {
4606 			showFullConsole= false;
4607 		}
4608 	}
4609 }
4610 
showMessageBox(const string & text,const string & header,bool toggle)4611 void MenuStateCustomGame::showMessageBox(const string &text, const string &header, bool toggle){
4612 	if(!toggle){
4613 		mainMessageBox.setEnabled(false);
4614 	}
4615 
4616 	if(!mainMessageBox.getEnabled()){
4617 		mainMessageBox.setText(text);
4618 		mainMessageBox.setHeader(header);
4619 		mainMessageBox.setEnabled(true);
4620 	}
4621 	else{
4622 		mainMessageBox.setEnabled(false);
4623 	}
4624 }
4625 
switchToNextMapGroup(const int direction)4626 void MenuStateCustomGame::switchToNextMapGroup(const int direction){
4627 	int i=listBoxMapFilter.getSelectedItemIndex();
4628 	// if there are no maps for the current selection we switch to next selection
4629 	while(formattedPlayerSortedMaps[i].empty()){
4630 		i=i+direction;
4631 		if(i>GameConstants::maxPlayers){
4632 			i=0;
4633 		}
4634 		if(i<0){
4635 			i=GameConstants::maxPlayers;
4636 		}
4637 	}
4638 	listBoxMapFilter.setSelectedItemIndex(i);
4639 	listBoxMap.setItems(formattedPlayerSortedMaps[i]);
4640 }
4641 
getCurrentMapFile()4642 string MenuStateCustomGame::getCurrentMapFile(){
4643 	int i=listBoxMapFilter.getSelectedItemIndex();
4644 	int mapIndex=listBoxMap.getSelectedItemIndex();
4645 	if(playerSortedMaps[i].empty() == false) {
4646 		return playerSortedMaps[i].at(mapIndex);
4647 	}
4648 	return "";
4649 }
4650 
setActiveInputLabel(GraphicLabel * newLable)4651 void MenuStateCustomGame::setActiveInputLabel(GraphicLabel *newLable) {
4652 	MenuState::setActiveInputLabel(newLable,&activeInputLabel);
4653 }
4654 
getHumanPlayerName(int index)4655 string MenuStateCustomGame::getHumanPlayerName(int index) {
4656 	string  result = defaultPlayerName;
4657 	if(index < 0) {
4658 		for(int j = 0; j < GameConstants::maxPlayers; ++j) {
4659 			if(listBoxControls[j].getSelectedItemIndex() >= 0) {
4660 				ControlType ct = static_cast<ControlType>(listBoxControls[j].getSelectedItemIndex());
4661 				if(ct == ctHuman) {
4662 					index = j;
4663 					break;
4664 				}
4665 			}
4666 		}
4667 	}
4668 
4669 	if(index >= 0 && index < GameConstants::maxPlayers &&
4670 		labelPlayerNames[index].getText() != "" &&
4671 		labelPlayerNames[index].getText() !=  GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME) {
4672 		result = labelPlayerNames[index].getText();
4673 
4674 		if(activeInputLabel != NULL) {
4675 			size_t found = result.find_last_of("_");
4676 			if (found != string::npos) {
4677 				result = result.substr(0,found);
4678 			}
4679 		}
4680 	}
4681 
4682 	return result;
4683 }
4684 
loadFactionTexture(string filepath)4685 void MenuStateCustomGame::loadFactionTexture(string filepath) {
4686 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4687 
4688 	if(enableFactionTexturePreview == true) {
4689 		if(filepath == "") {
4690 			factionTexture = NULL;
4691 		}
4692 		else {
4693 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] filepath = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,filepath.c_str());
4694 
4695 			factionTexture = Renderer::findTexture(filepath);
4696 
4697 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4698 		}
4699 	}
4700 }
4701 
cleanupMapPreviewTexture()4702 void MenuStateCustomGame::cleanupMapPreviewTexture() {
4703 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4704 
4705 	//printf("CLEANUP map preview texture\n");
4706 
4707 	if(mapPreviewTexture != NULL) {
4708 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4709 
4710 		mapPreviewTexture->end();
4711 
4712 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4713 		delete mapPreviewTexture;
4714 		mapPreviewTexture = NULL;
4715 	}
4716 	if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4717 }
4718 
getNetworkPlayerStatus()4719 int32 MenuStateCustomGame::getNetworkPlayerStatus() {
4720 	int32 result = npst_None;
4721 	switch(listBoxPlayerStatus.getSelectedItemIndex()) {
4722 		case 2:
4723 			result = npst_Ready;
4724 			break;
4725 		case 1:
4726 			result = npst_BeRightBack;
4727 			break;
4728 		case 0:
4729 		default:
4730 			result = npst_PickSettings;
4731 			break;
4732 	}
4733 
4734 	return result;
4735 }
4736 
loadScenarioInfo(string file,ScenarioInfo * scenarioInfo)4737 void MenuStateCustomGame::loadScenarioInfo(string file, ScenarioInfo *scenarioInfo) {
4738 	//printf("Load scenario file [%s]\n",file.c_str());
4739 	bool isTutorial = Scenario::isGameTutorial(file);
4740 	Scenario::loadScenarioInfo(file, scenarioInfo, isTutorial);
4741 
4742 	//cleanupPreviewTexture();
4743 	previewLoadDelayTimer=time(NULL);
4744 	needToLoadTextures=true;
4745 }
4746 
isInSpecialKeyCaptureEvent()4747 bool MenuStateCustomGame::isInSpecialKeyCaptureEvent() {
4748 	bool result = (chatManager.getEditEnabled() || activeInputLabel != NULL);
4749 	return result;
4750 }
4751 
processScenario()4752 void MenuStateCustomGame::processScenario() {
4753 	try {
4754 		if(checkBoxScenario.getValue() == true) {
4755 			//printf("listBoxScenario.getSelectedItemIndex() = %d [%s] scenarioFiles.size() = %d\n",listBoxScenario.getSelectedItemIndex(),listBoxScenario.getSelectedItem().c_str(),scenarioFiles.size());
4756 			loadScenarioInfo(Scenario::getScenarioPath(dirList, scenarioFiles[listBoxScenario.getSelectedItemIndex()]), &scenarioInfo);
4757 			string scenarioDir = Scenario::getScenarioDir(dirList, scenarioInfo.name);
4758 
4759 			//printf("scenarioInfo.fogOfWar = %d scenarioInfo.fogOfWar_exploredFlag = %d\n",scenarioInfo.fogOfWar,scenarioInfo.fogOfWar_exploredFlag);
4760 			if(scenarioInfo.fogOfWar == false && scenarioInfo.fogOfWar_exploredFlag == false) {
4761 				listBoxFogOfWar.setSelectedItemIndex(2);
4762 			}
4763 			else if(scenarioInfo.fogOfWar_exploredFlag == true) {
4764 				listBoxFogOfWar.setSelectedItemIndex(1);
4765 			}
4766 			else {
4767 				listBoxFogOfWar.setSelectedItemIndex(0);
4768 			}
4769 
4770 			checkBoxAllowTeamUnitSharing.setValue(scenarioInfo.allowTeamUnitSharing);
4771 			checkBoxAllowTeamResourceSharing.setValue(scenarioInfo.allowTeamResourceSharing);
4772 
4773 			setupTechList(scenarioInfo.name, false);
4774 			listBoxTechTree.setSelectedItem(formatString(scenarioInfo.techTreeName));
4775 			reloadFactions(false,scenarioInfo.name);
4776 
4777 			setupTilesetList(scenarioInfo.name);
4778 			listBoxTileset.setSelectedItem(formatString(scenarioInfo.tilesetName));
4779 
4780 			setupMapList(scenarioInfo.name);
4781 			listBoxMap.setSelectedItem(formatString(scenarioInfo.mapName));
4782 			loadMapInfo(Config::getMapPath(getCurrentMapFile(),scenarioDir,true), &mapInfo, true);
4783 			labelMapInfo.setText(mapInfo.desc);
4784 
4785 			//printf("scenarioInfo.name [%s] [%s]\n",scenarioInfo.name.c_str(),listBoxMap.getSelectedItem().c_str());
4786 
4787 			// Loop twice to set the human slot or else it closes network slots in some cases
4788 			for(int humanIndex = 0; humanIndex < 2; ++humanIndex) {
4789 				for(int i = 0; i < mapInfo.players; ++i) {
4790 					listBoxRMultiplier[i].setSelectedItem(floatToStr(scenarioInfo.resourceMultipliers[i],1));
4791 
4792 					ServerInterface* serverInterface= NetworkManager::getInstance().getServerInterface();
4793 					ConnectionSlot *slot = serverInterface->getSlot(i,true);
4794 
4795 					int selectedControlItemIndex = listBoxControls[i].getSelectedItemIndex();
4796 					if(selectedControlItemIndex != ctNetwork ||
4797 						(selectedControlItemIndex == ctNetwork && (slot == NULL || slot->isConnected() == false))) {
4798 					}
4799 
4800 					listBoxControls[i].setSelectedItemIndex(scenarioInfo.factionControls[i]);
4801 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__);
4802 
4803 					// Skip over networkunassigned
4804 					//if(listBoxControls[i].getSelectedItemIndex() == ctNetworkUnassigned &&
4805 					//	selectedControlItemIndex != ctNetworkUnassigned) {
4806 					//	listBoxControls[i].mouseClick(x, y);
4807 					//}
4808 
4809 					//look for human players
4810 					int humanIndex1= -1;
4811 					int humanIndex2= -1;
4812 					for(int j = 0; j < GameConstants::maxPlayers; ++j) {
4813 						ControlType ct= static_cast<ControlType>(listBoxControls[j].getSelectedItemIndex());
4814 						if(ct == ctHuman) {
4815 							if(humanIndex1 == -1) {
4816 								humanIndex1= j;
4817 							}
4818 							else {
4819 								humanIndex2= j;
4820 							}
4821 						}
4822 					}
4823 
4824 					if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] humanIndex1 = %d, humanIndex2 = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,humanIndex1,humanIndex2);
4825 
4826 					//no human
4827 					if(humanIndex1 == -1 && humanIndex2 == -1) {
4828 						setSlotHuman(i);
4829 						if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] i = %d, labelPlayerNames[i].getText() [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,labelPlayerNames[i].getText().c_str());
4830 
4831 						//printf("humanIndex1 = %d humanIndex2 = %d i = %d listBoxControls[i].getSelectedItemIndex() = %d\n",humanIndex1,humanIndex2,i,listBoxControls[i].getSelectedItemIndex());
4832 					}
4833 					//2 humans
4834 					else if(humanIndex1 != -1 && humanIndex2 != -1) {
4835 						int closeSlotIndex = (humanIndex1 == i ? humanIndex2: humanIndex1);
4836 						int humanSlotIndex = (closeSlotIndex == humanIndex1 ? humanIndex2 : humanIndex1);
4837 
4838 						string origPlayName = labelPlayerNames[closeSlotIndex].getText();
4839 
4840 						if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line %d] closeSlotIndex = %d, origPlayName [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,closeSlotIndex,origPlayName.c_str());
4841 						//printf("humanIndex1 = %d humanIndex2 = %d i = %d closeSlotIndex = %d humanSlotIndex = %d\n",humanIndex1,humanIndex2,i,closeSlotIndex,humanSlotIndex);
4842 
4843 						listBoxControls[closeSlotIndex].setSelectedItemIndex(ctClosed);
4844 						labelPlayerNames[humanSlotIndex].setText((origPlayName != "" ? origPlayName : getHumanPlayerName()));
4845 					}
4846 
4847 					ControlType ct= static_cast<ControlType>(listBoxControls[i].getSelectedItemIndex());
4848 					if(ct != ctClosed) {
4849 						//updateNetworkSlots();
4850 						//updateResourceMultiplier(i);
4851 						updateResourceMultiplier(i);
4852 
4853 						//printf("Setting scenario faction i = %d [ %s]\n",i,scenarioInfo.factionTypeNames[i].c_str());
4854 						listBoxFactions[i].setSelectedItem(formatString(scenarioInfo.factionTypeNames[i]));
4855 						//printf("DONE Setting scenario faction i = %d [ %s]\n",i,scenarioInfo.factionTypeNames[i].c_str());
4856 
4857 						// Disallow CPU players to be observers
4858 						if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] == formatString(GameConstants::OBSERVER_SLOTNAME) &&
4859 							(listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu ||
4860 							 listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega)) {
4861 							listBoxFactions[i].setSelectedItemIndex(0);
4862 						}
4863 						//
4864 
4865 						listBoxTeams[i].setSelectedItem(intToStr(scenarioInfo.teams[i]));
4866 						if(factionFiles[listBoxFactions[i].getSelectedItemIndex()] != formatString(GameConstants::OBSERVER_SLOTNAME)) {
4867 							if(listBoxTeams[i].getSelectedItemIndex() + 1 != (GameConstants::maxPlayers + fpt_Observer)) {
4868 								lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex();
4869 							}
4870 							// Alow Neutral cpu players
4871 							else if(listBoxControls[i].getSelectedItemIndex() == ctCpuEasy || listBoxControls[i].getSelectedItemIndex() == ctCpu ||
4872 							 listBoxControls[i].getSelectedItemIndex() == ctCpuUltra || listBoxControls[i].getSelectedItemIndex() == ctCpuMega) {
4873 								lastSelectedTeamIndex[i] = listBoxTeams[i].getSelectedItemIndex();
4874 							}
4875 						}
4876 						else {
4877 							lastSelectedTeamIndex[i] = -1;
4878 						}
4879 					}
4880 
4881 					if(checkBoxPublishServer.getValue() == true) {
4882 						needToRepublishToMasterserver = true;
4883 					}
4884 
4885 					if(hasNetworkGameSettings() == true) {
4886 						needToSetChangedGameSettings = true;
4887 						lastSetChangedGameSettings   = time(NULL);;
4888 					}
4889 				}
4890 			}
4891 
4892 			updateControlers();
4893 			updateNetworkSlots();
4894 
4895 			MutexSafeWrapper safeMutex((publishToMasterserverThread != NULL ? publishToMasterserverThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4896 			MutexSafeWrapper safeMutexCLI((publishToClientsThread != NULL ? publishToClientsThread->getMutexThreadObjectAccessor() : NULL),string(__FILE__) + "_" + intToStr(__LINE__));
4897 
4898 			if(checkBoxPublishServer.getValue() == true) {
4899 				needToRepublishToMasterserver = true;
4900 			}
4901 			if(hasNetworkGameSettings() == true) {
4902 				needToSetChangedGameSettings = true;
4903 				lastSetChangedGameSettings   = time(NULL);
4904 			}
4905 
4906 			//labelInfo.setText(scenarioInfo.desc);
4907 		}
4908 		else {
4909 			setupMapList("");
4910 			listBoxMap.setSelectedItem(formatString(formattedPlayerSortedMaps[0][0]));
4911 			loadMapInfo(Config::getMapPath(getCurrentMapFile(),"",true), &mapInfo, true);
4912 			labelMapInfo.setText(mapInfo.desc);
4913 
4914 			setupTechList("", false);
4915 			reloadFactions(false,"");
4916 			setupTilesetList("");
4917 			updateControlers();
4918 		}
4919 		SetupUIForScenarios();
4920 	}
4921 	catch(const std::exception &ex) {
4922 		char szBuf[8096]="";
4923 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4924 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
4925 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
4926 
4927 		mainMessageBoxState=1;
4928 		showMessageBox( szBuf, "Error detected", false);
4929 	}
4930 }
4931 
SetupUIForScenarios()4932 void MenuStateCustomGame::SetupUIForScenarios() {
4933 	try {
4934 		if(checkBoxScenario.getValue() == true) {
4935 			// START - Disable changes to controls while in Scenario mode
4936 			for(int i = 0; i < GameConstants::maxPlayers; ++i) {
4937 				listBoxControls[i].setEditable(false);
4938 				listBoxFactions[i].setEditable(false);
4939 				listBoxRMultiplier[i].setEditable(false);
4940 				listBoxTeams[i].setEditable(false);
4941 			}
4942 			listBoxFogOfWar.setEditable(false);
4943 			checkBoxAllowObservers.setEditable(false);
4944 			checkBoxAllowTeamUnitSharing.setEditable(false);
4945 			checkBoxAllowTeamResourceSharing.setEditable(false);
4946 			//listBoxPathFinderType.setEditable(false);
4947 			checkBoxEnableSwitchTeamMode.setEditable(false);
4948 			listBoxAISwitchTeamAcceptPercent.setEditable(false);
4949 			listBoxFallbackCpuMultiplier.setEditable(false);
4950 			listBoxMap.setEditable(false);
4951 			listBoxTileset.setEditable(false);
4952 			listBoxMapFilter.setEditable(false);
4953 			listBoxTechTree.setEditable(false);
4954 			// END - Disable changes to controls while in Scenario mode
4955 		}
4956 		else {
4957 			// START - Disable changes to controls while in Scenario mode
4958 			for(int i = 0; i < GameConstants::maxPlayers; ++i) {
4959 				listBoxControls[i].setEditable(true);
4960 				listBoxFactions[i].setEditable(true);
4961 				listBoxRMultiplier[i].setEditable(true);
4962 				listBoxTeams[i].setEditable(true);
4963 			}
4964 			listBoxFogOfWar.setEditable(true);
4965 			checkBoxAllowObservers.setEditable(true);
4966 			checkBoxAllowTeamUnitSharing.setEditable(true);
4967 			checkBoxAllowTeamResourceSharing.setEditable(true);
4968 			//listBoxPathFinderType.setEditable(true);
4969 			checkBoxEnableSwitchTeamMode.setEditable(true);
4970 			listBoxAISwitchTeamAcceptPercent.setEditable(true);
4971 			listBoxFallbackCpuMultiplier.setEditable(true);
4972 			listBoxMap.setEditable(true);
4973 			listBoxTileset.setEditable(true);
4974 			listBoxMapFilter.setEditable(true);
4975 			listBoxTechTree.setEditable(true);
4976 			// END - Disable changes to controls while in Scenario mode
4977 		}
4978 	}
4979 	catch(const std::exception &ex) {
4980 		char szBuf[8096]="";
4981 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
4982 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
4983 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
4984 
4985 		throw megaglest_runtime_error(szBuf);
4986 	}
4987 
4988 }
4989 
setupMapList(string scenario)4990 int MenuStateCustomGame::setupMapList(string scenario) {
4991 	int initialMapSelection = 0;
4992 
4993 	try {
4994 		Config &config = Config::getInstance();
4995 		vector<string> invalidMapList;
4996 		string scenarioDir = Scenario::getScenarioDir(dirList, scenario);
4997 		vector<string> pathList = config.getPathListForType(ptMaps,scenarioDir);
4998 		vector<string> allMaps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,true,&invalidMapList);
4999 		if(scenario != "") {
5000 			vector<string> allMaps2 = MapPreview::findAllValidMaps(config.getPathListForType(ptMaps,""),"",false,true,&invalidMapList);
5001 			copy(allMaps2.begin(), allMaps2.end(), std::inserter(allMaps, allMaps.begin()));
5002 		}
5003 		// sort map list non case sensitive
5004 		std::sort(allMaps.begin(),allMaps.end(),compareNonCaseSensitive);
5005 
5006 		if (allMaps.empty()) {
5007 			throw megaglest_runtime_error("No maps were found!");
5008 		}
5009 		vector<string> results;
5010 		copy(allMaps.begin(), allMaps.end(), std::back_inserter(results));
5011 		mapFiles = results;
5012 
5013 		for(unsigned int i = 0; i < GameConstants::maxPlayers+1; ++i) {
5014 			playerSortedMaps[i].clear();
5015 			formattedPlayerSortedMaps[i].clear();
5016 		}
5017 
5018 		// at index=0 fill in the whole list
5019 		copy(mapFiles.begin(), mapFiles.end(), std::back_inserter(playerSortedMaps[0]));
5020 		copy(playerSortedMaps[0].begin(), playerSortedMaps[0].end(), std::back_inserter(formattedPlayerSortedMaps[0]));
5021 		std::for_each(formattedPlayerSortedMaps[0].begin(), formattedPlayerSortedMaps[0].end(), FormatString());
5022 
5023 		// fill playerSortedMaps and formattedPlayerSortedMaps according to map player count
5024 		for(int i= 0; i < (int)mapFiles.size(); i++){// fetch info and put map in right list
5025 			loadMapInfo(Config::getMapPath(mapFiles.at(i), scenarioDir, false), &mapInfo, false);
5026 
5027 			if(GameConstants::maxPlayers+1 <= mapInfo.players) {
5028 				char szBuf[8096]="";
5029 				snprintf(szBuf,8096,"Sorted map list [%d] does not match\ncurrent map playercount [%d]\nfor file [%s]\nmap [%s]",GameConstants::maxPlayers+1,mapInfo.players,Config::getMapPath(mapFiles.at(i), "", false).c_str(),mapInfo.desc.c_str());
5030 				throw megaglest_runtime_error(szBuf);
5031 			}
5032 			playerSortedMaps[mapInfo.players].push_back(mapFiles.at(i));
5033 			formattedPlayerSortedMaps[mapInfo.players].push_back(formatString(mapFiles.at(i)));
5034 			if(config.getString("InitialMap", "Conflict") == formattedPlayerSortedMaps[mapInfo.players].back()){
5035 				initialMapSelection= i;
5036 			}
5037 		}
5038 
5039 		//printf("#6 scenario [%s] [%s]\n",scenario.c_str(),scenarioDir.c_str());
5040 		if(scenario != "") {
5041 			string file = Scenario::getScenarioPath(dirList, scenario);
5042 			loadScenarioInfo(file, &scenarioInfo);
5043 
5044 			//printf("#6.1 about to load map [%s]\n",scenarioInfo.mapName.c_str());
5045 			loadMapInfo(Config::getMapPath(scenarioInfo.mapName, scenarioDir, true), &mapInfo, false);
5046 			//printf("#6.2\n");
5047 			listBoxMapFilter.setSelectedItem(intToStr(mapInfo.players));
5048 			listBoxMap.setItems(formattedPlayerSortedMaps[mapInfo.players]);
5049 		}
5050 		else {
5051 			listBoxMapFilter.setSelectedItemIndex(0);
5052 			listBoxMap.setItems(formattedPlayerSortedMaps[0]);
5053 		}
5054 		//printf("#7\n");
5055 	}
5056 	catch(const std::exception &ex) {
5057 		char szBuf[8096]="";
5058 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
5059 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
5060 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
5061 
5062 		throw megaglest_runtime_error(szBuf);
5063 		//abort();
5064 	}
5065 
5066 	return initialMapSelection;
5067 }
5068 
setupTechList(string scenario,bool forceLoad)5069 int MenuStateCustomGame::setupTechList(string scenario, bool forceLoad) {
5070 	int initialTechSelection = 0;
5071 	try {
5072 		Config &config = Config::getInstance();
5073 
5074 		string scenarioDir = Scenario::getScenarioDir(dirList, scenario);
5075 		vector<string> results;
5076 		vector<string> techPaths = config.getPathListForType(ptTechs,scenarioDir);
5077 		findDirs(techPaths, results);
5078 
5079 		if(results.empty()) {
5080 			//throw megaglest_runtime_error("No tech-trees were found!");
5081 			printf("No tech-trees were found (custom)!\n");
5082 		}
5083 
5084 		techTreeFiles= results;
5085 
5086 		vector<string> translatedTechs;
5087 
5088 		for(unsigned int i= 0; i < results.size(); i++) {
5089 			//printf("TECHS i = %d results [%s] scenario [%s]\n",i,results[i].c_str(),scenario.c_str());
5090 
5091 			results.at(i)= formatString(results.at(i));
5092 			if(config.getString("InitialTechTree", "Megapack") == results.at(i)) {
5093 				initialTechSelection= i;
5094 			}
5095 			string txTech = techTree->getTranslatedName(techTreeFiles.at(i), forceLoad);
5096 			translatedTechs.push_back(formatString(txTech));
5097 		}
5098 
5099 
5100 		listBoxTechTree.setItems(results,translatedTechs);
5101 	}
5102 	catch(const std::exception &ex) {
5103 		char szBuf[8096]="";
5104 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
5105 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
5106 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
5107 
5108 		throw megaglest_runtime_error(szBuf);
5109 	}
5110 
5111 	return initialTechSelection;
5112 }
5113 
reloadFactions(bool keepExistingSelectedItem,string scenario)5114 void MenuStateCustomGame::reloadFactions(bool keepExistingSelectedItem, string scenario) {
5115 	try {
5116 		Config &config = Config::getInstance();
5117 		Lang &lang= Lang::getInstance();
5118 
5119 		vector<string> results;
5120 		string scenarioDir = Scenario::getScenarioDir(dirList, scenario);
5121 		vector<string> techPaths = config.getPathListForType(ptTechs,scenarioDir);
5122 
5123 		//printf("#1 techPaths.size() = %d scenarioDir [%s] [%s]\n",techPaths.size(),scenario.c_str(),scenarioDir.c_str());
5124 
5125 		if(listBoxTechTree.getItemCount() > 0) {
5126 			for(int idx = 0; idx < (int)techPaths.size(); idx++) {
5127 				string &techPath = techPaths[idx];
5128 				endPathWithSlash(techPath);
5129 				string factionPath = techPath + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "/factions/";
5130 				findDirs(factionPath, results, false, false);
5131 
5132 				//printf("idx = %d factionPath [%s] results.size() = %d\n",idx,factionPath.c_str(),results.size());
5133 
5134 				if(results.empty() == false) {
5135 					break;
5136 				}
5137 			}
5138 		}
5139 
5140 		if(results.empty() == true) {
5141 			//throw megaglest_runtime_error("(2)There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]");
5142 			showGeneralError=true;
5143 			if(listBoxTechTree.getItemCount() > 0) {
5144 				generalErrorToShow = "[#2] There are no factions for the tech tree [" + techTreeFiles[listBoxTechTree.getSelectedItemIndex()] + "]";
5145 			}
5146 			else {
5147 				generalErrorToShow = "[#2] There are no factions since there is no tech tree!";
5148 			}
5149 		}
5150 
5151 //		results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME));
5152 //
5153 //		// Add special Observer Faction
5154 //		if(checkBoxAllowObservers.getValue() == 1) {
5155 //			results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME));
5156 //		}
5157 
5158 		vector<string> translatedFactionNames;
5159 		factionFiles= results;
5160 		for(int i = 0; i < (int)results.size(); ++i) {
5161 			results[i]= formatString(results[i]);
5162 
5163 			string translatedString = "";
5164 			if(listBoxTechTree.getItemCount() > 0) {
5165 				translatedString = techTree->getTranslatedFactionName(techTreeFiles[listBoxTechTree.getSelectedItemIndex()],factionFiles[i]);
5166 			}
5167 			//printf("translatedString=%s  formatString(results[i])=%s \n",translatedString.c_str(),formatString(results[i]).c_str() );
5168 			if(toLower(translatedString)==toLower(results[i])){
5169 				translatedFactionNames.push_back(results[i]);
5170 			}
5171 			else {
5172 				translatedFactionNames.push_back(results[i]+" ("+translatedString+")");
5173 			}
5174 			//printf("FACTIONS i = %d results [%s]\n",i,results[i].c_str());
5175 
5176 			if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"Tech [%s] has faction [%s]\n",techTreeFiles[listBoxTechTree.getSelectedItemIndex()].c_str(),results[i].c_str());
5177 		}
5178 		results.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME));
5179 		factionFiles.push_back(formatString(GameConstants::RANDOMFACTION_SLOTNAME));
5180 		translatedFactionNames.push_back("*"+lang.getString("Random","",true)+"*");
5181 
5182 		// Add special Observer Faction
5183 		if(checkBoxAllowObservers.getValue() == 1) {
5184 			results.push_back(formatString(GameConstants::OBSERVER_SLOTNAME));
5185 			factionFiles.push_back(formatString(GameConstants::OBSERVER_SLOTNAME));
5186 			translatedFactionNames.push_back("*"+lang.getString("Observer","",true)+"*");
5187 		}
5188 
5189 		for(int i = 0; i < GameConstants::maxPlayers; ++i) {
5190 			int originalIndex = listBoxFactions[i].getSelectedItemIndex();
5191 			string originalValue = (listBoxFactions[i].getItemCount() > 0 ? listBoxFactions[i].getSelectedItem() : "");
5192 
5193 			listBoxFactions[i].setItems(results,translatedFactionNames);
5194 			if( keepExistingSelectedItem == false ||
5195 				(checkBoxAllowObservers.getValue() == 0 &&
5196 						originalValue == formatString(GameConstants::OBSERVER_SLOTNAME)) ) {
5197 
5198 				listBoxFactions[i].setSelectedItemIndex(i % results.size());
5199 
5200 				if( originalValue == formatString(GameConstants::OBSERVER_SLOTNAME) &&
5201 					listBoxFactions[i].getSelectedItem() != formatString(GameConstants::OBSERVER_SLOTNAME)) {
5202 					if(listBoxTeams[i].getSelectedItem() == intToStr(GameConstants::maxPlayers + fpt_Observer)) {
5203 						listBoxTeams[i].setSelectedItem(intToStr(1));
5204 					}
5205 				}
5206 			}
5207 			else if(originalIndex < (int)results.size()) {
5208 				listBoxFactions[i].setSelectedItemIndex(originalIndex);
5209 			}
5210 		}
5211 	}
5212 	catch(const std::exception &ex) {
5213 		char szBuf[8096]="";
5214 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
5215 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
5216 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
5217 
5218 		throw megaglest_runtime_error(szBuf);
5219 	}
5220 }
5221 
setSlotHuman(int i)5222 void MenuStateCustomGame::setSlotHuman(int i) {
5223 	if(labelPlayerNames[i].getEditable()) {
5224 		return;
5225 	}
5226 	listBoxControls[i].setSelectedItemIndex(ctHuman);
5227 	listBoxRMultiplier[i].setSelectedItem("1.0");
5228 
5229 	labelPlayerNames[i].setText(getHumanPlayerName());
5230 	for(int j = 0; j < GameConstants::maxPlayers; ++j) {
5231 		labelPlayerNames[j].setEditable(false);
5232 	}
5233 	labelPlayerNames[i].setEditable(true);
5234 }
5235 
setupTilesetList(string scenario)5236 void MenuStateCustomGame::setupTilesetList(string scenario) {
5237 	try {
5238 		Config &config = Config::getInstance();
5239 
5240 		string scenarioDir = Scenario::getScenarioDir(dirList, scenario);
5241 
5242 		vector<string> results;
5243 		findDirs(config.getPathListForType(ptTilesets,scenarioDir), results);
5244 		if (results.empty()) {
5245 			throw megaglest_runtime_error("No tile-sets were found!");
5246 		}
5247 		tilesetFiles= results;
5248 		std::for_each(results.begin(), results.end(), FormatString());
5249 
5250 		listBoxTileset.setItems(results);
5251 	}
5252 	catch(const std::exception &ex) {
5253 		char szBuf[8096]="";
5254 		snprintf(szBuf,8096,"In [%s::%s %d]\nError detected:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what());
5255 		SystemFlags::OutputDebug(SystemFlags::debugError,szBuf);
5256 		if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf);
5257 
5258 		throw megaglest_runtime_error(szBuf);
5259 	}
5260 
5261 }
5262 
5263 }}//end namespace
5264